PackageManagerService.java revision 183501e1aaee9584f8f0c6ea2d983e3fc17429d1
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.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 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_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 71import static android.system.OsConstants.O_CREAT; 72import static android.system.OsConstants.O_RDWR; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 77import static com.android.internal.util.ArrayUtils.appendInt; 78import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 87 88import android.Manifest; 89import android.app.ActivityManager; 90import android.app.ActivityManagerNative; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.admin.IDevicePolicyManager; 94import android.app.backup.IBackupManager; 95import android.app.usage.UsageStats; 96import android.app.usage.UsageStatsManager; 97import android.content.BroadcastReceiver; 98import android.content.ComponentName; 99import android.content.Context; 100import android.content.IIntentReceiver; 101import android.content.Intent; 102import android.content.IntentFilter; 103import android.content.IntentSender; 104import android.content.IntentSender.SendIntentException; 105import android.content.ServiceConnection; 106import android.content.pm.ActivityInfo; 107import android.content.pm.ApplicationInfo; 108import android.content.pm.FeatureInfo; 109import android.content.pm.IOnPermissionsChangeListener; 110import android.content.pm.IPackageDataObserver; 111import android.content.pm.IPackageDeleteObserver; 112import android.content.pm.IPackageDeleteObserver2; 113import android.content.pm.IPackageInstallObserver2; 114import android.content.pm.IPackageInstaller; 115import android.content.pm.IPackageManager; 116import android.content.pm.IPackageMoveObserver; 117import android.content.pm.IPackageStatsObserver; 118import android.content.pm.InstrumentationInfo; 119import android.content.pm.IntentFilterVerificationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageManagerInternal; 129import android.content.pm.PackageParser; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageStats; 134import android.content.pm.PackageUserState; 135import android.content.pm.ParceledListSlice; 136import android.content.pm.PermissionGroupInfo; 137import android.content.pm.PermissionInfo; 138import android.content.pm.ProviderInfo; 139import android.content.pm.ResolveInfo; 140import android.content.pm.ServiceInfo; 141import android.content.pm.Signature; 142import android.content.pm.UserInfo; 143import android.content.pm.VerificationParams; 144import android.content.pm.VerifierDeviceIdentity; 145import android.content.pm.VerifierInfo; 146import android.content.res.Resources; 147import android.hardware.display.DisplayManager; 148import android.net.Uri; 149import android.os.Debug; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.FileUtils; 156import android.os.Handler; 157import android.os.IBinder; 158import android.os.Looper; 159import android.os.Message; 160import android.os.Parcel; 161import android.os.ParcelFileDescriptor; 162import android.os.Process; 163import android.os.RemoteCallbackList; 164import android.os.RemoteException; 165import android.os.ResultReceiver; 166import android.os.SELinux; 167import android.os.ServiceManager; 168import android.os.SystemClock; 169import android.os.SystemProperties; 170import android.os.Trace; 171import android.os.UserHandle; 172import android.os.UserManager; 173import android.os.storage.IMountService; 174import android.os.storage.MountServiceInternal; 175import android.os.storage.StorageEventListener; 176import android.os.storage.StorageManager; 177import android.os.storage.VolumeInfo; 178import android.os.storage.VolumeRecord; 179import android.security.KeyStore; 180import android.security.SystemKeyStore; 181import android.system.ErrnoException; 182import android.system.Os; 183import android.system.StructStat; 184import android.text.TextUtils; 185import android.text.format.DateUtils; 186import android.util.ArrayMap; 187import android.util.ArraySet; 188import android.util.AtomicFile; 189import android.util.DisplayMetrics; 190import android.util.EventLog; 191import android.util.ExceptionUtils; 192import android.util.Log; 193import android.util.LogPrinter; 194import android.util.MathUtils; 195import android.util.PrintStreamPrinter; 196import android.util.Slog; 197import android.util.SparseArray; 198import android.util.SparseBooleanArray; 199import android.util.SparseIntArray; 200import android.util.Xml; 201import android.view.Display; 202 203import dalvik.system.DexFile; 204import dalvik.system.VMRuntime; 205 206import libcore.io.IoUtils; 207import libcore.util.EmptyArray; 208 209import com.android.internal.R; 210import com.android.internal.annotations.GuardedBy; 211import com.android.internal.app.IMediaContainerService; 212import com.android.internal.app.ResolverActivity; 213import com.android.internal.content.NativeLibraryHelper; 214import com.android.internal.content.PackageHelper; 215import com.android.internal.os.IParcelFileDescriptorFactory; 216import com.android.internal.os.SomeArgs; 217import com.android.internal.os.Zygote; 218import com.android.internal.util.ArrayUtils; 219import com.android.internal.util.FastPrintWriter; 220import com.android.internal.util.FastXmlSerializer; 221import com.android.internal.util.IndentingPrintWriter; 222import com.android.internal.util.Preconditions; 223import com.android.server.EventLogTags; 224import com.android.server.FgThread; 225import com.android.server.IntentResolver; 226import com.android.server.LocalServices; 227import com.android.server.ServiceThread; 228import com.android.server.SystemConfig; 229import com.android.server.Watchdog; 230import com.android.server.pm.PermissionsState.PermissionState; 231import com.android.server.pm.Settings.DatabaseVersion; 232import com.android.server.pm.Settings.VersionInfo; 233import com.android.server.storage.DeviceStorageMonitorInternal; 234 235import org.xmlpull.v1.XmlPullParser; 236import org.xmlpull.v1.XmlPullParserException; 237import org.xmlpull.v1.XmlSerializer; 238 239import java.io.BufferedInputStream; 240import java.io.BufferedOutputStream; 241import java.io.BufferedReader; 242import java.io.ByteArrayInputStream; 243import java.io.ByteArrayOutputStream; 244import java.io.File; 245import java.io.FileDescriptor; 246import java.io.FileNotFoundException; 247import java.io.FileOutputStream; 248import java.io.FileReader; 249import java.io.FilenameFilter; 250import java.io.IOException; 251import java.io.InputStream; 252import java.io.PrintWriter; 253import java.nio.charset.StandardCharsets; 254import java.security.NoSuchAlgorithmException; 255import java.security.PublicKey; 256import java.security.cert.CertificateEncodingException; 257import java.security.cert.CertificateException; 258import java.text.SimpleDateFormat; 259import java.util.ArrayList; 260import java.util.Arrays; 261import java.util.Collection; 262import java.util.Collections; 263import java.util.Comparator; 264import java.util.Date; 265import java.util.Iterator; 266import java.util.List; 267import java.util.Map; 268import java.util.Objects; 269import java.util.Set; 270import java.util.concurrent.CountDownLatch; 271import java.util.concurrent.TimeUnit; 272import java.util.concurrent.atomic.AtomicBoolean; 273import java.util.concurrent.atomic.AtomicInteger; 274import java.util.concurrent.atomic.AtomicLong; 275 276/** 277 * Keep track of all those .apks everywhere. 278 * 279 * This is very central to the platform's security; please run the unit 280 * tests whenever making modifications here: 281 * 282runtest -c android.content.pm.PackageManagerTests frameworks-core 283 * 284 * {@hide} 285 */ 286public class PackageManagerService extends IPackageManager.Stub { 287 static final String TAG = "PackageManager"; 288 static final boolean DEBUG_SETTINGS = false; 289 static final boolean DEBUG_PREFERRED = false; 290 static final boolean DEBUG_UPGRADE = false; 291 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 292 private static final boolean DEBUG_BACKUP = false; 293 private static final boolean DEBUG_INSTALL = false; 294 private static final boolean DEBUG_REMOVE = false; 295 private static final boolean DEBUG_BROADCASTS = false; 296 private static final boolean DEBUG_SHOW_INFO = false; 297 private static final boolean DEBUG_PACKAGE_INFO = false; 298 private static final boolean DEBUG_INTENT_MATCHING = false; 299 private static final boolean DEBUG_PACKAGE_SCANNING = false; 300 private static final boolean DEBUG_VERIFY = false; 301 private static final boolean DEBUG_DEXOPT = false; 302 private static final boolean DEBUG_ABI_SELECTION = false; 303 304 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 305 306 private static final int RADIO_UID = Process.PHONE_UID; 307 private static final int LOG_UID = Process.LOG_UID; 308 private static final int NFC_UID = Process.NFC_UID; 309 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 310 private static final int SHELL_UID = Process.SHELL_UID; 311 312 // Cap the size of permission trees that 3rd party apps can define 313 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 314 315 // Suffix used during package installation when copying/moving 316 // package apks to install directory. 317 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 318 319 static final int SCAN_NO_DEX = 1<<1; 320 static final int SCAN_FORCE_DEX = 1<<2; 321 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 322 static final int SCAN_NEW_INSTALL = 1<<4; 323 static final int SCAN_NO_PATHS = 1<<5; 324 static final int SCAN_UPDATE_TIME = 1<<6; 325 static final int SCAN_DEFER_DEX = 1<<7; 326 static final int SCAN_BOOTING = 1<<8; 327 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 328 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 329 static final int SCAN_REPLACING = 1<<11; 330 static final int SCAN_REQUIRE_KNOWN = 1<<12; 331 static final int SCAN_MOVE = 1<<13; 332 static final int SCAN_INITIAL = 1<<14; 333 334 static final int REMOVE_CHATTY = 1<<16; 335 336 private static final int[] EMPTY_INT_ARRAY = new int[0]; 337 338 /** 339 * Timeout (in milliseconds) after which the watchdog should declare that 340 * our handler thread is wedged. The usual default for such things is one 341 * minute but we sometimes do very lengthy I/O operations on this thread, 342 * such as installing multi-gigabyte applications, so ours needs to be longer. 343 */ 344 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 345 346 /** 347 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 348 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 349 * settings entry if available, otherwise we use the hardcoded default. If it's been 350 * more than this long since the last fstrim, we force one during the boot sequence. 351 * 352 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 353 * one gets run at the next available charging+idle time. This final mandatory 354 * no-fstrim check kicks in only of the other scheduling criteria is never met. 355 */ 356 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 357 358 /** 359 * Whether verification is enabled by default. 360 */ 361 private static final boolean DEFAULT_VERIFY_ENABLE = true; 362 363 /** 364 * The default maximum time to wait for the verification agent to return in 365 * milliseconds. 366 */ 367 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 368 369 /** 370 * The default response for package verification timeout. 371 * 372 * This can be either PackageManager.VERIFICATION_ALLOW or 373 * PackageManager.VERIFICATION_REJECT. 374 */ 375 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 376 377 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 378 379 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 380 DEFAULT_CONTAINER_PACKAGE, 381 "com.android.defcontainer.DefaultContainerService"); 382 383 private static final String KILL_APP_REASON_GIDS_CHANGED = 384 "permission grant or revoke changed gids"; 385 386 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 387 "permissions revoked"; 388 389 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 390 391 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 392 393 /** Permission grant: not grant the permission. */ 394 private static final int GRANT_DENIED = 1; 395 396 /** Permission grant: grant the permission as an install permission. */ 397 private static final int GRANT_INSTALL = 2; 398 399 /** Permission grant: grant the permission as an install permission for a legacy app. */ 400 private static final int GRANT_INSTALL_LEGACY = 3; 401 402 /** Permission grant: grant the permission as a runtime one. */ 403 private static final int GRANT_RUNTIME = 4; 404 405 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 406 private static final int GRANT_UPGRADE = 5; 407 408 /** Canonical intent used to identify what counts as a "web browser" app */ 409 private static final Intent sBrowserIntent; 410 static { 411 sBrowserIntent = new Intent(); 412 sBrowserIntent.setAction(Intent.ACTION_VIEW); 413 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 414 sBrowserIntent.setData(Uri.parse("http:")); 415 } 416 417 final ServiceThread mHandlerThread; 418 419 final PackageHandler mHandler; 420 421 /** 422 * Messages for {@link #mHandler} that need to wait for system ready before 423 * being dispatched. 424 */ 425 private ArrayList<Message> mPostSystemReadyMessages; 426 427 final int mSdkVersion = Build.VERSION.SDK_INT; 428 429 final Context mContext; 430 final boolean mFactoryTest; 431 final boolean mOnlyCore; 432 final DisplayMetrics mMetrics; 433 final int mDefParseFlags; 434 final String[] mSeparateProcesses; 435 final boolean mIsUpgrade; 436 437 // This is where all application persistent data goes. 438 final File mAppDataDir; 439 440 // This is where all application persistent data goes for secondary users. 441 final File mUserAppDataDir; 442 443 /** The location for ASEC container files on internal storage. */ 444 final String mAsecInternalPath; 445 446 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 447 // LOCK HELD. Can be called with mInstallLock held. 448 @GuardedBy("mInstallLock") 449 final Installer mInstaller; 450 451 /** Directory where installed third-party apps stored */ 452 final File mAppInstallDir; 453 454 /** 455 * Directory to which applications installed internally have their 456 * 32 bit native libraries copied. 457 */ 458 private File mAppLib32InstallDir; 459 460 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 461 // apps. 462 final File mDrmAppPrivateInstallDir; 463 464 // ---------------------------------------------------------------- 465 466 // Lock for state used when installing and doing other long running 467 // operations. Methods that must be called with this lock held have 468 // the suffix "LI". 469 final Object mInstallLock = new Object(); 470 471 // ---------------------------------------------------------------- 472 473 // Keys are String (package name), values are Package. This also serves 474 // as the lock for the global state. Methods that must be called with 475 // this lock held have the prefix "LP". 476 @GuardedBy("mPackages") 477 final ArrayMap<String, PackageParser.Package> mPackages = 478 new ArrayMap<String, PackageParser.Package>(); 479 480 // Tracks available target package names -> overlay package paths. 481 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 482 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 483 484 /** 485 * Tracks new system packages [received in an OTA] that we expect to 486 * find updated user-installed versions. Keys are package name, values 487 * are package location. 488 */ 489 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 490 491 /** 492 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 493 */ 494 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 495 /** 496 * Whether or not system app permissions should be promoted from install to runtime. 497 */ 498 boolean mPromoteSystemApps; 499 500 final Settings mSettings; 501 boolean mRestoredSettings; 502 503 // System configuration read by SystemConfig. 504 final int[] mGlobalGids; 505 final SparseArray<ArraySet<String>> mSystemPermissions; 506 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 507 508 // If mac_permissions.xml was found for seinfo labeling. 509 boolean mFoundPolicyFile; 510 511 // If a recursive restorecon of /data/data/<pkg> is needed. 512 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 513 514 public static final class SharedLibraryEntry { 515 public final String path; 516 public final String apk; 517 518 SharedLibraryEntry(String _path, String _apk) { 519 path = _path; 520 apk = _apk; 521 } 522 } 523 524 // Currently known shared libraries. 525 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 526 new ArrayMap<String, SharedLibraryEntry>(); 527 528 // All available activities, for your resolving pleasure. 529 final ActivityIntentResolver mActivities = 530 new ActivityIntentResolver(); 531 532 // All available receivers, for your resolving pleasure. 533 final ActivityIntentResolver mReceivers = 534 new ActivityIntentResolver(); 535 536 // All available services, for your resolving pleasure. 537 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 538 539 // All available providers, for your resolving pleasure. 540 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 541 542 // Mapping from provider base names (first directory in content URI codePath) 543 // to the provider information. 544 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 545 new ArrayMap<String, PackageParser.Provider>(); 546 547 // Mapping from instrumentation class names to info about them. 548 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 549 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 550 551 // Mapping from permission names to info about them. 552 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 553 new ArrayMap<String, PackageParser.PermissionGroup>(); 554 555 // Packages whose data we have transfered into another package, thus 556 // should no longer exist. 557 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 558 559 // Broadcast actions that are only available to the system. 560 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 561 562 /** List of packages waiting for verification. */ 563 final SparseArray<PackageVerificationState> mPendingVerification 564 = new SparseArray<PackageVerificationState>(); 565 566 /** Set of packages associated with each app op permission. */ 567 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 568 569 final PackageInstallerService mInstallerService; 570 571 private final PackageDexOptimizer mPackageDexOptimizer; 572 573 private AtomicInteger mNextMoveId = new AtomicInteger(); 574 private final MoveCallbacks mMoveCallbacks; 575 576 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 577 578 // Cache of users who need badging. 579 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 580 581 /** Token for keys in mPendingVerification. */ 582 private int mPendingVerificationToken = 0; 583 584 volatile boolean mSystemReady; 585 volatile boolean mSafeMode; 586 volatile boolean mHasSystemUidErrors; 587 588 ApplicationInfo mAndroidApplication; 589 final ActivityInfo mResolveActivity = new ActivityInfo(); 590 final ResolveInfo mResolveInfo = new ResolveInfo(); 591 ComponentName mResolveComponentName; 592 PackageParser.Package mPlatformPackage; 593 ComponentName mCustomResolverComponentName; 594 595 boolean mResolverReplaced = false; 596 597 private final ComponentName mIntentFilterVerifierComponent; 598 private int mIntentFilterVerificationToken = 0; 599 600 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 601 = new SparseArray<IntentFilterVerificationState>(); 602 603 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 604 new DefaultPermissionGrantPolicy(this); 605 606 private static class IFVerificationParams { 607 PackageParser.Package pkg; 608 boolean replacing; 609 int userId; 610 int verifierUid; 611 612 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 613 int _userId, int _verifierUid) { 614 pkg = _pkg; 615 replacing = _replacing; 616 userId = _userId; 617 replacing = _replacing; 618 verifierUid = _verifierUid; 619 } 620 } 621 622 private interface IntentFilterVerifier<T extends IntentFilter> { 623 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 624 T filter, String packageName); 625 void startVerifications(int userId); 626 void receiveVerificationResponse(int verificationId); 627 } 628 629 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 630 private Context mContext; 631 private ComponentName mIntentFilterVerifierComponent; 632 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 633 634 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 635 mContext = context; 636 mIntentFilterVerifierComponent = verifierComponent; 637 } 638 639 private String getDefaultScheme() { 640 return IntentFilter.SCHEME_HTTPS; 641 } 642 643 @Override 644 public void startVerifications(int userId) { 645 // Launch verifications requests 646 int count = mCurrentIntentFilterVerifications.size(); 647 for (int n=0; n<count; n++) { 648 int verificationId = mCurrentIntentFilterVerifications.get(n); 649 final IntentFilterVerificationState ivs = 650 mIntentFilterVerificationStates.get(verificationId); 651 652 String packageName = ivs.getPackageName(); 653 654 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 655 final int filterCount = filters.size(); 656 ArraySet<String> domainsSet = new ArraySet<>(); 657 for (int m=0; m<filterCount; m++) { 658 PackageParser.ActivityIntentInfo filter = filters.get(m); 659 domainsSet.addAll(filter.getHostsList()); 660 } 661 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 662 synchronized (mPackages) { 663 if (mSettings.createIntentFilterVerificationIfNeededLPw( 664 packageName, domainsList) != null) { 665 scheduleWriteSettingsLocked(); 666 } 667 } 668 sendVerificationRequest(userId, verificationId, ivs); 669 } 670 mCurrentIntentFilterVerifications.clear(); 671 } 672 673 private void sendVerificationRequest(int userId, int verificationId, 674 IntentFilterVerificationState ivs) { 675 676 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 677 verificationIntent.putExtra( 678 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 679 verificationId); 680 verificationIntent.putExtra( 681 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 682 getDefaultScheme()); 683 verificationIntent.putExtra( 684 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 685 ivs.getHostsString()); 686 verificationIntent.putExtra( 687 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 688 ivs.getPackageName()); 689 verificationIntent.setComponent(mIntentFilterVerifierComponent); 690 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 691 692 UserHandle user = new UserHandle(userId); 693 mContext.sendBroadcastAsUser(verificationIntent, user); 694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 695 "Sending IntentFilter verification broadcast"); 696 } 697 698 public void receiveVerificationResponse(int verificationId) { 699 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 700 701 final boolean verified = ivs.isVerified(); 702 703 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 704 final int count = filters.size(); 705 if (DEBUG_DOMAIN_VERIFICATION) { 706 Slog.i(TAG, "Received verification response " + verificationId 707 + " for " + count + " filters, verified=" + verified); 708 } 709 for (int n=0; n<count; n++) { 710 PackageParser.ActivityIntentInfo filter = filters.get(n); 711 filter.setVerified(verified); 712 713 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 714 + " verified with result:" + verified + " and hosts:" 715 + ivs.getHostsString()); 716 } 717 718 mIntentFilterVerificationStates.remove(verificationId); 719 720 final String packageName = ivs.getPackageName(); 721 IntentFilterVerificationInfo ivi = null; 722 723 synchronized (mPackages) { 724 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 725 } 726 if (ivi == null) { 727 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 728 + verificationId + " packageName:" + packageName); 729 return; 730 } 731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 732 "Updating IntentFilterVerificationInfo for package " + packageName 733 +" verificationId:" + verificationId); 734 735 synchronized (mPackages) { 736 if (verified) { 737 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 738 } else { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 740 } 741 scheduleWriteSettingsLocked(); 742 743 final int userId = ivs.getUserId(); 744 if (userId != UserHandle.USER_ALL) { 745 final int userStatus = 746 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 747 748 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 749 boolean needUpdate = false; 750 751 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 752 // already been set by the User thru the Disambiguation dialog 753 switch (userStatus) { 754 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 755 if (verified) { 756 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 757 } else { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 759 } 760 needUpdate = true; 761 break; 762 763 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 764 if (verified) { 765 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 766 needUpdate = true; 767 } 768 break; 769 770 default: 771 // Nothing to do 772 } 773 774 if (needUpdate) { 775 mSettings.updateIntentFilterVerificationStatusLPw( 776 packageName, updatedStatus, userId); 777 scheduleWritePackageRestrictionsLocked(userId); 778 } 779 } 780 } 781 } 782 783 @Override 784 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 785 ActivityIntentInfo filter, String packageName) { 786 if (!hasValidDomains(filter)) { 787 return false; 788 } 789 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 790 if (ivs == null) { 791 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 792 packageName); 793 } 794 if (DEBUG_DOMAIN_VERIFICATION) { 795 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 796 } 797 ivs.addFilter(filter); 798 return true; 799 } 800 801 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 802 int userId, int verificationId, String packageName) { 803 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 804 verifierUid, userId, packageName); 805 ivs.setPendingState(); 806 synchronized (mPackages) { 807 mIntentFilterVerificationStates.append(verificationId, ivs); 808 mCurrentIntentFilterVerifications.add(verificationId); 809 } 810 return ivs; 811 } 812 } 813 814 private static boolean hasValidDomains(ActivityIntentInfo filter) { 815 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 816 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 817 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 818 } 819 820 private IntentFilterVerifier mIntentFilterVerifier; 821 822 // Set of pending broadcasts for aggregating enable/disable of components. 823 static class PendingPackageBroadcasts { 824 // for each user id, a map of <package name -> components within that package> 825 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 826 827 public PendingPackageBroadcasts() { 828 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 829 } 830 831 public ArrayList<String> get(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 833 return packages.get(packageName); 834 } 835 836 public void put(int userId, String packageName, ArrayList<String> components) { 837 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 838 packages.put(packageName, components); 839 } 840 841 public void remove(int userId, String packageName) { 842 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 843 if (packages != null) { 844 packages.remove(packageName); 845 } 846 } 847 848 public void remove(int userId) { 849 mUidMap.remove(userId); 850 } 851 852 public int userIdCount() { 853 return mUidMap.size(); 854 } 855 856 public int userIdAt(int n) { 857 return mUidMap.keyAt(n); 858 } 859 860 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 861 return mUidMap.get(userId); 862 } 863 864 public int size() { 865 // total number of pending broadcast entries across all userIds 866 int num = 0; 867 for (int i = 0; i< mUidMap.size(); i++) { 868 num += mUidMap.valueAt(i).size(); 869 } 870 return num; 871 } 872 873 public void clear() { 874 mUidMap.clear(); 875 } 876 877 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 878 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 879 if (map == null) { 880 map = new ArrayMap<String, ArrayList<String>>(); 881 mUidMap.put(userId, map); 882 } 883 return map; 884 } 885 } 886 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 887 888 // Service Connection to remote media container service to copy 889 // package uri's from external media onto secure containers 890 // or internal storage. 891 private IMediaContainerService mContainerService = null; 892 893 static final int SEND_PENDING_BROADCAST = 1; 894 static final int MCS_BOUND = 3; 895 static final int END_COPY = 4; 896 static final int INIT_COPY = 5; 897 static final int MCS_UNBIND = 6; 898 static final int START_CLEANING_PACKAGE = 7; 899 static final int FIND_INSTALL_LOC = 8; 900 static final int POST_INSTALL = 9; 901 static final int MCS_RECONNECT = 10; 902 static final int MCS_GIVE_UP = 11; 903 static final int UPDATED_MEDIA_STATUS = 12; 904 static final int WRITE_SETTINGS = 13; 905 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 906 static final int PACKAGE_VERIFIED = 15; 907 static final int CHECK_PENDING_VERIFICATION = 16; 908 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 909 static final int INTENT_FILTER_VERIFIED = 18; 910 911 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 912 913 // Delay time in millisecs 914 static final int BROADCAST_DELAY = 10 * 1000; 915 916 static UserManagerService sUserManager; 917 918 // Stores a list of users whose package restrictions file needs to be updated 919 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 920 921 final private DefaultContainerConnection mDefContainerConn = 922 new DefaultContainerConnection(); 923 class DefaultContainerConnection implements ServiceConnection { 924 public void onServiceConnected(ComponentName name, IBinder service) { 925 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 926 IMediaContainerService imcs = 927 IMediaContainerService.Stub.asInterface(service); 928 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 929 } 930 931 public void onServiceDisconnected(ComponentName name) { 932 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 933 } 934 } 935 936 // Recordkeeping of restore-after-install operations that are currently in flight 937 // between the Package Manager and the Backup Manager 938 class PostInstallData { 939 public InstallArgs args; 940 public PackageInstalledInfo res; 941 942 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 943 args = _a; 944 res = _r; 945 } 946 } 947 948 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 949 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 950 951 // XML tags for backup/restore of various bits of state 952 private static final String TAG_PREFERRED_BACKUP = "pa"; 953 private static final String TAG_DEFAULT_APPS = "da"; 954 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 955 956 final String mRequiredVerifierPackage; 957 final String mRequiredInstallerPackage; 958 959 private final PackageUsage mPackageUsage = new PackageUsage(); 960 961 private class PackageUsage { 962 private static final int WRITE_INTERVAL 963 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 964 965 private final Object mFileLock = new Object(); 966 private final AtomicLong mLastWritten = new AtomicLong(0); 967 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 968 969 private boolean mIsHistoricalPackageUsageAvailable = true; 970 971 boolean isHistoricalPackageUsageAvailable() { 972 return mIsHistoricalPackageUsageAvailable; 973 } 974 975 void write(boolean force) { 976 if (force) { 977 writeInternal(); 978 return; 979 } 980 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 981 && !DEBUG_DEXOPT) { 982 return; 983 } 984 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 985 new Thread("PackageUsage_DiskWriter") { 986 @Override 987 public void run() { 988 try { 989 writeInternal(); 990 } finally { 991 mBackgroundWriteRunning.set(false); 992 } 993 } 994 }.start(); 995 } 996 } 997 998 private void writeInternal() { 999 synchronized (mPackages) { 1000 synchronized (mFileLock) { 1001 AtomicFile file = getFile(); 1002 FileOutputStream f = null; 1003 try { 1004 f = file.startWrite(); 1005 BufferedOutputStream out = new BufferedOutputStream(f); 1006 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1007 StringBuilder sb = new StringBuilder(); 1008 for (PackageParser.Package pkg : mPackages.values()) { 1009 if (pkg.mLastPackageUsageTimeInMills == 0) { 1010 continue; 1011 } 1012 sb.setLength(0); 1013 sb.append(pkg.packageName); 1014 sb.append(' '); 1015 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1016 sb.append('\n'); 1017 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1018 } 1019 out.flush(); 1020 file.finishWrite(f); 1021 } catch (IOException e) { 1022 if (f != null) { 1023 file.failWrite(f); 1024 } 1025 Log.e(TAG, "Failed to write package usage times", e); 1026 } 1027 } 1028 } 1029 mLastWritten.set(SystemClock.elapsedRealtime()); 1030 } 1031 1032 void readLP() { 1033 synchronized (mFileLock) { 1034 AtomicFile file = getFile(); 1035 BufferedInputStream in = null; 1036 try { 1037 in = new BufferedInputStream(file.openRead()); 1038 StringBuffer sb = new StringBuffer(); 1039 while (true) { 1040 String packageName = readToken(in, sb, ' '); 1041 if (packageName == null) { 1042 break; 1043 } 1044 String timeInMillisString = readToken(in, sb, '\n'); 1045 if (timeInMillisString == null) { 1046 throw new IOException("Failed to find last usage time for package " 1047 + packageName); 1048 } 1049 PackageParser.Package pkg = mPackages.get(packageName); 1050 if (pkg == null) { 1051 continue; 1052 } 1053 long timeInMillis; 1054 try { 1055 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1056 } catch (NumberFormatException e) { 1057 throw new IOException("Failed to parse " + timeInMillisString 1058 + " as a long.", e); 1059 } 1060 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1061 } 1062 } catch (FileNotFoundException expected) { 1063 mIsHistoricalPackageUsageAvailable = false; 1064 } catch (IOException e) { 1065 Log.w(TAG, "Failed to read package usage times", e); 1066 } finally { 1067 IoUtils.closeQuietly(in); 1068 } 1069 } 1070 mLastWritten.set(SystemClock.elapsedRealtime()); 1071 } 1072 1073 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1074 throws IOException { 1075 sb.setLength(0); 1076 while (true) { 1077 int ch = in.read(); 1078 if (ch == -1) { 1079 if (sb.length() == 0) { 1080 return null; 1081 } 1082 throw new IOException("Unexpected EOF"); 1083 } 1084 if (ch == endOfToken) { 1085 return sb.toString(); 1086 } 1087 sb.append((char)ch); 1088 } 1089 } 1090 1091 private AtomicFile getFile() { 1092 File dataDir = Environment.getDataDirectory(); 1093 File systemDir = new File(dataDir, "system"); 1094 File fname = new File(systemDir, "package-usage.list"); 1095 return new AtomicFile(fname); 1096 } 1097 } 1098 1099 class PackageHandler extends Handler { 1100 private boolean mBound = false; 1101 final ArrayList<HandlerParams> mPendingInstalls = 1102 new ArrayList<HandlerParams>(); 1103 1104 private boolean connectToService() { 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1106 " DefaultContainerService"); 1107 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1110 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 mBound = true; 1113 return true; 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 return false; 1117 } 1118 1119 private void disconnectService() { 1120 mContainerService = null; 1121 mBound = false; 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1123 mContext.unbindService(mDefContainerConn); 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } 1126 1127 PackageHandler(Looper looper) { 1128 super(looper); 1129 } 1130 1131 public void handleMessage(Message msg) { 1132 try { 1133 doHandleMessage(msg); 1134 } finally { 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1136 } 1137 } 1138 1139 void doHandleMessage(Message msg) { 1140 switch (msg.what) { 1141 case INIT_COPY: { 1142 HandlerParams params = (HandlerParams) msg.obj; 1143 int idx = mPendingInstalls.size(); 1144 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1145 // If a bind was already initiated we dont really 1146 // need to do anything. The pending install 1147 // will be processed later on. 1148 if (!mBound) { 1149 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1150 System.identityHashCode(mHandler)); 1151 // If this is the only one pending we might 1152 // have to bind to the service again. 1153 if (!connectToService()) { 1154 Slog.e(TAG, "Failed to bind to media container service"); 1155 params.serviceError(); 1156 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1157 System.identityHashCode(mHandler)); 1158 if (params.traceMethod != null) { 1159 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1160 params.traceCookie); 1161 } 1162 return; 1163 } else { 1164 // Once we bind to the service, the first 1165 // pending request will be processed. 1166 mPendingInstalls.add(idx, params); 1167 } 1168 } else { 1169 mPendingInstalls.add(idx, params); 1170 // Already bound to the service. Just make 1171 // sure we trigger off processing the first request. 1172 if (idx == 0) { 1173 mHandler.sendEmptyMessage(MCS_BOUND); 1174 } 1175 } 1176 break; 1177 } 1178 case MCS_BOUND: { 1179 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1180 if (msg.obj != null) { 1181 mContainerService = (IMediaContainerService) msg.obj; 1182 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1183 System.identityHashCode(mHandler)); 1184 } 1185 if (mContainerService == null) { 1186 if (!mBound) { 1187 // Something seriously wrong since we are not bound and we are not 1188 // waiting for connection. Bail out. 1189 Slog.e(TAG, "Cannot bind to media container service"); 1190 for (HandlerParams params : mPendingInstalls) { 1191 // Indicate service bind error 1192 params.serviceError(); 1193 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1194 System.identityHashCode(params)); 1195 if (params.traceMethod != null) { 1196 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1197 params.traceMethod, params.traceCookie); 1198 } 1199 return; 1200 } 1201 mPendingInstalls.clear(); 1202 } else { 1203 Slog.w(TAG, "Waiting to connect to media container service"); 1204 } 1205 } else if (mPendingInstalls.size() > 0) { 1206 HandlerParams params = mPendingInstalls.get(0); 1207 if (params != null) { 1208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1209 System.identityHashCode(params)); 1210 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1211 if (params.startCopy()) { 1212 // We are done... look for more work or to 1213 // go idle. 1214 if (DEBUG_SD_INSTALL) Log.i(TAG, 1215 "Checking for more work or unbind..."); 1216 // Delete pending install 1217 if (mPendingInstalls.size() > 0) { 1218 mPendingInstalls.remove(0); 1219 } 1220 if (mPendingInstalls.size() == 0) { 1221 if (mBound) { 1222 if (DEBUG_SD_INSTALL) Log.i(TAG, 1223 "Posting delayed MCS_UNBIND"); 1224 removeMessages(MCS_UNBIND); 1225 Message ubmsg = obtainMessage(MCS_UNBIND); 1226 // Unbind after a little delay, to avoid 1227 // continual thrashing. 1228 sendMessageDelayed(ubmsg, 10000); 1229 } 1230 } else { 1231 // There are more pending requests in queue. 1232 // Just post MCS_BOUND message to trigger processing 1233 // of next pending install. 1234 if (DEBUG_SD_INSTALL) Log.i(TAG, 1235 "Posting MCS_BOUND for next work"); 1236 mHandler.sendEmptyMessage(MCS_BOUND); 1237 } 1238 } 1239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1240 } 1241 } else { 1242 // Should never happen ideally. 1243 Slog.w(TAG, "Empty queue"); 1244 } 1245 break; 1246 } 1247 case MCS_RECONNECT: { 1248 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1249 if (mPendingInstalls.size() > 0) { 1250 if (mBound) { 1251 disconnectService(); 1252 } 1253 if (!connectToService()) { 1254 Slog.e(TAG, "Failed to bind to media container service"); 1255 for (HandlerParams params : mPendingInstalls) { 1256 // Indicate service bind error 1257 params.serviceError(); 1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1259 System.identityHashCode(params)); 1260 } 1261 mPendingInstalls.clear(); 1262 } 1263 } 1264 break; 1265 } 1266 case MCS_UNBIND: { 1267 // If there is no actual work left, then time to unbind. 1268 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1269 1270 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1271 if (mBound) { 1272 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1273 1274 disconnectService(); 1275 } 1276 } else if (mPendingInstalls.size() > 0) { 1277 // There are more pending requests in queue. 1278 // Just post MCS_BOUND message to trigger processing 1279 // of next pending install. 1280 mHandler.sendEmptyMessage(MCS_BOUND); 1281 } 1282 1283 break; 1284 } 1285 case MCS_GIVE_UP: { 1286 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1287 HandlerParams params = mPendingInstalls.remove(0); 1288 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1289 System.identityHashCode(params)); 1290 break; 1291 } 1292 case SEND_PENDING_BROADCAST: { 1293 String packages[]; 1294 ArrayList<String> components[]; 1295 int size = 0; 1296 int uids[]; 1297 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1298 synchronized (mPackages) { 1299 if (mPendingBroadcasts == null) { 1300 return; 1301 } 1302 size = mPendingBroadcasts.size(); 1303 if (size <= 0) { 1304 // Nothing to be done. Just return 1305 return; 1306 } 1307 packages = new String[size]; 1308 components = new ArrayList[size]; 1309 uids = new int[size]; 1310 int i = 0; // filling out the above arrays 1311 1312 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1313 int packageUserId = mPendingBroadcasts.userIdAt(n); 1314 Iterator<Map.Entry<String, ArrayList<String>>> it 1315 = mPendingBroadcasts.packagesForUserId(packageUserId) 1316 .entrySet().iterator(); 1317 while (it.hasNext() && i < size) { 1318 Map.Entry<String, ArrayList<String>> ent = it.next(); 1319 packages[i] = ent.getKey(); 1320 components[i] = ent.getValue(); 1321 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1322 uids[i] = (ps != null) 1323 ? UserHandle.getUid(packageUserId, ps.appId) 1324 : -1; 1325 i++; 1326 } 1327 } 1328 size = i; 1329 mPendingBroadcasts.clear(); 1330 } 1331 // Send broadcasts 1332 for (int i = 0; i < size; i++) { 1333 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1334 } 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 break; 1337 } 1338 case START_CLEANING_PACKAGE: { 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1340 final String packageName = (String)msg.obj; 1341 final int userId = msg.arg1; 1342 final boolean andCode = msg.arg2 != 0; 1343 synchronized (mPackages) { 1344 if (userId == UserHandle.USER_ALL) { 1345 int[] users = sUserManager.getUserIds(); 1346 for (int user : users) { 1347 mSettings.addPackageToCleanLPw( 1348 new PackageCleanItem(user, packageName, andCode)); 1349 } 1350 } else { 1351 mSettings.addPackageToCleanLPw( 1352 new PackageCleanItem(userId, packageName, andCode)); 1353 } 1354 } 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1356 startCleaningPackages(); 1357 } break; 1358 case POST_INSTALL: { 1359 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1360 PostInstallData data = mRunningInstalls.get(msg.arg1); 1361 mRunningInstalls.delete(msg.arg1); 1362 boolean deleteOld = false; 1363 1364 if (data != null) { 1365 InstallArgs args = data.args; 1366 PackageInstalledInfo res = data.res; 1367 1368 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1369 final String packageName = res.pkg.applicationInfo.packageName; 1370 res.removedInfo.sendBroadcast(false, true, false); 1371 Bundle extras = new Bundle(1); 1372 extras.putInt(Intent.EXTRA_UID, res.uid); 1373 1374 // Now that we successfully installed the package, grant runtime 1375 // permissions if requested before broadcasting the install. 1376 if ((args.installFlags 1377 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1378 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1379 args.installGrantPermissions); 1380 } 1381 1382 // Determine the set of users who are adding this 1383 // package for the first time vs. those who are seeing 1384 // an update. 1385 int[] firstUsers; 1386 int[] updateUsers = new int[0]; 1387 if (res.origUsers == null || res.origUsers.length == 0) { 1388 firstUsers = res.newUsers; 1389 } else { 1390 firstUsers = new int[0]; 1391 for (int i=0; i<res.newUsers.length; i++) { 1392 int user = res.newUsers[i]; 1393 boolean isNew = true; 1394 for (int j=0; j<res.origUsers.length; j++) { 1395 if (res.origUsers[j] == user) { 1396 isNew = false; 1397 break; 1398 } 1399 } 1400 if (isNew) { 1401 int[] newFirst = new int[firstUsers.length+1]; 1402 System.arraycopy(firstUsers, 0, newFirst, 0, 1403 firstUsers.length); 1404 newFirst[firstUsers.length] = user; 1405 firstUsers = newFirst; 1406 } else { 1407 int[] newUpdate = new int[updateUsers.length+1]; 1408 System.arraycopy(updateUsers, 0, newUpdate, 0, 1409 updateUsers.length); 1410 newUpdate[updateUsers.length] = user; 1411 updateUsers = newUpdate; 1412 } 1413 } 1414 } 1415 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1416 packageName, extras, null, null, firstUsers); 1417 final boolean update = res.removedInfo.removedPackage != null; 1418 if (update) { 1419 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1420 } 1421 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1422 packageName, extras, null, null, updateUsers); 1423 if (update) { 1424 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1425 packageName, extras, null, null, updateUsers); 1426 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1427 null, null, packageName, null, updateUsers); 1428 1429 // treat asec-hosted packages like removable media on upgrade 1430 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1431 if (DEBUG_INSTALL) { 1432 Slog.i(TAG, "upgrading pkg " + res.pkg 1433 + " is ASEC-hosted -> AVAILABLE"); 1434 } 1435 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1436 ArrayList<String> pkgList = new ArrayList<String>(1); 1437 pkgList.add(packageName); 1438 sendResourcesChangedBroadcast(true, true, 1439 pkgList,uidArray, null); 1440 } 1441 } 1442 if (res.removedInfo.args != null) { 1443 // Remove the replaced package's older resources safely now 1444 deleteOld = true; 1445 } 1446 1447 // If this app is a browser and it's newly-installed for some 1448 // users, clear any default-browser state in those users 1449 if (firstUsers.length > 0) { 1450 // the app's nature doesn't depend on the user, so we can just 1451 // check its browser nature in any user and generalize. 1452 if (packageIsBrowser(packageName, firstUsers[0])) { 1453 synchronized (mPackages) { 1454 for (int userId : firstUsers) { 1455 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1456 } 1457 } 1458 } 1459 } 1460 // Log current value of "unknown sources" setting 1461 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1462 getUnknownSourcesSettings()); 1463 } 1464 // Force a gc to clear up things 1465 Runtime.getRuntime().gc(); 1466 // We delete after a gc for applications on sdcard. 1467 if (deleteOld) { 1468 synchronized (mInstallLock) { 1469 res.removedInfo.args.doPostDeleteLI(true); 1470 } 1471 } 1472 if (args.observer != null) { 1473 try { 1474 Bundle extras = extrasForInstallResult(res); 1475 args.observer.onPackageInstalled(res.name, res.returnCode, 1476 res.returnMsg, extras); 1477 } catch (RemoteException e) { 1478 Slog.i(TAG, "Observer no longer exists."); 1479 } 1480 } 1481 if (args.traceMethod != null) { 1482 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1483 args.traceCookie); 1484 } 1485 return; 1486 } else { 1487 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1488 } 1489 1490 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1491 } break; 1492 case UPDATED_MEDIA_STATUS: { 1493 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1494 boolean reportStatus = msg.arg1 == 1; 1495 boolean doGc = msg.arg2 == 1; 1496 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1497 if (doGc) { 1498 // Force a gc to clear up stale containers. 1499 Runtime.getRuntime().gc(); 1500 } 1501 if (msg.obj != null) { 1502 @SuppressWarnings("unchecked") 1503 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1504 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1505 // Unload containers 1506 unloadAllContainers(args); 1507 } 1508 if (reportStatus) { 1509 try { 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1511 PackageHelper.getMountService().finishMediaUpdate(); 1512 } catch (RemoteException e) { 1513 Log.e(TAG, "MountService not running?"); 1514 } 1515 } 1516 } break; 1517 case WRITE_SETTINGS: { 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 removeMessages(WRITE_SETTINGS); 1521 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1522 mSettings.writeLPr(); 1523 mDirtyUsers.clear(); 1524 } 1525 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1526 } break; 1527 case WRITE_PACKAGE_RESTRICTIONS: { 1528 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1529 synchronized (mPackages) { 1530 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1531 for (int userId : mDirtyUsers) { 1532 mSettings.writePackageRestrictionsLPr(userId); 1533 } 1534 mDirtyUsers.clear(); 1535 } 1536 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1537 } break; 1538 case CHECK_PENDING_VERIFICATION: { 1539 final int verificationId = msg.arg1; 1540 final PackageVerificationState state = mPendingVerification.get(verificationId); 1541 1542 if ((state != null) && !state.timeoutExtended()) { 1543 final InstallArgs args = state.getInstallArgs(); 1544 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1545 1546 Slog.i(TAG, "Verification timed out for " + originUri); 1547 mPendingVerification.remove(verificationId); 1548 1549 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1550 1551 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1552 Slog.i(TAG, "Continuing with installation of " + originUri); 1553 state.setVerifierResponse(Binder.getCallingUid(), 1554 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1555 broadcastPackageVerified(verificationId, originUri, 1556 PackageManager.VERIFICATION_ALLOW, 1557 state.getInstallArgs().getUser()); 1558 try { 1559 ret = args.copyApk(mContainerService, true); 1560 } catch (RemoteException e) { 1561 Slog.e(TAG, "Could not contact the ContainerService"); 1562 } 1563 } else { 1564 broadcastPackageVerified(verificationId, originUri, 1565 PackageManager.VERIFICATION_REJECT, 1566 state.getInstallArgs().getUser()); 1567 } 1568 1569 Trace.asyncTraceEnd( 1570 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1571 1572 processPendingInstall(args, ret); 1573 mHandler.sendEmptyMessage(MCS_UNBIND); 1574 } 1575 break; 1576 } 1577 case PACKAGE_VERIFIED: { 1578 final int verificationId = msg.arg1; 1579 1580 final PackageVerificationState state = mPendingVerification.get(verificationId); 1581 if (state == null) { 1582 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1583 break; 1584 } 1585 1586 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1587 1588 state.setVerifierResponse(response.callerUid, response.code); 1589 1590 if (state.isVerificationComplete()) { 1591 mPendingVerification.remove(verificationId); 1592 1593 final InstallArgs args = state.getInstallArgs(); 1594 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1595 1596 int ret; 1597 if (state.isInstallAllowed()) { 1598 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1599 broadcastPackageVerified(verificationId, originUri, 1600 response.code, state.getInstallArgs().getUser()); 1601 try { 1602 ret = args.copyApk(mContainerService, true); 1603 } catch (RemoteException e) { 1604 Slog.e(TAG, "Could not contact the ContainerService"); 1605 } 1606 } else { 1607 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1608 } 1609 1610 Trace.asyncTraceEnd( 1611 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1612 1613 processPendingInstall(args, ret); 1614 mHandler.sendEmptyMessage(MCS_UNBIND); 1615 } 1616 1617 break; 1618 } 1619 case START_INTENT_FILTER_VERIFICATIONS: { 1620 IFVerificationParams params = (IFVerificationParams) msg.obj; 1621 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1622 params.replacing, params.pkg); 1623 break; 1624 } 1625 case INTENT_FILTER_VERIFIED: { 1626 final int verificationId = msg.arg1; 1627 1628 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1629 verificationId); 1630 if (state == null) { 1631 Slog.w(TAG, "Invalid IntentFilter verification token " 1632 + verificationId + " received"); 1633 break; 1634 } 1635 1636 final int userId = state.getUserId(); 1637 1638 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1639 "Processing IntentFilter verification with token:" 1640 + verificationId + " and userId:" + userId); 1641 1642 final IntentFilterVerificationResponse response = 1643 (IntentFilterVerificationResponse) msg.obj; 1644 1645 state.setVerifierResponse(response.callerUid, response.code); 1646 1647 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1648 "IntentFilter verification with token:" + verificationId 1649 + " and userId:" + userId 1650 + " is settings verifier response with response code:" 1651 + response.code); 1652 1653 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1654 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1655 + response.getFailedDomainsString()); 1656 } 1657 1658 if (state.isVerificationComplete()) { 1659 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1660 } else { 1661 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1662 "IntentFilter verification with token:" + verificationId 1663 + " was not said to be complete"); 1664 } 1665 1666 break; 1667 } 1668 } 1669 } 1670 } 1671 1672 private StorageEventListener mStorageListener = new StorageEventListener() { 1673 @Override 1674 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1675 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1676 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1677 final String volumeUuid = vol.getFsUuid(); 1678 1679 // Clean up any users or apps that were removed or recreated 1680 // while this volume was missing 1681 reconcileUsers(volumeUuid); 1682 reconcileApps(volumeUuid); 1683 1684 // Clean up any install sessions that expired or were 1685 // cancelled while this volume was missing 1686 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1687 1688 loadPrivatePackages(vol); 1689 1690 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1691 unloadPrivatePackages(vol); 1692 } 1693 } 1694 1695 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1696 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1697 updateExternalMediaStatus(true, false); 1698 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1699 updateExternalMediaStatus(false, false); 1700 } 1701 } 1702 } 1703 1704 @Override 1705 public void onVolumeForgotten(String fsUuid) { 1706 if (TextUtils.isEmpty(fsUuid)) { 1707 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1708 return; 1709 } 1710 1711 // Remove any apps installed on the forgotten volume 1712 synchronized (mPackages) { 1713 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1714 for (PackageSetting ps : packages) { 1715 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1716 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1717 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1718 } 1719 1720 mSettings.onVolumeForgotten(fsUuid); 1721 mSettings.writeLPr(); 1722 } 1723 } 1724 }; 1725 1726 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1727 String[] grantedPermissions) { 1728 if (userId >= UserHandle.USER_SYSTEM) { 1729 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1730 } else if (userId == UserHandle.USER_ALL) { 1731 final int[] userIds; 1732 synchronized (mPackages) { 1733 userIds = UserManagerService.getInstance().getUserIds(); 1734 } 1735 for (int someUserId : userIds) { 1736 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1737 } 1738 } 1739 1740 // We could have touched GID membership, so flush out packages.list 1741 synchronized (mPackages) { 1742 mSettings.writePackageListLPr(); 1743 } 1744 } 1745 1746 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1747 String[] grantedPermissions) { 1748 SettingBase sb = (SettingBase) pkg.mExtras; 1749 if (sb == null) { 1750 return; 1751 } 1752 1753 PermissionsState permissionsState = sb.getPermissionsState(); 1754 1755 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1756 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1757 1758 synchronized (mPackages) { 1759 for (String permission : pkg.requestedPermissions) { 1760 BasePermission bp = mSettings.mPermissions.get(permission); 1761 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1762 && (grantedPermissions == null 1763 || ArrayUtils.contains(grantedPermissions, permission))) { 1764 final int flags = permissionsState.getPermissionFlags(permission, userId); 1765 // Installer cannot change immutable permissions. 1766 if ((flags & immutableFlags) == 0) { 1767 grantRuntimePermission(pkg.packageName, permission, userId); 1768 } 1769 } 1770 } 1771 } 1772 } 1773 1774 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1775 Bundle extras = null; 1776 switch (res.returnCode) { 1777 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1778 extras = new Bundle(); 1779 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1780 res.origPermission); 1781 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1782 res.origPackage); 1783 break; 1784 } 1785 case PackageManager.INSTALL_SUCCEEDED: { 1786 extras = new Bundle(); 1787 extras.putBoolean(Intent.EXTRA_REPLACING, 1788 res.removedInfo != null && res.removedInfo.removedPackage != null); 1789 break; 1790 } 1791 } 1792 return extras; 1793 } 1794 1795 void scheduleWriteSettingsLocked() { 1796 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1797 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1798 } 1799 } 1800 1801 void scheduleWritePackageRestrictionsLocked(int userId) { 1802 if (!sUserManager.exists(userId)) return; 1803 mDirtyUsers.add(userId); 1804 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1805 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1806 } 1807 } 1808 1809 public static PackageManagerService main(Context context, Installer installer, 1810 boolean factoryTest, boolean onlyCore) { 1811 PackageManagerService m = new PackageManagerService(context, installer, 1812 factoryTest, onlyCore); 1813 ServiceManager.addService("package", m); 1814 return m; 1815 } 1816 1817 static String[] splitString(String str, char sep) { 1818 int count = 1; 1819 int i = 0; 1820 while ((i=str.indexOf(sep, i)) >= 0) { 1821 count++; 1822 i++; 1823 } 1824 1825 String[] res = new String[count]; 1826 i=0; 1827 count = 0; 1828 int lastI=0; 1829 while ((i=str.indexOf(sep, i)) >= 0) { 1830 res[count] = str.substring(lastI, i); 1831 count++; 1832 i++; 1833 lastI = i; 1834 } 1835 res[count] = str.substring(lastI, str.length()); 1836 return res; 1837 } 1838 1839 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1840 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1841 Context.DISPLAY_SERVICE); 1842 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1843 } 1844 1845 public PackageManagerService(Context context, Installer installer, 1846 boolean factoryTest, boolean onlyCore) { 1847 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1848 SystemClock.uptimeMillis()); 1849 1850 if (mSdkVersion <= 0) { 1851 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1852 } 1853 1854 mContext = context; 1855 mFactoryTest = factoryTest; 1856 mOnlyCore = onlyCore; 1857 mMetrics = new DisplayMetrics(); 1858 mSettings = new Settings(mPackages); 1859 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1860 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1861 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1862 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1863 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1864 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1865 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1866 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1867 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1868 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1869 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1870 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1871 1872 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1873 if (separateProcesses != null && separateProcesses.length() > 0) { 1874 if ("*".equals(separateProcesses)) { 1875 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1876 mSeparateProcesses = null; 1877 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1878 } else { 1879 mDefParseFlags = 0; 1880 mSeparateProcesses = separateProcesses.split(","); 1881 Slog.w(TAG, "Running with debug.separate_processes: " 1882 + separateProcesses); 1883 } 1884 } else { 1885 mDefParseFlags = 0; 1886 mSeparateProcesses = null; 1887 } 1888 1889 mInstaller = installer; 1890 mPackageDexOptimizer = new PackageDexOptimizer(this); 1891 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1892 1893 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1894 FgThread.get().getLooper()); 1895 1896 getDefaultDisplayMetrics(context, mMetrics); 1897 1898 SystemConfig systemConfig = SystemConfig.getInstance(); 1899 mGlobalGids = systemConfig.getGlobalGids(); 1900 mSystemPermissions = systemConfig.getSystemPermissions(); 1901 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1902 1903 synchronized (mInstallLock) { 1904 // writer 1905 synchronized (mPackages) { 1906 mHandlerThread = new ServiceThread(TAG, 1907 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1908 mHandlerThread.start(); 1909 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1910 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1911 1912 File dataDir = Environment.getDataDirectory(); 1913 mAppDataDir = new File(dataDir, "data"); 1914 mAppInstallDir = new File(dataDir, "app"); 1915 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1916 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1917 mUserAppDataDir = new File(dataDir, "user"); 1918 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1919 1920 sUserManager = new UserManagerService(context, this, 1921 mInstallLock, mPackages); 1922 1923 // Propagate permission configuration in to package manager. 1924 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1925 = systemConfig.getPermissions(); 1926 for (int i=0; i<permConfig.size(); i++) { 1927 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1928 BasePermission bp = mSettings.mPermissions.get(perm.name); 1929 if (bp == null) { 1930 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1931 mSettings.mPermissions.put(perm.name, bp); 1932 } 1933 if (perm.gids != null) { 1934 bp.setGids(perm.gids, perm.perUser); 1935 } 1936 } 1937 1938 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1939 for (int i=0; i<libConfig.size(); i++) { 1940 mSharedLibraries.put(libConfig.keyAt(i), 1941 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1942 } 1943 1944 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1945 1946 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1947 1948 String customResolverActivity = Resources.getSystem().getString( 1949 R.string.config_customResolverActivity); 1950 if (TextUtils.isEmpty(customResolverActivity)) { 1951 customResolverActivity = null; 1952 } else { 1953 mCustomResolverComponentName = ComponentName.unflattenFromString( 1954 customResolverActivity); 1955 } 1956 1957 long startTime = SystemClock.uptimeMillis(); 1958 1959 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1960 startTime); 1961 1962 // Set flag to monitor and not change apk file paths when 1963 // scanning install directories. 1964 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1965 1966 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1967 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1968 1969 if (bootClassPath == null) { 1970 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1971 } 1972 1973 if (systemServerClassPath == null) { 1974 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1975 } 1976 1977 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1978 final String[] dexCodeInstructionSets = 1979 getDexCodeInstructionSets( 1980 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1981 1982 /** 1983 * Ensure all external libraries have had dexopt run on them. 1984 */ 1985 if (mSharedLibraries.size() > 0) { 1986 // NOTE: For now, we're compiling these system "shared libraries" 1987 // (and framework jars) into all available architectures. It's possible 1988 // to compile them only when we come across an app that uses them (there's 1989 // already logic for that in scanPackageLI) but that adds some complexity. 1990 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1991 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1992 final String lib = libEntry.path; 1993 if (lib == null) { 1994 continue; 1995 } 1996 1997 try { 1998 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1999 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2000 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2001 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2002 } 2003 } catch (FileNotFoundException e) { 2004 Slog.w(TAG, "Library not found: " + lib); 2005 } catch (IOException e) { 2006 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2007 + e.getMessage()); 2008 } 2009 } 2010 } 2011 } 2012 2013 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2014 2015 final VersionInfo ver = mSettings.getInternalVersion(); 2016 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2017 // when upgrading from pre-M, promote system app permissions from install to runtime 2018 mPromoteSystemApps = 2019 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2020 2021 // save off the names of pre-existing system packages prior to scanning; we don't 2022 // want to automatically grant runtime permissions for new system apps 2023 if (mPromoteSystemApps) { 2024 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2025 while (pkgSettingIter.hasNext()) { 2026 PackageSetting ps = pkgSettingIter.next(); 2027 if (isSystemApp(ps)) { 2028 mExistingSystemPackages.add(ps.name); 2029 } 2030 } 2031 } 2032 2033 // Collect vendor overlay packages. 2034 // (Do this before scanning any apps.) 2035 // For security and version matching reason, only consider 2036 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2037 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2038 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2039 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2040 2041 // Find base frameworks (resource packages without code). 2042 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2043 | PackageParser.PARSE_IS_SYSTEM_DIR 2044 | PackageParser.PARSE_IS_PRIVILEGED, 2045 scanFlags | SCAN_NO_DEX, 0); 2046 2047 // Collected privileged system packages. 2048 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2049 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2050 | PackageParser.PARSE_IS_SYSTEM_DIR 2051 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2052 2053 // Collect ordinary system packages. 2054 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2055 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2056 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2057 2058 // Collect all vendor packages. 2059 File vendorAppDir = new File("/vendor/app"); 2060 try { 2061 vendorAppDir = vendorAppDir.getCanonicalFile(); 2062 } catch (IOException e) { 2063 // failed to look up canonical path, continue with original one 2064 } 2065 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2066 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2067 2068 // Collect all OEM packages. 2069 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2070 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2071 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2072 2073 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2074 mInstaller.moveFiles(); 2075 2076 // Prune any system packages that no longer exist. 2077 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2078 if (!mOnlyCore) { 2079 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2080 while (psit.hasNext()) { 2081 PackageSetting ps = psit.next(); 2082 2083 /* 2084 * If this is not a system app, it can't be a 2085 * disable system app. 2086 */ 2087 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2088 continue; 2089 } 2090 2091 /* 2092 * If the package is scanned, it's not erased. 2093 */ 2094 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2095 if (scannedPkg != null) { 2096 /* 2097 * If the system app is both scanned and in the 2098 * disabled packages list, then it must have been 2099 * added via OTA. Remove it from the currently 2100 * scanned package so the previously user-installed 2101 * application can be scanned. 2102 */ 2103 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2104 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2105 + ps.name + "; removing system app. Last known codePath=" 2106 + ps.codePathString + ", installStatus=" + ps.installStatus 2107 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2108 + scannedPkg.mVersionCode); 2109 removePackageLI(ps, true); 2110 mExpectingBetter.put(ps.name, ps.codePath); 2111 } 2112 2113 continue; 2114 } 2115 2116 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2117 psit.remove(); 2118 logCriticalInfo(Log.WARN, "System package " + ps.name 2119 + " no longer exists; wiping its data"); 2120 removeDataDirsLI(null, ps.name); 2121 } else { 2122 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2123 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2124 possiblyDeletedUpdatedSystemApps.add(ps.name); 2125 } 2126 } 2127 } 2128 } 2129 2130 //look for any incomplete package installations 2131 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2132 //clean up list 2133 for(int i = 0; i < deletePkgsList.size(); i++) { 2134 //clean up here 2135 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2136 } 2137 //delete tmp files 2138 deleteTempPackageFiles(); 2139 2140 // Remove any shared userIDs that have no associated packages 2141 mSettings.pruneSharedUsersLPw(); 2142 2143 if (!mOnlyCore) { 2144 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2145 SystemClock.uptimeMillis()); 2146 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2147 2148 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2149 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2150 2151 /** 2152 * Remove disable package settings for any updated system 2153 * apps that were removed via an OTA. If they're not a 2154 * previously-updated app, remove them completely. 2155 * Otherwise, just revoke their system-level permissions. 2156 */ 2157 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2158 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2159 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2160 2161 String msg; 2162 if (deletedPkg == null) { 2163 msg = "Updated system package " + deletedAppName 2164 + " no longer exists; wiping its data"; 2165 removeDataDirsLI(null, deletedAppName); 2166 } else { 2167 msg = "Updated system app + " + deletedAppName 2168 + " no longer present; removing system privileges for " 2169 + deletedAppName; 2170 2171 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2172 2173 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2174 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2175 } 2176 logCriticalInfo(Log.WARN, msg); 2177 } 2178 2179 /** 2180 * Make sure all system apps that we expected to appear on 2181 * the userdata partition actually showed up. If they never 2182 * appeared, crawl back and revive the system version. 2183 */ 2184 for (int i = 0; i < mExpectingBetter.size(); i++) { 2185 final String packageName = mExpectingBetter.keyAt(i); 2186 if (!mPackages.containsKey(packageName)) { 2187 final File scanFile = mExpectingBetter.valueAt(i); 2188 2189 logCriticalInfo(Log.WARN, "Expected better " + packageName 2190 + " but never showed up; reverting to system"); 2191 2192 final int reparseFlags; 2193 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2194 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2195 | PackageParser.PARSE_IS_SYSTEM_DIR 2196 | PackageParser.PARSE_IS_PRIVILEGED; 2197 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2198 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2199 | PackageParser.PARSE_IS_SYSTEM_DIR; 2200 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2201 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2202 | PackageParser.PARSE_IS_SYSTEM_DIR; 2203 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2204 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2205 | PackageParser.PARSE_IS_SYSTEM_DIR; 2206 } else { 2207 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2208 continue; 2209 } 2210 2211 mSettings.enableSystemPackageLPw(packageName); 2212 2213 try { 2214 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2215 } catch (PackageManagerException e) { 2216 Slog.e(TAG, "Failed to parse original system package: " 2217 + e.getMessage()); 2218 } 2219 } 2220 } 2221 } 2222 mExpectingBetter.clear(); 2223 2224 // Now that we know all of the shared libraries, update all clients to have 2225 // the correct library paths. 2226 updateAllSharedLibrariesLPw(); 2227 2228 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2229 // NOTE: We ignore potential failures here during a system scan (like 2230 // the rest of the commands above) because there's precious little we 2231 // can do about it. A settings error is reported, though. 2232 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2233 false /* boot complete */); 2234 } 2235 2236 // Now that we know all the packages we are keeping, 2237 // read and update their last usage times. 2238 mPackageUsage.readLP(); 2239 2240 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2241 SystemClock.uptimeMillis()); 2242 Slog.i(TAG, "Time to scan packages: " 2243 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2244 + " seconds"); 2245 2246 // If the platform SDK has changed since the last time we booted, 2247 // we need to re-grant app permission to catch any new ones that 2248 // appear. This is really a hack, and means that apps can in some 2249 // cases get permissions that the user didn't initially explicitly 2250 // allow... it would be nice to have some better way to handle 2251 // this situation. 2252 int updateFlags = UPDATE_PERMISSIONS_ALL; 2253 if (ver.sdkVersion != mSdkVersion) { 2254 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2255 + mSdkVersion + "; regranting permissions for internal storage"); 2256 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2257 } 2258 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2259 ver.sdkVersion = mSdkVersion; 2260 2261 // If this is the first boot or an update from pre-M, and it is a normal 2262 // boot, then we need to initialize the default preferred apps across 2263 // all defined users. 2264 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2265 for (UserInfo user : sUserManager.getUsers(true)) { 2266 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2267 applyFactoryDefaultBrowserLPw(user.id); 2268 primeDomainVerificationsLPw(user.id); 2269 } 2270 } 2271 2272 // If this is first boot after an OTA, and a normal boot, then 2273 // we need to clear code cache directories. 2274 if (mIsUpgrade && !onlyCore) { 2275 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2276 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2277 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2278 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2279 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2280 } 2281 } 2282 ver.fingerprint = Build.FINGERPRINT; 2283 } 2284 2285 checkDefaultBrowser(); 2286 2287 // clear only after permissions and other defaults have been updated 2288 mExistingSystemPackages.clear(); 2289 mPromoteSystemApps = false; 2290 2291 // All the changes are done during package scanning. 2292 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2293 2294 // can downgrade to reader 2295 mSettings.writeLPr(); 2296 2297 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2298 SystemClock.uptimeMillis()); 2299 2300 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2301 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2302 2303 mInstallerService = new PackageInstallerService(context, this); 2304 2305 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2306 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2307 mIntentFilterVerifierComponent); 2308 2309 } // synchronized (mPackages) 2310 } // synchronized (mInstallLock) 2311 2312 // Now after opening every single application zip, make sure they 2313 // are all flushed. Not really needed, but keeps things nice and 2314 // tidy. 2315 Runtime.getRuntime().gc(); 2316 2317 // The initial scanning above does many calls into installd while 2318 // holding the mPackages lock, but we're mostly interested in yelling 2319 // once we have a booted system. 2320 mInstaller.setWarnIfHeld(mPackages); 2321 2322 // Expose private service for system components to use. 2323 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2324 } 2325 2326 @Override 2327 public boolean isFirstBoot() { 2328 return !mRestoredSettings; 2329 } 2330 2331 @Override 2332 public boolean isOnlyCoreApps() { 2333 return mOnlyCore; 2334 } 2335 2336 @Override 2337 public boolean isUpgrade() { 2338 return mIsUpgrade; 2339 } 2340 2341 private String getRequiredVerifierLPr() { 2342 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2343 // We only care about verifier that's installed under system user. 2344 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2345 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2346 2347 String requiredVerifier = null; 2348 2349 final int N = receivers.size(); 2350 for (int i = 0; i < N; i++) { 2351 final ResolveInfo info = receivers.get(i); 2352 2353 if (info.activityInfo == null) { 2354 continue; 2355 } 2356 2357 final String packageName = info.activityInfo.packageName; 2358 2359 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2360 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2361 continue; 2362 } 2363 2364 if (requiredVerifier != null) { 2365 throw new RuntimeException("There can be only one required verifier"); 2366 } 2367 2368 requiredVerifier = packageName; 2369 } 2370 2371 return requiredVerifier; 2372 } 2373 2374 private String getRequiredInstallerLPr() { 2375 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2376 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2377 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2378 2379 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2380 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2381 2382 String requiredInstaller = null; 2383 2384 final int N = installers.size(); 2385 for (int i = 0; i < N; i++) { 2386 final ResolveInfo info = installers.get(i); 2387 final String packageName = info.activityInfo.packageName; 2388 2389 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2390 continue; 2391 } 2392 2393 if (requiredInstaller != null) { 2394 throw new RuntimeException("There must be one required installer"); 2395 } 2396 2397 requiredInstaller = packageName; 2398 } 2399 2400 if (requiredInstaller == null) { 2401 throw new RuntimeException("There must be one required installer"); 2402 } 2403 2404 return requiredInstaller; 2405 } 2406 2407 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2408 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2409 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2410 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2411 2412 ComponentName verifierComponentName = null; 2413 2414 int priority = -1000; 2415 final int N = receivers.size(); 2416 for (int i = 0; i < N; i++) { 2417 final ResolveInfo info = receivers.get(i); 2418 2419 if (info.activityInfo == null) { 2420 continue; 2421 } 2422 2423 final String packageName = info.activityInfo.packageName; 2424 2425 final PackageSetting ps = mSettings.mPackages.get(packageName); 2426 if (ps == null) { 2427 continue; 2428 } 2429 2430 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2431 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2432 continue; 2433 } 2434 2435 // Select the IntentFilterVerifier with the highest priority 2436 if (priority < info.priority) { 2437 priority = info.priority; 2438 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2439 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2440 + verifierComponentName + " with priority: " + info.priority); 2441 } 2442 } 2443 2444 return verifierComponentName; 2445 } 2446 2447 private void primeDomainVerificationsLPw(int userId) { 2448 if (DEBUG_DOMAIN_VERIFICATION) { 2449 Slog.d(TAG, "Priming domain verifications in user " + userId); 2450 } 2451 2452 SystemConfig systemConfig = SystemConfig.getInstance(); 2453 ArraySet<String> packages = systemConfig.getLinkedApps(); 2454 ArraySet<String> domains = new ArraySet<String>(); 2455 2456 for (String packageName : packages) { 2457 PackageParser.Package pkg = mPackages.get(packageName); 2458 if (pkg != null) { 2459 if (!pkg.isSystemApp()) { 2460 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2461 continue; 2462 } 2463 2464 domains.clear(); 2465 for (PackageParser.Activity a : pkg.activities) { 2466 for (ActivityIntentInfo filter : a.intents) { 2467 if (hasValidDomains(filter)) { 2468 domains.addAll(filter.getHostsList()); 2469 } 2470 } 2471 } 2472 2473 if (domains.size() > 0) { 2474 if (DEBUG_DOMAIN_VERIFICATION) { 2475 Slog.v(TAG, " + " + packageName); 2476 } 2477 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2478 // state w.r.t. the formal app-linkage "no verification attempted" state; 2479 // and then 'always' in the per-user state actually used for intent resolution. 2480 final IntentFilterVerificationInfo ivi; 2481 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2482 new ArrayList<String>(domains)); 2483 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2484 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2485 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2486 } else { 2487 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2488 + "' does not handle web links"); 2489 } 2490 } else { 2491 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2492 } 2493 } 2494 2495 scheduleWritePackageRestrictionsLocked(userId); 2496 scheduleWriteSettingsLocked(); 2497 } 2498 2499 private void applyFactoryDefaultBrowserLPw(int userId) { 2500 // The default browser app's package name is stored in a string resource, 2501 // with a product-specific overlay used for vendor customization. 2502 String browserPkg = mContext.getResources().getString( 2503 com.android.internal.R.string.default_browser); 2504 if (!TextUtils.isEmpty(browserPkg)) { 2505 // non-empty string => required to be a known package 2506 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2507 if (ps == null) { 2508 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2509 browserPkg = null; 2510 } else { 2511 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2512 } 2513 } 2514 2515 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2516 // default. If there's more than one, just leave everything alone. 2517 if (browserPkg == null) { 2518 calculateDefaultBrowserLPw(userId); 2519 } 2520 } 2521 2522 private void calculateDefaultBrowserLPw(int userId) { 2523 List<String> allBrowsers = resolveAllBrowserApps(userId); 2524 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2525 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2526 } 2527 2528 private List<String> resolveAllBrowserApps(int userId) { 2529 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2530 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2531 PackageManager.MATCH_ALL, userId); 2532 2533 final int count = list.size(); 2534 List<String> result = new ArrayList<String>(count); 2535 for (int i=0; i<count; i++) { 2536 ResolveInfo info = list.get(i); 2537 if (info.activityInfo == null 2538 || !info.handleAllWebDataURI 2539 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2540 || result.contains(info.activityInfo.packageName)) { 2541 continue; 2542 } 2543 result.add(info.activityInfo.packageName); 2544 } 2545 2546 return result; 2547 } 2548 2549 private boolean packageIsBrowser(String packageName, int userId) { 2550 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2551 PackageManager.MATCH_ALL, userId); 2552 final int N = list.size(); 2553 for (int i = 0; i < N; i++) { 2554 ResolveInfo info = list.get(i); 2555 if (packageName.equals(info.activityInfo.packageName)) { 2556 return true; 2557 } 2558 } 2559 return false; 2560 } 2561 2562 private void checkDefaultBrowser() { 2563 final int myUserId = UserHandle.myUserId(); 2564 final String packageName = getDefaultBrowserPackageName(myUserId); 2565 if (packageName != null) { 2566 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2567 if (info == null) { 2568 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2569 synchronized (mPackages) { 2570 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2571 } 2572 } 2573 } 2574 } 2575 2576 @Override 2577 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2578 throws RemoteException { 2579 try { 2580 return super.onTransact(code, data, reply, flags); 2581 } catch (RuntimeException e) { 2582 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2583 Slog.wtf(TAG, "Package Manager Crash", e); 2584 } 2585 throw e; 2586 } 2587 } 2588 2589 void cleanupInstallFailedPackage(PackageSetting ps) { 2590 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2591 2592 removeDataDirsLI(ps.volumeUuid, ps.name); 2593 if (ps.codePath != null) { 2594 if (ps.codePath.isDirectory()) { 2595 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2596 } else { 2597 ps.codePath.delete(); 2598 } 2599 } 2600 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2601 if (ps.resourcePath.isDirectory()) { 2602 FileUtils.deleteContents(ps.resourcePath); 2603 } 2604 ps.resourcePath.delete(); 2605 } 2606 mSettings.removePackageLPw(ps.name); 2607 } 2608 2609 static int[] appendInts(int[] cur, int[] add) { 2610 if (add == null) return cur; 2611 if (cur == null) return add; 2612 final int N = add.length; 2613 for (int i=0; i<N; i++) { 2614 cur = appendInt(cur, add[i]); 2615 } 2616 return cur; 2617 } 2618 2619 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2620 if (!sUserManager.exists(userId)) return null; 2621 final PackageSetting ps = (PackageSetting) p.mExtras; 2622 if (ps == null) { 2623 return null; 2624 } 2625 2626 final PermissionsState permissionsState = ps.getPermissionsState(); 2627 2628 final int[] gids = permissionsState.computeGids(userId); 2629 final Set<String> permissions = permissionsState.getPermissions(userId); 2630 final PackageUserState state = ps.readUserState(userId); 2631 2632 return PackageParser.generatePackageInfo(p, gids, flags, 2633 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2634 } 2635 2636 @Override 2637 public boolean isPackageFrozen(String packageName) { 2638 synchronized (mPackages) { 2639 final PackageSetting ps = mSettings.mPackages.get(packageName); 2640 if (ps != null) { 2641 return ps.frozen; 2642 } 2643 } 2644 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2645 return true; 2646 } 2647 2648 @Override 2649 public boolean isPackageAvailable(String packageName, int userId) { 2650 if (!sUserManager.exists(userId)) return false; 2651 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2652 synchronized (mPackages) { 2653 PackageParser.Package p = mPackages.get(packageName); 2654 if (p != null) { 2655 final PackageSetting ps = (PackageSetting) p.mExtras; 2656 if (ps != null) { 2657 final PackageUserState state = ps.readUserState(userId); 2658 if (state != null) { 2659 return PackageParser.isAvailable(state); 2660 } 2661 } 2662 } 2663 } 2664 return false; 2665 } 2666 2667 @Override 2668 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2669 if (!sUserManager.exists(userId)) return null; 2670 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2671 // reader 2672 synchronized (mPackages) { 2673 PackageParser.Package p = mPackages.get(packageName); 2674 if (DEBUG_PACKAGE_INFO) 2675 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2676 if (p != null) { 2677 return generatePackageInfo(p, flags, userId); 2678 } 2679 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2680 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2681 } 2682 } 2683 return null; 2684 } 2685 2686 @Override 2687 public String[] currentToCanonicalPackageNames(String[] names) { 2688 String[] out = new String[names.length]; 2689 // reader 2690 synchronized (mPackages) { 2691 for (int i=names.length-1; i>=0; i--) { 2692 PackageSetting ps = mSettings.mPackages.get(names[i]); 2693 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2694 } 2695 } 2696 return out; 2697 } 2698 2699 @Override 2700 public String[] canonicalToCurrentPackageNames(String[] names) { 2701 String[] out = new String[names.length]; 2702 // reader 2703 synchronized (mPackages) { 2704 for (int i=names.length-1; i>=0; i--) { 2705 String cur = mSettings.mRenamedPackages.get(names[i]); 2706 out[i] = cur != null ? cur : names[i]; 2707 } 2708 } 2709 return out; 2710 } 2711 2712 @Override 2713 public int getPackageUid(String packageName, int userId) { 2714 return getPackageUidEtc(packageName, 0, userId); 2715 } 2716 2717 @Override 2718 public int getPackageUidEtc(String packageName, int flags, int userId) { 2719 if (!sUserManager.exists(userId)) return -1; 2720 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2721 2722 // reader 2723 synchronized (mPackages) { 2724 final PackageParser.Package p = mPackages.get(packageName); 2725 if (p != null) { 2726 return UserHandle.getUid(userId, p.applicationInfo.uid); 2727 } 2728 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2729 final PackageSetting ps = mSettings.mPackages.get(packageName); 2730 if (ps != null) { 2731 return UserHandle.getUid(userId, ps.appId); 2732 } 2733 } 2734 } 2735 2736 return -1; 2737 } 2738 2739 @Override 2740 public int[] getPackageGids(String packageName, int userId) { 2741 return getPackageGidsEtc(packageName, 0, userId); 2742 } 2743 2744 @Override 2745 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2746 if (!sUserManager.exists(userId)) { 2747 return null; 2748 } 2749 2750 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2751 "getPackageGids"); 2752 2753 // reader 2754 synchronized (mPackages) { 2755 final PackageParser.Package p = mPackages.get(packageName); 2756 if (p != null) { 2757 PackageSetting ps = (PackageSetting) p.mExtras; 2758 return ps.getPermissionsState().computeGids(userId); 2759 } 2760 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2761 final PackageSetting ps = mSettings.mPackages.get(packageName); 2762 if (ps != null) { 2763 return ps.getPermissionsState().computeGids(userId); 2764 } 2765 } 2766 } 2767 2768 return null; 2769 } 2770 2771 static PermissionInfo generatePermissionInfo( 2772 BasePermission bp, int flags) { 2773 if (bp.perm != null) { 2774 return PackageParser.generatePermissionInfo(bp.perm, flags); 2775 } 2776 PermissionInfo pi = new PermissionInfo(); 2777 pi.name = bp.name; 2778 pi.packageName = bp.sourcePackage; 2779 pi.nonLocalizedLabel = bp.name; 2780 pi.protectionLevel = bp.protectionLevel; 2781 return pi; 2782 } 2783 2784 @Override 2785 public PermissionInfo getPermissionInfo(String name, int flags) { 2786 // reader 2787 synchronized (mPackages) { 2788 final BasePermission p = mSettings.mPermissions.get(name); 2789 if (p != null) { 2790 return generatePermissionInfo(p, flags); 2791 } 2792 return null; 2793 } 2794 } 2795 2796 @Override 2797 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2798 // reader 2799 synchronized (mPackages) { 2800 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2801 for (BasePermission p : mSettings.mPermissions.values()) { 2802 if (group == null) { 2803 if (p.perm == null || p.perm.info.group == null) { 2804 out.add(generatePermissionInfo(p, flags)); 2805 } 2806 } else { 2807 if (p.perm != null && group.equals(p.perm.info.group)) { 2808 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2809 } 2810 } 2811 } 2812 2813 if (out.size() > 0) { 2814 return out; 2815 } 2816 return mPermissionGroups.containsKey(group) ? out : null; 2817 } 2818 } 2819 2820 @Override 2821 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2822 // reader 2823 synchronized (mPackages) { 2824 return PackageParser.generatePermissionGroupInfo( 2825 mPermissionGroups.get(name), flags); 2826 } 2827 } 2828 2829 @Override 2830 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2831 // reader 2832 synchronized (mPackages) { 2833 final int N = mPermissionGroups.size(); 2834 ArrayList<PermissionGroupInfo> out 2835 = new ArrayList<PermissionGroupInfo>(N); 2836 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2837 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2838 } 2839 return out; 2840 } 2841 } 2842 2843 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2844 int userId) { 2845 if (!sUserManager.exists(userId)) return null; 2846 PackageSetting ps = mSettings.mPackages.get(packageName); 2847 if (ps != null) { 2848 if (ps.pkg == null) { 2849 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2850 flags, userId); 2851 if (pInfo != null) { 2852 return pInfo.applicationInfo; 2853 } 2854 return null; 2855 } 2856 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2857 ps.readUserState(userId), userId); 2858 } 2859 return null; 2860 } 2861 2862 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2863 int userId) { 2864 if (!sUserManager.exists(userId)) return null; 2865 PackageSetting ps = mSettings.mPackages.get(packageName); 2866 if (ps != null) { 2867 PackageParser.Package pkg = ps.pkg; 2868 if (pkg == null) { 2869 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2870 return null; 2871 } 2872 // Only data remains, so we aren't worried about code paths 2873 pkg = new PackageParser.Package(packageName); 2874 pkg.applicationInfo.packageName = packageName; 2875 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2876 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2877 pkg.applicationInfo.uid = ps.appId; 2878 pkg.applicationInfo.initForUser(userId); 2879 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2880 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2881 } 2882 return generatePackageInfo(pkg, flags, userId); 2883 } 2884 return null; 2885 } 2886 2887 @Override 2888 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2889 if (!sUserManager.exists(userId)) return null; 2890 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2891 // writer 2892 synchronized (mPackages) { 2893 PackageParser.Package p = mPackages.get(packageName); 2894 if (DEBUG_PACKAGE_INFO) Log.v( 2895 TAG, "getApplicationInfo " + packageName 2896 + ": " + p); 2897 if (p != null) { 2898 PackageSetting ps = mSettings.mPackages.get(packageName); 2899 if (ps == null) return null; 2900 // Note: isEnabledLP() does not apply here - always return info 2901 return PackageParser.generateApplicationInfo( 2902 p, flags, ps.readUserState(userId), userId); 2903 } 2904 if ("android".equals(packageName)||"system".equals(packageName)) { 2905 return mAndroidApplication; 2906 } 2907 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2908 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2909 } 2910 } 2911 return null; 2912 } 2913 2914 @Override 2915 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2916 final IPackageDataObserver observer) { 2917 mContext.enforceCallingOrSelfPermission( 2918 android.Manifest.permission.CLEAR_APP_CACHE, null); 2919 // Queue up an async operation since clearing cache may take a little while. 2920 mHandler.post(new Runnable() { 2921 public void run() { 2922 mHandler.removeCallbacks(this); 2923 int retCode = -1; 2924 synchronized (mInstallLock) { 2925 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2926 if (retCode < 0) { 2927 Slog.w(TAG, "Couldn't clear application caches"); 2928 } 2929 } 2930 if (observer != null) { 2931 try { 2932 observer.onRemoveCompleted(null, (retCode >= 0)); 2933 } catch (RemoteException e) { 2934 Slog.w(TAG, "RemoveException when invoking call back"); 2935 } 2936 } 2937 } 2938 }); 2939 } 2940 2941 @Override 2942 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2943 final IntentSender pi) { 2944 mContext.enforceCallingOrSelfPermission( 2945 android.Manifest.permission.CLEAR_APP_CACHE, null); 2946 // Queue up an async operation since clearing cache may take a little while. 2947 mHandler.post(new Runnable() { 2948 public void run() { 2949 mHandler.removeCallbacks(this); 2950 int retCode = -1; 2951 synchronized (mInstallLock) { 2952 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2953 if (retCode < 0) { 2954 Slog.w(TAG, "Couldn't clear application caches"); 2955 } 2956 } 2957 if(pi != null) { 2958 try { 2959 // Callback via pending intent 2960 int code = (retCode >= 0) ? 1 : 0; 2961 pi.sendIntent(null, code, null, 2962 null, null); 2963 } catch (SendIntentException e1) { 2964 Slog.i(TAG, "Failed to send pending intent"); 2965 } 2966 } 2967 } 2968 }); 2969 } 2970 2971 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2972 synchronized (mInstallLock) { 2973 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2974 throw new IOException("Failed to free enough space"); 2975 } 2976 } 2977 } 2978 2979 /** 2980 * Augment the given flags depending on current user running state. This is 2981 * purposefully done before acquiring {@link #mPackages} lock. 2982 */ 2983 private int augmentFlagsForUser(int flags, int userId) { 2984 // TODO: bring back once locking fixed 2985// final IActivityManager am = ActivityManagerNative.getDefault(); 2986// if (am == null) { 2987// // We must be early in boot, so the best we can do is assume the 2988// // user is fully running. 2989// return flags; 2990// } 2991// final long token = Binder.clearCallingIdentity(); 2992// try { 2993// if (am.isUserRunning(userId, ActivityManager.FLAG_WITH_AMNESIA)) { 2994// flags |= PackageManager.FLAG_USER_RUNNING_WITH_AMNESIA; 2995// } 2996// } catch (RemoteException e) { 2997// throw e.rethrowAsRuntimeException(); 2998// } finally { 2999// Binder.restoreCallingIdentity(token); 3000// } 3001 return flags; 3002 } 3003 3004 @Override 3005 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3006 if (!sUserManager.exists(userId)) return null; 3007 flags = augmentFlagsForUser(flags, userId); 3008 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3009 synchronized (mPackages) { 3010 PackageParser.Activity a = mActivities.mActivities.get(component); 3011 3012 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3013 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3014 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3015 if (ps == null) return null; 3016 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3017 userId); 3018 } 3019 if (mResolveComponentName.equals(component)) { 3020 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3021 new PackageUserState(), userId); 3022 } 3023 } 3024 return null; 3025 } 3026 3027 @Override 3028 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3029 String resolvedType) { 3030 synchronized (mPackages) { 3031 if (component.equals(mResolveComponentName)) { 3032 // The resolver supports EVERYTHING! 3033 return true; 3034 } 3035 PackageParser.Activity a = mActivities.mActivities.get(component); 3036 if (a == null) { 3037 return false; 3038 } 3039 for (int i=0; i<a.intents.size(); i++) { 3040 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3041 intent.getData(), intent.getCategories(), TAG) >= 0) { 3042 return true; 3043 } 3044 } 3045 return false; 3046 } 3047 } 3048 3049 @Override 3050 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3051 if (!sUserManager.exists(userId)) return null; 3052 flags = augmentFlagsForUser(flags, userId); 3053 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3054 synchronized (mPackages) { 3055 PackageParser.Activity a = mReceivers.mActivities.get(component); 3056 if (DEBUG_PACKAGE_INFO) Log.v( 3057 TAG, "getReceiverInfo " + component + ": " + a); 3058 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3059 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3060 if (ps == null) return null; 3061 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3062 userId); 3063 } 3064 } 3065 return null; 3066 } 3067 3068 @Override 3069 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3070 if (!sUserManager.exists(userId)) return null; 3071 flags = augmentFlagsForUser(flags, userId); 3072 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3073 synchronized (mPackages) { 3074 PackageParser.Service s = mServices.mServices.get(component); 3075 if (DEBUG_PACKAGE_INFO) Log.v( 3076 TAG, "getServiceInfo " + component + ": " + s); 3077 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3078 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3079 if (ps == null) return null; 3080 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3081 userId); 3082 } 3083 } 3084 return null; 3085 } 3086 3087 @Override 3088 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3089 if (!sUserManager.exists(userId)) return null; 3090 flags = augmentFlagsForUser(flags, userId); 3091 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3092 synchronized (mPackages) { 3093 PackageParser.Provider p = mProviders.mProviders.get(component); 3094 if (DEBUG_PACKAGE_INFO) Log.v( 3095 TAG, "getProviderInfo " + component + ": " + p); 3096 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3097 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3098 if (ps == null) return null; 3099 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3100 userId); 3101 } 3102 } 3103 return null; 3104 } 3105 3106 @Override 3107 public String[] getSystemSharedLibraryNames() { 3108 Set<String> libSet; 3109 synchronized (mPackages) { 3110 libSet = mSharedLibraries.keySet(); 3111 int size = libSet.size(); 3112 if (size > 0) { 3113 String[] libs = new String[size]; 3114 libSet.toArray(libs); 3115 return libs; 3116 } 3117 } 3118 return null; 3119 } 3120 3121 /** 3122 * @hide 3123 */ 3124 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3125 synchronized (mPackages) { 3126 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3127 if (lib != null && lib.apk != null) { 3128 return mPackages.get(lib.apk); 3129 } 3130 } 3131 return null; 3132 } 3133 3134 @Override 3135 public FeatureInfo[] getSystemAvailableFeatures() { 3136 Collection<FeatureInfo> featSet; 3137 synchronized (mPackages) { 3138 featSet = mAvailableFeatures.values(); 3139 int size = featSet.size(); 3140 if (size > 0) { 3141 FeatureInfo[] features = new FeatureInfo[size+1]; 3142 featSet.toArray(features); 3143 FeatureInfo fi = new FeatureInfo(); 3144 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3145 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3146 features[size] = fi; 3147 return features; 3148 } 3149 } 3150 return null; 3151 } 3152 3153 @Override 3154 public boolean hasSystemFeature(String name) { 3155 synchronized (mPackages) { 3156 return mAvailableFeatures.containsKey(name); 3157 } 3158 } 3159 3160 private void checkValidCaller(int uid, int userId) { 3161 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3162 return; 3163 3164 throw new SecurityException("Caller uid=" + uid 3165 + " is not privileged to communicate with user=" + userId); 3166 } 3167 3168 @Override 3169 public int checkPermission(String permName, String pkgName, int userId) { 3170 if (!sUserManager.exists(userId)) { 3171 return PackageManager.PERMISSION_DENIED; 3172 } 3173 3174 synchronized (mPackages) { 3175 final PackageParser.Package p = mPackages.get(pkgName); 3176 if (p != null && p.mExtras != null) { 3177 final PackageSetting ps = (PackageSetting) p.mExtras; 3178 final PermissionsState permissionsState = ps.getPermissionsState(); 3179 if (permissionsState.hasPermission(permName, userId)) { 3180 return PackageManager.PERMISSION_GRANTED; 3181 } 3182 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3183 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3184 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3185 return PackageManager.PERMISSION_GRANTED; 3186 } 3187 } 3188 } 3189 3190 return PackageManager.PERMISSION_DENIED; 3191 } 3192 3193 @Override 3194 public int checkUidPermission(String permName, int uid) { 3195 final int userId = UserHandle.getUserId(uid); 3196 3197 if (!sUserManager.exists(userId)) { 3198 return PackageManager.PERMISSION_DENIED; 3199 } 3200 3201 synchronized (mPackages) { 3202 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3203 if (obj != null) { 3204 final SettingBase ps = (SettingBase) obj; 3205 final PermissionsState permissionsState = ps.getPermissionsState(); 3206 if (permissionsState.hasPermission(permName, userId)) { 3207 return PackageManager.PERMISSION_GRANTED; 3208 } 3209 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3210 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3211 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3212 return PackageManager.PERMISSION_GRANTED; 3213 } 3214 } else { 3215 ArraySet<String> perms = mSystemPermissions.get(uid); 3216 if (perms != null) { 3217 if (perms.contains(permName)) { 3218 return PackageManager.PERMISSION_GRANTED; 3219 } 3220 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3221 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3222 return PackageManager.PERMISSION_GRANTED; 3223 } 3224 } 3225 } 3226 } 3227 3228 return PackageManager.PERMISSION_DENIED; 3229 } 3230 3231 @Override 3232 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3233 if (UserHandle.getCallingUserId() != userId) { 3234 mContext.enforceCallingPermission( 3235 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3236 "isPermissionRevokedByPolicy for user " + userId); 3237 } 3238 3239 if (checkPermission(permission, packageName, userId) 3240 == PackageManager.PERMISSION_GRANTED) { 3241 return false; 3242 } 3243 3244 final long identity = Binder.clearCallingIdentity(); 3245 try { 3246 final int flags = getPermissionFlags(permission, packageName, userId); 3247 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3248 } finally { 3249 Binder.restoreCallingIdentity(identity); 3250 } 3251 } 3252 3253 @Override 3254 public String getPermissionControllerPackageName() { 3255 synchronized (mPackages) { 3256 return mRequiredInstallerPackage; 3257 } 3258 } 3259 3260 /** 3261 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3262 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3263 * @param checkShell TODO(yamasani): 3264 * @param message the message to log on security exception 3265 */ 3266 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3267 boolean checkShell, String message) { 3268 if (userId < 0) { 3269 throw new IllegalArgumentException("Invalid userId " + userId); 3270 } 3271 if (checkShell) { 3272 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3273 } 3274 if (userId == UserHandle.getUserId(callingUid)) return; 3275 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3276 if (requireFullPermission) { 3277 mContext.enforceCallingOrSelfPermission( 3278 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3279 } else { 3280 try { 3281 mContext.enforceCallingOrSelfPermission( 3282 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3283 } catch (SecurityException se) { 3284 mContext.enforceCallingOrSelfPermission( 3285 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3286 } 3287 } 3288 } 3289 } 3290 3291 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3292 if (callingUid == Process.SHELL_UID) { 3293 if (userHandle >= 0 3294 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3295 throw new SecurityException("Shell does not have permission to access user " 3296 + userHandle); 3297 } else if (userHandle < 0) { 3298 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3299 + Debug.getCallers(3)); 3300 } 3301 } 3302 } 3303 3304 private BasePermission findPermissionTreeLP(String permName) { 3305 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3306 if (permName.startsWith(bp.name) && 3307 permName.length() > bp.name.length() && 3308 permName.charAt(bp.name.length()) == '.') { 3309 return bp; 3310 } 3311 } 3312 return null; 3313 } 3314 3315 private BasePermission checkPermissionTreeLP(String permName) { 3316 if (permName != null) { 3317 BasePermission bp = findPermissionTreeLP(permName); 3318 if (bp != null) { 3319 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3320 return bp; 3321 } 3322 throw new SecurityException("Calling uid " 3323 + Binder.getCallingUid() 3324 + " is not allowed to add to permission tree " 3325 + bp.name + " owned by uid " + bp.uid); 3326 } 3327 } 3328 throw new SecurityException("No permission tree found for " + permName); 3329 } 3330 3331 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3332 if (s1 == null) { 3333 return s2 == null; 3334 } 3335 if (s2 == null) { 3336 return false; 3337 } 3338 if (s1.getClass() != s2.getClass()) { 3339 return false; 3340 } 3341 return s1.equals(s2); 3342 } 3343 3344 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3345 if (pi1.icon != pi2.icon) return false; 3346 if (pi1.logo != pi2.logo) return false; 3347 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3348 if (!compareStrings(pi1.name, pi2.name)) return false; 3349 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3350 // We'll take care of setting this one. 3351 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3352 // These are not currently stored in settings. 3353 //if (!compareStrings(pi1.group, pi2.group)) return false; 3354 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3355 //if (pi1.labelRes != pi2.labelRes) return false; 3356 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3357 return true; 3358 } 3359 3360 int permissionInfoFootprint(PermissionInfo info) { 3361 int size = info.name.length(); 3362 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3363 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3364 return size; 3365 } 3366 3367 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3368 int size = 0; 3369 for (BasePermission perm : mSettings.mPermissions.values()) { 3370 if (perm.uid == tree.uid) { 3371 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3372 } 3373 } 3374 return size; 3375 } 3376 3377 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3378 // We calculate the max size of permissions defined by this uid and throw 3379 // if that plus the size of 'info' would exceed our stated maximum. 3380 if (tree.uid != Process.SYSTEM_UID) { 3381 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3382 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3383 throw new SecurityException("Permission tree size cap exceeded"); 3384 } 3385 } 3386 } 3387 3388 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3389 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3390 throw new SecurityException("Label must be specified in permission"); 3391 } 3392 BasePermission tree = checkPermissionTreeLP(info.name); 3393 BasePermission bp = mSettings.mPermissions.get(info.name); 3394 boolean added = bp == null; 3395 boolean changed = true; 3396 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3397 if (added) { 3398 enforcePermissionCapLocked(info, tree); 3399 bp = new BasePermission(info.name, tree.sourcePackage, 3400 BasePermission.TYPE_DYNAMIC); 3401 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3402 throw new SecurityException( 3403 "Not allowed to modify non-dynamic permission " 3404 + info.name); 3405 } else { 3406 if (bp.protectionLevel == fixedLevel 3407 && bp.perm.owner.equals(tree.perm.owner) 3408 && bp.uid == tree.uid 3409 && comparePermissionInfos(bp.perm.info, info)) { 3410 changed = false; 3411 } 3412 } 3413 bp.protectionLevel = fixedLevel; 3414 info = new PermissionInfo(info); 3415 info.protectionLevel = fixedLevel; 3416 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3417 bp.perm.info.packageName = tree.perm.info.packageName; 3418 bp.uid = tree.uid; 3419 if (added) { 3420 mSettings.mPermissions.put(info.name, bp); 3421 } 3422 if (changed) { 3423 if (!async) { 3424 mSettings.writeLPr(); 3425 } else { 3426 scheduleWriteSettingsLocked(); 3427 } 3428 } 3429 return added; 3430 } 3431 3432 @Override 3433 public boolean addPermission(PermissionInfo info) { 3434 synchronized (mPackages) { 3435 return addPermissionLocked(info, false); 3436 } 3437 } 3438 3439 @Override 3440 public boolean addPermissionAsync(PermissionInfo info) { 3441 synchronized (mPackages) { 3442 return addPermissionLocked(info, true); 3443 } 3444 } 3445 3446 @Override 3447 public void removePermission(String name) { 3448 synchronized (mPackages) { 3449 checkPermissionTreeLP(name); 3450 BasePermission bp = mSettings.mPermissions.get(name); 3451 if (bp != null) { 3452 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3453 throw new SecurityException( 3454 "Not allowed to modify non-dynamic permission " 3455 + name); 3456 } 3457 mSettings.mPermissions.remove(name); 3458 mSettings.writeLPr(); 3459 } 3460 } 3461 } 3462 3463 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3464 BasePermission bp) { 3465 int index = pkg.requestedPermissions.indexOf(bp.name); 3466 if (index == -1) { 3467 throw new SecurityException("Package " + pkg.packageName 3468 + " has not requested permission " + bp.name); 3469 } 3470 if (!bp.isRuntime() && !bp.isDevelopment()) { 3471 throw new SecurityException("Permission " + bp.name 3472 + " is not a changeable permission type"); 3473 } 3474 } 3475 3476 @Override 3477 public void grantRuntimePermission(String packageName, String name, final int userId) { 3478 if (!sUserManager.exists(userId)) { 3479 Log.e(TAG, "No such user:" + userId); 3480 return; 3481 } 3482 3483 mContext.enforceCallingOrSelfPermission( 3484 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3485 "grantRuntimePermission"); 3486 3487 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3488 "grantRuntimePermission"); 3489 3490 final int uid; 3491 final SettingBase sb; 3492 3493 synchronized (mPackages) { 3494 final PackageParser.Package pkg = mPackages.get(packageName); 3495 if (pkg == null) { 3496 throw new IllegalArgumentException("Unknown package: " + packageName); 3497 } 3498 3499 final BasePermission bp = mSettings.mPermissions.get(name); 3500 if (bp == null) { 3501 throw new IllegalArgumentException("Unknown permission: " + name); 3502 } 3503 3504 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3505 3506 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3507 sb = (SettingBase) pkg.mExtras; 3508 if (sb == null) { 3509 throw new IllegalArgumentException("Unknown package: " + packageName); 3510 } 3511 3512 final PermissionsState permissionsState = sb.getPermissionsState(); 3513 3514 final int flags = permissionsState.getPermissionFlags(name, userId); 3515 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3516 throw new SecurityException("Cannot grant system fixed permission: " 3517 + name + " for package: " + packageName); 3518 } 3519 3520 if (bp.isDevelopment()) { 3521 // Development permissions must be handled specially, since they are not 3522 // normal runtime permissions. For now they apply to all users. 3523 if (permissionsState.grantInstallPermission(bp) != 3524 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3525 scheduleWriteSettingsLocked(); 3526 } 3527 return; 3528 } 3529 3530 final int result = permissionsState.grantRuntimePermission(bp, userId); 3531 switch (result) { 3532 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3533 return; 3534 } 3535 3536 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3537 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3538 mHandler.post(new Runnable() { 3539 @Override 3540 public void run() { 3541 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3542 } 3543 }); 3544 } 3545 break; 3546 } 3547 3548 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3549 3550 // Not critical if that is lost - app has to request again. 3551 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3552 } 3553 3554 // Only need to do this if user is initialized. Otherwise it's a new user 3555 // and there are no processes running as the user yet and there's no need 3556 // to make an expensive call to remount processes for the changed permissions. 3557 if (READ_EXTERNAL_STORAGE.equals(name) 3558 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3559 final long token = Binder.clearCallingIdentity(); 3560 try { 3561 if (sUserManager.isInitialized(userId)) { 3562 MountServiceInternal mountServiceInternal = LocalServices.getService( 3563 MountServiceInternal.class); 3564 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3565 } 3566 } finally { 3567 Binder.restoreCallingIdentity(token); 3568 } 3569 } 3570 } 3571 3572 @Override 3573 public void revokeRuntimePermission(String packageName, String name, int userId) { 3574 if (!sUserManager.exists(userId)) { 3575 Log.e(TAG, "No such user:" + userId); 3576 return; 3577 } 3578 3579 mContext.enforceCallingOrSelfPermission( 3580 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3581 "revokeRuntimePermission"); 3582 3583 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3584 "revokeRuntimePermission"); 3585 3586 final int appId; 3587 3588 synchronized (mPackages) { 3589 final PackageParser.Package pkg = mPackages.get(packageName); 3590 if (pkg == null) { 3591 throw new IllegalArgumentException("Unknown package: " + packageName); 3592 } 3593 3594 final BasePermission bp = mSettings.mPermissions.get(name); 3595 if (bp == null) { 3596 throw new IllegalArgumentException("Unknown permission: " + name); 3597 } 3598 3599 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3600 3601 SettingBase sb = (SettingBase) pkg.mExtras; 3602 if (sb == null) { 3603 throw new IllegalArgumentException("Unknown package: " + packageName); 3604 } 3605 3606 final PermissionsState permissionsState = sb.getPermissionsState(); 3607 3608 final int flags = permissionsState.getPermissionFlags(name, userId); 3609 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3610 throw new SecurityException("Cannot revoke system fixed permission: " 3611 + name + " for package: " + packageName); 3612 } 3613 3614 if (bp.isDevelopment()) { 3615 // Development permissions must be handled specially, since they are not 3616 // normal runtime permissions. For now they apply to all users. 3617 if (permissionsState.revokeInstallPermission(bp) != 3618 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3619 scheduleWriteSettingsLocked(); 3620 } 3621 return; 3622 } 3623 3624 if (permissionsState.revokeRuntimePermission(bp, userId) == 3625 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3626 return; 3627 } 3628 3629 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3630 3631 // Critical, after this call app should never have the permission. 3632 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3633 3634 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3635 } 3636 3637 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3638 } 3639 3640 @Override 3641 public void resetRuntimePermissions() { 3642 mContext.enforceCallingOrSelfPermission( 3643 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3644 "revokeRuntimePermission"); 3645 3646 int callingUid = Binder.getCallingUid(); 3647 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3648 mContext.enforceCallingOrSelfPermission( 3649 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3650 "resetRuntimePermissions"); 3651 } 3652 3653 synchronized (mPackages) { 3654 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3655 for (int userId : UserManagerService.getInstance().getUserIds()) { 3656 final int packageCount = mPackages.size(); 3657 for (int i = 0; i < packageCount; i++) { 3658 PackageParser.Package pkg = mPackages.valueAt(i); 3659 if (!(pkg.mExtras instanceof PackageSetting)) { 3660 continue; 3661 } 3662 PackageSetting ps = (PackageSetting) pkg.mExtras; 3663 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3664 } 3665 } 3666 } 3667 } 3668 3669 @Override 3670 public int getPermissionFlags(String name, String packageName, int userId) { 3671 if (!sUserManager.exists(userId)) { 3672 return 0; 3673 } 3674 3675 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3676 3677 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3678 "getPermissionFlags"); 3679 3680 synchronized (mPackages) { 3681 final PackageParser.Package pkg = mPackages.get(packageName); 3682 if (pkg == null) { 3683 throw new IllegalArgumentException("Unknown package: " + packageName); 3684 } 3685 3686 final BasePermission bp = mSettings.mPermissions.get(name); 3687 if (bp == null) { 3688 throw new IllegalArgumentException("Unknown permission: " + name); 3689 } 3690 3691 SettingBase sb = (SettingBase) pkg.mExtras; 3692 if (sb == null) { 3693 throw new IllegalArgumentException("Unknown package: " + packageName); 3694 } 3695 3696 PermissionsState permissionsState = sb.getPermissionsState(); 3697 return permissionsState.getPermissionFlags(name, userId); 3698 } 3699 } 3700 3701 @Override 3702 public void updatePermissionFlags(String name, String packageName, int flagMask, 3703 int flagValues, int userId) { 3704 if (!sUserManager.exists(userId)) { 3705 return; 3706 } 3707 3708 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3709 3710 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3711 "updatePermissionFlags"); 3712 3713 // Only the system can change these flags and nothing else. 3714 if (getCallingUid() != Process.SYSTEM_UID) { 3715 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3716 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3717 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3718 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3719 } 3720 3721 synchronized (mPackages) { 3722 final PackageParser.Package pkg = mPackages.get(packageName); 3723 if (pkg == null) { 3724 throw new IllegalArgumentException("Unknown package: " + packageName); 3725 } 3726 3727 final BasePermission bp = mSettings.mPermissions.get(name); 3728 if (bp == null) { 3729 throw new IllegalArgumentException("Unknown permission: " + name); 3730 } 3731 3732 SettingBase sb = (SettingBase) pkg.mExtras; 3733 if (sb == null) { 3734 throw new IllegalArgumentException("Unknown package: " + packageName); 3735 } 3736 3737 PermissionsState permissionsState = sb.getPermissionsState(); 3738 3739 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3740 3741 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3742 // Install and runtime permissions are stored in different places, 3743 // so figure out what permission changed and persist the change. 3744 if (permissionsState.getInstallPermissionState(name) != null) { 3745 scheduleWriteSettingsLocked(); 3746 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3747 || hadState) { 3748 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3749 } 3750 } 3751 } 3752 } 3753 3754 /** 3755 * Update the permission flags for all packages and runtime permissions of a user in order 3756 * to allow device or profile owner to remove POLICY_FIXED. 3757 */ 3758 @Override 3759 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3760 if (!sUserManager.exists(userId)) { 3761 return; 3762 } 3763 3764 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3765 3766 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3767 "updatePermissionFlagsForAllApps"); 3768 3769 // Only the system can change system fixed flags. 3770 if (getCallingUid() != Process.SYSTEM_UID) { 3771 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3772 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3773 } 3774 3775 synchronized (mPackages) { 3776 boolean changed = false; 3777 final int packageCount = mPackages.size(); 3778 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3779 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3780 SettingBase sb = (SettingBase) pkg.mExtras; 3781 if (sb == null) { 3782 continue; 3783 } 3784 PermissionsState permissionsState = sb.getPermissionsState(); 3785 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3786 userId, flagMask, flagValues); 3787 } 3788 if (changed) { 3789 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3790 } 3791 } 3792 } 3793 3794 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3795 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3796 != PackageManager.PERMISSION_GRANTED 3797 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3798 != PackageManager.PERMISSION_GRANTED) { 3799 throw new SecurityException(message + " requires " 3800 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3801 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3802 } 3803 } 3804 3805 @Override 3806 public boolean shouldShowRequestPermissionRationale(String permissionName, 3807 String packageName, int userId) { 3808 if (UserHandle.getCallingUserId() != userId) { 3809 mContext.enforceCallingPermission( 3810 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3811 "canShowRequestPermissionRationale for user " + userId); 3812 } 3813 3814 final int uid = getPackageUid(packageName, userId); 3815 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3816 return false; 3817 } 3818 3819 if (checkPermission(permissionName, packageName, userId) 3820 == PackageManager.PERMISSION_GRANTED) { 3821 return false; 3822 } 3823 3824 final int flags; 3825 3826 final long identity = Binder.clearCallingIdentity(); 3827 try { 3828 flags = getPermissionFlags(permissionName, 3829 packageName, userId); 3830 } finally { 3831 Binder.restoreCallingIdentity(identity); 3832 } 3833 3834 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3835 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3836 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3837 3838 if ((flags & fixedFlags) != 0) { 3839 return false; 3840 } 3841 3842 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3843 } 3844 3845 @Override 3846 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3847 mContext.enforceCallingOrSelfPermission( 3848 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3849 "addOnPermissionsChangeListener"); 3850 3851 synchronized (mPackages) { 3852 mOnPermissionChangeListeners.addListenerLocked(listener); 3853 } 3854 } 3855 3856 @Override 3857 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3858 synchronized (mPackages) { 3859 mOnPermissionChangeListeners.removeListenerLocked(listener); 3860 } 3861 } 3862 3863 @Override 3864 public boolean isProtectedBroadcast(String actionName) { 3865 synchronized (mPackages) { 3866 return mProtectedBroadcasts.contains(actionName); 3867 } 3868 } 3869 3870 @Override 3871 public int checkSignatures(String pkg1, String pkg2) { 3872 synchronized (mPackages) { 3873 final PackageParser.Package p1 = mPackages.get(pkg1); 3874 final PackageParser.Package p2 = mPackages.get(pkg2); 3875 if (p1 == null || p1.mExtras == null 3876 || p2 == null || p2.mExtras == null) { 3877 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3878 } 3879 return compareSignatures(p1.mSignatures, p2.mSignatures); 3880 } 3881 } 3882 3883 @Override 3884 public int checkUidSignatures(int uid1, int uid2) { 3885 // Map to base uids. 3886 uid1 = UserHandle.getAppId(uid1); 3887 uid2 = UserHandle.getAppId(uid2); 3888 // reader 3889 synchronized (mPackages) { 3890 Signature[] s1; 3891 Signature[] s2; 3892 Object obj = mSettings.getUserIdLPr(uid1); 3893 if (obj != null) { 3894 if (obj instanceof SharedUserSetting) { 3895 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3896 } else if (obj instanceof PackageSetting) { 3897 s1 = ((PackageSetting)obj).signatures.mSignatures; 3898 } else { 3899 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3900 } 3901 } else { 3902 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3903 } 3904 obj = mSettings.getUserIdLPr(uid2); 3905 if (obj != null) { 3906 if (obj instanceof SharedUserSetting) { 3907 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3908 } else if (obj instanceof PackageSetting) { 3909 s2 = ((PackageSetting)obj).signatures.mSignatures; 3910 } else { 3911 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3912 } 3913 } else { 3914 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3915 } 3916 return compareSignatures(s1, s2); 3917 } 3918 } 3919 3920 private void killUid(int appId, int userId, String reason) { 3921 final long identity = Binder.clearCallingIdentity(); 3922 try { 3923 IActivityManager am = ActivityManagerNative.getDefault(); 3924 if (am != null) { 3925 try { 3926 am.killUid(appId, userId, reason); 3927 } catch (RemoteException e) { 3928 /* ignore - same process */ 3929 } 3930 } 3931 } finally { 3932 Binder.restoreCallingIdentity(identity); 3933 } 3934 } 3935 3936 /** 3937 * Compares two sets of signatures. Returns: 3938 * <br /> 3939 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3940 * <br /> 3941 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3942 * <br /> 3943 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3944 * <br /> 3945 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3946 * <br /> 3947 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3948 */ 3949 static int compareSignatures(Signature[] s1, Signature[] s2) { 3950 if (s1 == null) { 3951 return s2 == null 3952 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3953 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3954 } 3955 3956 if (s2 == null) { 3957 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3958 } 3959 3960 if (s1.length != s2.length) { 3961 return PackageManager.SIGNATURE_NO_MATCH; 3962 } 3963 3964 // Since both signature sets are of size 1, we can compare without HashSets. 3965 if (s1.length == 1) { 3966 return s1[0].equals(s2[0]) ? 3967 PackageManager.SIGNATURE_MATCH : 3968 PackageManager.SIGNATURE_NO_MATCH; 3969 } 3970 3971 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3972 for (Signature sig : s1) { 3973 set1.add(sig); 3974 } 3975 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3976 for (Signature sig : s2) { 3977 set2.add(sig); 3978 } 3979 // Make sure s2 contains all signatures in s1. 3980 if (set1.equals(set2)) { 3981 return PackageManager.SIGNATURE_MATCH; 3982 } 3983 return PackageManager.SIGNATURE_NO_MATCH; 3984 } 3985 3986 /** 3987 * If the database version for this type of package (internal storage or 3988 * external storage) is less than the version where package signatures 3989 * were updated, return true. 3990 */ 3991 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3992 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3993 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3994 } 3995 3996 /** 3997 * Used for backward compatibility to make sure any packages with 3998 * certificate chains get upgraded to the new style. {@code existingSigs} 3999 * will be in the old format (since they were stored on disk from before the 4000 * system upgrade) and {@code scannedSigs} will be in the newer format. 4001 */ 4002 private int compareSignaturesCompat(PackageSignatures existingSigs, 4003 PackageParser.Package scannedPkg) { 4004 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4005 return PackageManager.SIGNATURE_NO_MATCH; 4006 } 4007 4008 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4009 for (Signature sig : existingSigs.mSignatures) { 4010 existingSet.add(sig); 4011 } 4012 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4013 for (Signature sig : scannedPkg.mSignatures) { 4014 try { 4015 Signature[] chainSignatures = sig.getChainSignatures(); 4016 for (Signature chainSig : chainSignatures) { 4017 scannedCompatSet.add(chainSig); 4018 } 4019 } catch (CertificateEncodingException e) { 4020 scannedCompatSet.add(sig); 4021 } 4022 } 4023 /* 4024 * Make sure the expanded scanned set contains all signatures in the 4025 * existing one. 4026 */ 4027 if (scannedCompatSet.equals(existingSet)) { 4028 // Migrate the old signatures to the new scheme. 4029 existingSigs.assignSignatures(scannedPkg.mSignatures); 4030 // The new KeySets will be re-added later in the scanning process. 4031 synchronized (mPackages) { 4032 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4033 } 4034 return PackageManager.SIGNATURE_MATCH; 4035 } 4036 return PackageManager.SIGNATURE_NO_MATCH; 4037 } 4038 4039 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4040 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4041 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4042 } 4043 4044 private int compareSignaturesRecover(PackageSignatures existingSigs, 4045 PackageParser.Package scannedPkg) { 4046 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4047 return PackageManager.SIGNATURE_NO_MATCH; 4048 } 4049 4050 String msg = null; 4051 try { 4052 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4053 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4054 + scannedPkg.packageName); 4055 return PackageManager.SIGNATURE_MATCH; 4056 } 4057 } catch (CertificateException e) { 4058 msg = e.getMessage(); 4059 } 4060 4061 logCriticalInfo(Log.INFO, 4062 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4063 return PackageManager.SIGNATURE_NO_MATCH; 4064 } 4065 4066 @Override 4067 public String[] getPackagesForUid(int uid) { 4068 uid = UserHandle.getAppId(uid); 4069 // reader 4070 synchronized (mPackages) { 4071 Object obj = mSettings.getUserIdLPr(uid); 4072 if (obj instanceof SharedUserSetting) { 4073 final SharedUserSetting sus = (SharedUserSetting) obj; 4074 final int N = sus.packages.size(); 4075 final String[] res = new String[N]; 4076 final Iterator<PackageSetting> it = sus.packages.iterator(); 4077 int i = 0; 4078 while (it.hasNext()) { 4079 res[i++] = it.next().name; 4080 } 4081 return res; 4082 } else if (obj instanceof PackageSetting) { 4083 final PackageSetting ps = (PackageSetting) obj; 4084 return new String[] { ps.name }; 4085 } 4086 } 4087 return null; 4088 } 4089 4090 @Override 4091 public String getNameForUid(int uid) { 4092 // reader 4093 synchronized (mPackages) { 4094 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4095 if (obj instanceof SharedUserSetting) { 4096 final SharedUserSetting sus = (SharedUserSetting) obj; 4097 return sus.name + ":" + sus.userId; 4098 } else if (obj instanceof PackageSetting) { 4099 final PackageSetting ps = (PackageSetting) obj; 4100 return ps.name; 4101 } 4102 } 4103 return null; 4104 } 4105 4106 @Override 4107 public int getUidForSharedUser(String sharedUserName) { 4108 if(sharedUserName == null) { 4109 return -1; 4110 } 4111 // reader 4112 synchronized (mPackages) { 4113 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4114 if (suid == null) { 4115 return -1; 4116 } 4117 return suid.userId; 4118 } 4119 } 4120 4121 @Override 4122 public int getFlagsForUid(int uid) { 4123 synchronized (mPackages) { 4124 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4125 if (obj instanceof SharedUserSetting) { 4126 final SharedUserSetting sus = (SharedUserSetting) obj; 4127 return sus.pkgFlags; 4128 } else if (obj instanceof PackageSetting) { 4129 final PackageSetting ps = (PackageSetting) obj; 4130 return ps.pkgFlags; 4131 } 4132 } 4133 return 0; 4134 } 4135 4136 @Override 4137 public int getPrivateFlagsForUid(int uid) { 4138 synchronized (mPackages) { 4139 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4140 if (obj instanceof SharedUserSetting) { 4141 final SharedUserSetting sus = (SharedUserSetting) obj; 4142 return sus.pkgPrivateFlags; 4143 } else if (obj instanceof PackageSetting) { 4144 final PackageSetting ps = (PackageSetting) obj; 4145 return ps.pkgPrivateFlags; 4146 } 4147 } 4148 return 0; 4149 } 4150 4151 @Override 4152 public boolean isUidPrivileged(int uid) { 4153 uid = UserHandle.getAppId(uid); 4154 // reader 4155 synchronized (mPackages) { 4156 Object obj = mSettings.getUserIdLPr(uid); 4157 if (obj instanceof SharedUserSetting) { 4158 final SharedUserSetting sus = (SharedUserSetting) obj; 4159 final Iterator<PackageSetting> it = sus.packages.iterator(); 4160 while (it.hasNext()) { 4161 if (it.next().isPrivileged()) { 4162 return true; 4163 } 4164 } 4165 } else if (obj instanceof PackageSetting) { 4166 final PackageSetting ps = (PackageSetting) obj; 4167 return ps.isPrivileged(); 4168 } 4169 } 4170 return false; 4171 } 4172 4173 @Override 4174 public String[] getAppOpPermissionPackages(String permissionName) { 4175 synchronized (mPackages) { 4176 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4177 if (pkgs == null) { 4178 return null; 4179 } 4180 return pkgs.toArray(new String[pkgs.size()]); 4181 } 4182 } 4183 4184 @Override 4185 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4186 int flags, int userId) { 4187 if (!sUserManager.exists(userId)) return null; 4188 flags = augmentFlagsForUser(flags, userId); 4189 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4190 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4191 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4192 } 4193 4194 @Override 4195 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4196 IntentFilter filter, int match, ComponentName activity) { 4197 final int userId = UserHandle.getCallingUserId(); 4198 if (DEBUG_PREFERRED) { 4199 Log.v(TAG, "setLastChosenActivity intent=" + intent 4200 + " resolvedType=" + resolvedType 4201 + " flags=" + flags 4202 + " filter=" + filter 4203 + " match=" + match 4204 + " activity=" + activity); 4205 filter.dump(new PrintStreamPrinter(System.out), " "); 4206 } 4207 intent.setComponent(null); 4208 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4209 // Find any earlier preferred or last chosen entries and nuke them 4210 findPreferredActivity(intent, resolvedType, 4211 flags, query, 0, false, true, false, userId); 4212 // Add the new activity as the last chosen for this filter 4213 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4214 "Setting last chosen"); 4215 } 4216 4217 @Override 4218 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4219 final int userId = UserHandle.getCallingUserId(); 4220 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4221 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4222 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4223 false, false, false, userId); 4224 } 4225 4226 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4227 int flags, List<ResolveInfo> query, int userId) { 4228 if (query != null) { 4229 final int N = query.size(); 4230 if (N == 1) { 4231 return query.get(0); 4232 } else if (N > 1) { 4233 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4234 // If there is more than one activity with the same priority, 4235 // then let the user decide between them. 4236 ResolveInfo r0 = query.get(0); 4237 ResolveInfo r1 = query.get(1); 4238 if (DEBUG_INTENT_MATCHING || debug) { 4239 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4240 + r1.activityInfo.name + "=" + r1.priority); 4241 } 4242 // If the first activity has a higher priority, or a different 4243 // default, then it is always desireable to pick it. 4244 if (r0.priority != r1.priority 4245 || r0.preferredOrder != r1.preferredOrder 4246 || r0.isDefault != r1.isDefault) { 4247 return query.get(0); 4248 } 4249 // If we have saved a preference for a preferred activity for 4250 // this Intent, use that. 4251 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4252 flags, query, r0.priority, true, false, debug, userId); 4253 if (ri != null) { 4254 return ri; 4255 } 4256 ri = new ResolveInfo(mResolveInfo); 4257 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4258 ri.activityInfo.applicationInfo = new ApplicationInfo( 4259 ri.activityInfo.applicationInfo); 4260 if (userId != 0) { 4261 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4262 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4263 } 4264 // Make sure that the resolver is displayable in car mode 4265 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4266 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4267 return ri; 4268 } 4269 } 4270 return null; 4271 } 4272 4273 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4274 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4275 final int N = query.size(); 4276 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4277 .get(userId); 4278 // Get the list of persistent preferred activities that handle the intent 4279 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4280 List<PersistentPreferredActivity> pprefs = ppir != null 4281 ? ppir.queryIntent(intent, resolvedType, 4282 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4283 : null; 4284 if (pprefs != null && pprefs.size() > 0) { 4285 final int M = pprefs.size(); 4286 for (int i=0; i<M; i++) { 4287 final PersistentPreferredActivity ppa = pprefs.get(i); 4288 if (DEBUG_PREFERRED || debug) { 4289 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4290 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4291 + "\n component=" + ppa.mComponent); 4292 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4293 } 4294 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4295 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4296 if (DEBUG_PREFERRED || debug) { 4297 Slog.v(TAG, "Found persistent preferred activity:"); 4298 if (ai != null) { 4299 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4300 } else { 4301 Slog.v(TAG, " null"); 4302 } 4303 } 4304 if (ai == null) { 4305 // This previously registered persistent preferred activity 4306 // component is no longer known. Ignore it and do NOT remove it. 4307 continue; 4308 } 4309 for (int j=0; j<N; j++) { 4310 final ResolveInfo ri = query.get(j); 4311 if (!ri.activityInfo.applicationInfo.packageName 4312 .equals(ai.applicationInfo.packageName)) { 4313 continue; 4314 } 4315 if (!ri.activityInfo.name.equals(ai.name)) { 4316 continue; 4317 } 4318 // Found a persistent preference that can handle the intent. 4319 if (DEBUG_PREFERRED || debug) { 4320 Slog.v(TAG, "Returning persistent preferred activity: " + 4321 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4322 } 4323 return ri; 4324 } 4325 } 4326 } 4327 return null; 4328 } 4329 4330 // TODO: handle preferred activities missing while user has amnesia 4331 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4332 List<ResolveInfo> query, int priority, boolean always, 4333 boolean removeMatches, boolean debug, int userId) { 4334 if (!sUserManager.exists(userId)) return null; 4335 flags = augmentFlagsForUser(flags, userId); 4336 // writer 4337 synchronized (mPackages) { 4338 if (intent.getSelector() != null) { 4339 intent = intent.getSelector(); 4340 } 4341 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4342 4343 // Try to find a matching persistent preferred activity. 4344 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4345 debug, userId); 4346 4347 // If a persistent preferred activity matched, use it. 4348 if (pri != null) { 4349 return pri; 4350 } 4351 4352 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4353 // Get the list of preferred activities that handle the intent 4354 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4355 List<PreferredActivity> prefs = pir != null 4356 ? pir.queryIntent(intent, resolvedType, 4357 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4358 : null; 4359 if (prefs != null && prefs.size() > 0) { 4360 boolean changed = false; 4361 try { 4362 // First figure out how good the original match set is. 4363 // We will only allow preferred activities that came 4364 // from the same match quality. 4365 int match = 0; 4366 4367 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4368 4369 final int N = query.size(); 4370 for (int j=0; j<N; j++) { 4371 final ResolveInfo ri = query.get(j); 4372 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4373 + ": 0x" + Integer.toHexString(match)); 4374 if (ri.match > match) { 4375 match = ri.match; 4376 } 4377 } 4378 4379 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4380 + Integer.toHexString(match)); 4381 4382 match &= IntentFilter.MATCH_CATEGORY_MASK; 4383 final int M = prefs.size(); 4384 for (int i=0; i<M; i++) { 4385 final PreferredActivity pa = prefs.get(i); 4386 if (DEBUG_PREFERRED || debug) { 4387 Slog.v(TAG, "Checking PreferredActivity ds=" 4388 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4389 + "\n component=" + pa.mPref.mComponent); 4390 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4391 } 4392 if (pa.mPref.mMatch != match) { 4393 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4394 + Integer.toHexString(pa.mPref.mMatch)); 4395 continue; 4396 } 4397 // If it's not an "always" type preferred activity and that's what we're 4398 // looking for, skip it. 4399 if (always && !pa.mPref.mAlways) { 4400 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4401 continue; 4402 } 4403 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4404 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4405 if (DEBUG_PREFERRED || debug) { 4406 Slog.v(TAG, "Found preferred activity:"); 4407 if (ai != null) { 4408 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4409 } else { 4410 Slog.v(TAG, " null"); 4411 } 4412 } 4413 if (ai == null) { 4414 // This previously registered preferred activity 4415 // component is no longer known. Most likely an update 4416 // to the app was installed and in the new version this 4417 // component no longer exists. Clean it up by removing 4418 // it from the preferred activities list, and skip it. 4419 Slog.w(TAG, "Removing dangling preferred activity: " 4420 + pa.mPref.mComponent); 4421 pir.removeFilter(pa); 4422 changed = true; 4423 continue; 4424 } 4425 for (int j=0; j<N; j++) { 4426 final ResolveInfo ri = query.get(j); 4427 if (!ri.activityInfo.applicationInfo.packageName 4428 .equals(ai.applicationInfo.packageName)) { 4429 continue; 4430 } 4431 if (!ri.activityInfo.name.equals(ai.name)) { 4432 continue; 4433 } 4434 4435 if (removeMatches) { 4436 pir.removeFilter(pa); 4437 changed = true; 4438 if (DEBUG_PREFERRED) { 4439 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4440 } 4441 break; 4442 } 4443 4444 // Okay we found a previously set preferred or last chosen app. 4445 // If the result set is different from when this 4446 // was created, we need to clear it and re-ask the 4447 // user their preference, if we're looking for an "always" type entry. 4448 if (always && !pa.mPref.sameSet(query)) { 4449 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4450 + intent + " type " + resolvedType); 4451 if (DEBUG_PREFERRED) { 4452 Slog.v(TAG, "Removing preferred activity since set changed " 4453 + pa.mPref.mComponent); 4454 } 4455 pir.removeFilter(pa); 4456 // Re-add the filter as a "last chosen" entry (!always) 4457 PreferredActivity lastChosen = new PreferredActivity( 4458 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4459 pir.addFilter(lastChosen); 4460 changed = true; 4461 return null; 4462 } 4463 4464 // Yay! Either the set matched or we're looking for the last chosen 4465 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4466 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4467 return ri; 4468 } 4469 } 4470 } finally { 4471 if (changed) { 4472 if (DEBUG_PREFERRED) { 4473 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4474 } 4475 scheduleWritePackageRestrictionsLocked(userId); 4476 } 4477 } 4478 } 4479 } 4480 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4481 return null; 4482 } 4483 4484 /* 4485 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4486 */ 4487 @Override 4488 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4489 int targetUserId) { 4490 mContext.enforceCallingOrSelfPermission( 4491 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4492 List<CrossProfileIntentFilter> matches = 4493 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4494 if (matches != null) { 4495 int size = matches.size(); 4496 for (int i = 0; i < size; i++) { 4497 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4498 } 4499 } 4500 if (hasWebURI(intent)) { 4501 // cross-profile app linking works only towards the parent. 4502 final UserInfo parent = getProfileParent(sourceUserId); 4503 synchronized(mPackages) { 4504 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4505 intent, resolvedType, 0, sourceUserId, parent.id); 4506 return xpDomainInfo != null; 4507 } 4508 } 4509 return false; 4510 } 4511 4512 private UserInfo getProfileParent(int userId) { 4513 final long identity = Binder.clearCallingIdentity(); 4514 try { 4515 return sUserManager.getProfileParent(userId); 4516 } finally { 4517 Binder.restoreCallingIdentity(identity); 4518 } 4519 } 4520 4521 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4522 String resolvedType, int userId) { 4523 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4524 if (resolver != null) { 4525 return resolver.queryIntent(intent, resolvedType, false, userId); 4526 } 4527 return null; 4528 } 4529 4530 @Override 4531 public List<ResolveInfo> queryIntentActivities(Intent intent, 4532 String resolvedType, int flags, int userId) { 4533 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4534 flags = augmentFlagsForUser(flags, userId); 4535 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4536 ComponentName comp = intent.getComponent(); 4537 if (comp == null) { 4538 if (intent.getSelector() != null) { 4539 intent = intent.getSelector(); 4540 comp = intent.getComponent(); 4541 } 4542 } 4543 4544 if (comp != null) { 4545 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4546 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4547 if (ai != null) { 4548 final ResolveInfo ri = new ResolveInfo(); 4549 ri.activityInfo = ai; 4550 list.add(ri); 4551 } 4552 return list; 4553 } 4554 4555 // reader 4556 synchronized (mPackages) { 4557 final String pkgName = intent.getPackage(); 4558 if (pkgName == null) { 4559 List<CrossProfileIntentFilter> matchingFilters = 4560 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4561 // Check for results that need to skip the current profile. 4562 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4563 resolvedType, flags, userId); 4564 if (xpResolveInfo != null) { 4565 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4566 result.add(xpResolveInfo); 4567 return filterIfNotSystemUser(result, userId); 4568 } 4569 4570 // Check for results in the current profile. 4571 List<ResolveInfo> result = mActivities.queryIntent( 4572 intent, resolvedType, flags, userId); 4573 4574 // Check for cross profile results. 4575 xpResolveInfo = queryCrossProfileIntents( 4576 matchingFilters, intent, resolvedType, flags, userId); 4577 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4578 result.add(xpResolveInfo); 4579 Collections.sort(result, mResolvePrioritySorter); 4580 } 4581 result = filterIfNotSystemUser(result, userId); 4582 if (hasWebURI(intent)) { 4583 CrossProfileDomainInfo xpDomainInfo = null; 4584 final UserInfo parent = getProfileParent(userId); 4585 if (parent != null) { 4586 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4587 flags, userId, parent.id); 4588 } 4589 if (xpDomainInfo != null) { 4590 if (xpResolveInfo != null) { 4591 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4592 // in the result. 4593 result.remove(xpResolveInfo); 4594 } 4595 if (result.size() == 0) { 4596 result.add(xpDomainInfo.resolveInfo); 4597 return result; 4598 } 4599 } else if (result.size() <= 1) { 4600 return result; 4601 } 4602 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4603 xpDomainInfo, userId); 4604 Collections.sort(result, mResolvePrioritySorter); 4605 } 4606 return result; 4607 } 4608 final PackageParser.Package pkg = mPackages.get(pkgName); 4609 if (pkg != null) { 4610 return filterIfNotSystemUser( 4611 mActivities.queryIntentForPackage( 4612 intent, resolvedType, flags, pkg.activities, userId), 4613 userId); 4614 } 4615 return new ArrayList<ResolveInfo>(); 4616 } 4617 } 4618 4619 private static class CrossProfileDomainInfo { 4620 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4621 ResolveInfo resolveInfo; 4622 /* Best domain verification status of the activities found in the other profile */ 4623 int bestDomainVerificationStatus; 4624 } 4625 4626 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4627 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4628 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4629 sourceUserId)) { 4630 return null; 4631 } 4632 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4633 resolvedType, flags, parentUserId); 4634 4635 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4636 return null; 4637 } 4638 CrossProfileDomainInfo result = null; 4639 int size = resultTargetUser.size(); 4640 for (int i = 0; i < size; i++) { 4641 ResolveInfo riTargetUser = resultTargetUser.get(i); 4642 // Intent filter verification is only for filters that specify a host. So don't return 4643 // those that handle all web uris. 4644 if (riTargetUser.handleAllWebDataURI) { 4645 continue; 4646 } 4647 String packageName = riTargetUser.activityInfo.packageName; 4648 PackageSetting ps = mSettings.mPackages.get(packageName); 4649 if (ps == null) { 4650 continue; 4651 } 4652 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4653 int status = (int)(verificationState >> 32); 4654 if (result == null) { 4655 result = new CrossProfileDomainInfo(); 4656 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4657 sourceUserId, parentUserId); 4658 result.bestDomainVerificationStatus = status; 4659 } else { 4660 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4661 result.bestDomainVerificationStatus); 4662 } 4663 } 4664 // Don't consider matches with status NEVER across profiles. 4665 if (result != null && result.bestDomainVerificationStatus 4666 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4667 return null; 4668 } 4669 return result; 4670 } 4671 4672 /** 4673 * Verification statuses are ordered from the worse to the best, except for 4674 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4675 */ 4676 private int bestDomainVerificationStatus(int status1, int status2) { 4677 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4678 return status2; 4679 } 4680 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4681 return status1; 4682 } 4683 return (int) MathUtils.max(status1, status2); 4684 } 4685 4686 private boolean isUserEnabled(int userId) { 4687 long callingId = Binder.clearCallingIdentity(); 4688 try { 4689 UserInfo userInfo = sUserManager.getUserInfo(userId); 4690 return userInfo != null && userInfo.isEnabled(); 4691 } finally { 4692 Binder.restoreCallingIdentity(callingId); 4693 } 4694 } 4695 4696 /** 4697 * Filter out activities with systemUserOnly flag set, when current user is not System. 4698 * 4699 * @return filtered list 4700 */ 4701 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4702 if (userId == UserHandle.USER_SYSTEM) { 4703 return resolveInfos; 4704 } 4705 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4706 ResolveInfo info = resolveInfos.get(i); 4707 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4708 resolveInfos.remove(i); 4709 } 4710 } 4711 return resolveInfos; 4712 } 4713 4714 private static boolean hasWebURI(Intent intent) { 4715 if (intent.getData() == null) { 4716 return false; 4717 } 4718 final String scheme = intent.getScheme(); 4719 if (TextUtils.isEmpty(scheme)) { 4720 return false; 4721 } 4722 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4723 } 4724 4725 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4726 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4727 int userId) { 4728 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4729 4730 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4731 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4732 candidates.size()); 4733 } 4734 4735 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4736 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4737 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4738 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4739 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4740 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4741 4742 synchronized (mPackages) { 4743 final int count = candidates.size(); 4744 // First, try to use linked apps. Partition the candidates into four lists: 4745 // one for the final results, one for the "do not use ever", one for "undefined status" 4746 // and finally one for "browser app type". 4747 for (int n=0; n<count; n++) { 4748 ResolveInfo info = candidates.get(n); 4749 String packageName = info.activityInfo.packageName; 4750 PackageSetting ps = mSettings.mPackages.get(packageName); 4751 if (ps != null) { 4752 // Add to the special match all list (Browser use case) 4753 if (info.handleAllWebDataURI) { 4754 matchAllList.add(info); 4755 continue; 4756 } 4757 // Try to get the status from User settings first 4758 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4759 int status = (int)(packedStatus >> 32); 4760 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4761 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4762 if (DEBUG_DOMAIN_VERIFICATION) { 4763 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4764 + " : linkgen=" + linkGeneration); 4765 } 4766 // Use link-enabled generation as preferredOrder, i.e. 4767 // prefer newly-enabled over earlier-enabled. 4768 info.preferredOrder = linkGeneration; 4769 alwaysList.add(info); 4770 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4771 if (DEBUG_DOMAIN_VERIFICATION) { 4772 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4773 } 4774 neverList.add(info); 4775 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4776 if (DEBUG_DOMAIN_VERIFICATION) { 4777 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4778 } 4779 alwaysAskList.add(info); 4780 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4781 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4782 if (DEBUG_DOMAIN_VERIFICATION) { 4783 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4784 } 4785 undefinedList.add(info); 4786 } 4787 } 4788 } 4789 4790 // We'll want to include browser possibilities in a few cases 4791 boolean includeBrowser = false; 4792 4793 // First try to add the "always" resolution(s) for the current user, if any 4794 if (alwaysList.size() > 0) { 4795 result.addAll(alwaysList); 4796 } else { 4797 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4798 result.addAll(undefinedList); 4799 // Maybe add one for the other profile. 4800 if (xpDomainInfo != null && ( 4801 xpDomainInfo.bestDomainVerificationStatus 4802 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4803 result.add(xpDomainInfo.resolveInfo); 4804 } 4805 includeBrowser = true; 4806 } 4807 4808 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4809 // If there were 'always' entries their preferred order has been set, so we also 4810 // back that off to make the alternatives equivalent 4811 if (alwaysAskList.size() > 0) { 4812 for (ResolveInfo i : result) { 4813 i.preferredOrder = 0; 4814 } 4815 result.addAll(alwaysAskList); 4816 includeBrowser = true; 4817 } 4818 4819 if (includeBrowser) { 4820 // Also add browsers (all of them or only the default one) 4821 if (DEBUG_DOMAIN_VERIFICATION) { 4822 Slog.v(TAG, " ...including browsers in candidate set"); 4823 } 4824 if ((matchFlags & MATCH_ALL) != 0) { 4825 result.addAll(matchAllList); 4826 } else { 4827 // Browser/generic handling case. If there's a default browser, go straight 4828 // to that (but only if there is no other higher-priority match). 4829 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4830 int maxMatchPrio = 0; 4831 ResolveInfo defaultBrowserMatch = null; 4832 final int numCandidates = matchAllList.size(); 4833 for (int n = 0; n < numCandidates; n++) { 4834 ResolveInfo info = matchAllList.get(n); 4835 // track the highest overall match priority... 4836 if (info.priority > maxMatchPrio) { 4837 maxMatchPrio = info.priority; 4838 } 4839 // ...and the highest-priority default browser match 4840 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4841 if (defaultBrowserMatch == null 4842 || (defaultBrowserMatch.priority < info.priority)) { 4843 if (debug) { 4844 Slog.v(TAG, "Considering default browser match " + info); 4845 } 4846 defaultBrowserMatch = info; 4847 } 4848 } 4849 } 4850 if (defaultBrowserMatch != null 4851 && defaultBrowserMatch.priority >= maxMatchPrio 4852 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4853 { 4854 if (debug) { 4855 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4856 } 4857 result.add(defaultBrowserMatch); 4858 } else { 4859 result.addAll(matchAllList); 4860 } 4861 } 4862 4863 // If there is nothing selected, add all candidates and remove the ones that the user 4864 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4865 if (result.size() == 0) { 4866 result.addAll(candidates); 4867 result.removeAll(neverList); 4868 } 4869 } 4870 } 4871 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4872 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4873 result.size()); 4874 for (ResolveInfo info : result) { 4875 Slog.v(TAG, " + " + info.activityInfo); 4876 } 4877 } 4878 return result; 4879 } 4880 4881 // Returns a packed value as a long: 4882 // 4883 // high 'int'-sized word: link status: undefined/ask/never/always. 4884 // low 'int'-sized word: relative priority among 'always' results. 4885 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4886 long result = ps.getDomainVerificationStatusForUser(userId); 4887 // if none available, get the master status 4888 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4889 if (ps.getIntentFilterVerificationInfo() != null) { 4890 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4891 } 4892 } 4893 return result; 4894 } 4895 4896 private ResolveInfo querySkipCurrentProfileIntents( 4897 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4898 int flags, int sourceUserId) { 4899 if (matchingFilters != null) { 4900 int size = matchingFilters.size(); 4901 for (int i = 0; i < size; i ++) { 4902 CrossProfileIntentFilter filter = matchingFilters.get(i); 4903 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4904 // Checking if there are activities in the target user that can handle the 4905 // intent. 4906 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4907 resolvedType, flags, sourceUserId); 4908 if (resolveInfo != null) { 4909 return resolveInfo; 4910 } 4911 } 4912 } 4913 } 4914 return null; 4915 } 4916 4917 // Return matching ResolveInfo if any for skip current profile intent filters. 4918 private ResolveInfo queryCrossProfileIntents( 4919 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4920 int flags, int sourceUserId) { 4921 if (matchingFilters != null) { 4922 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4923 // match the same intent. For performance reasons, it is better not to 4924 // run queryIntent twice for the same userId 4925 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4926 int size = matchingFilters.size(); 4927 for (int i = 0; i < size; i++) { 4928 CrossProfileIntentFilter filter = matchingFilters.get(i); 4929 int targetUserId = filter.getTargetUserId(); 4930 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4931 && !alreadyTriedUserIds.get(targetUserId)) { 4932 // Checking if there are activities in the target user that can handle the 4933 // intent. 4934 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4935 resolvedType, flags, sourceUserId); 4936 if (resolveInfo != null) return resolveInfo; 4937 alreadyTriedUserIds.put(targetUserId, true); 4938 } 4939 } 4940 } 4941 return null; 4942 } 4943 4944 /** 4945 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4946 * will forward the intent to the filter's target user. 4947 * Otherwise, returns null. 4948 */ 4949 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4950 String resolvedType, int flags, int sourceUserId) { 4951 int targetUserId = filter.getTargetUserId(); 4952 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4953 resolvedType, flags, targetUserId); 4954 if (resultTargetUser != null && !resultTargetUser.isEmpty() 4955 && isUserEnabled(targetUserId)) { 4956 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 4957 } 4958 return null; 4959 } 4960 4961 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 4962 int sourceUserId, int targetUserId) { 4963 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4964 long ident = Binder.clearCallingIdentity(); 4965 boolean targetIsProfile; 4966 try { 4967 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4968 } finally { 4969 Binder.restoreCallingIdentity(ident); 4970 } 4971 String className; 4972 if (targetIsProfile) { 4973 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4974 } else { 4975 className = FORWARD_INTENT_TO_PARENT; 4976 } 4977 ComponentName forwardingActivityComponentName = new ComponentName( 4978 mAndroidApplication.packageName, className); 4979 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4980 sourceUserId); 4981 if (!targetIsProfile) { 4982 forwardingActivityInfo.showUserIcon = targetUserId; 4983 forwardingResolveInfo.noResourceId = true; 4984 } 4985 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4986 forwardingResolveInfo.priority = 0; 4987 forwardingResolveInfo.preferredOrder = 0; 4988 forwardingResolveInfo.match = 0; 4989 forwardingResolveInfo.isDefault = true; 4990 forwardingResolveInfo.filter = filter; 4991 forwardingResolveInfo.targetUserId = targetUserId; 4992 return forwardingResolveInfo; 4993 } 4994 4995 @Override 4996 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4997 Intent[] specifics, String[] specificTypes, Intent intent, 4998 String resolvedType, int flags, int userId) { 4999 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5000 flags = augmentFlagsForUser(flags, userId); 5001 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5002 false, "query intent activity options"); 5003 final String resultsAction = intent.getAction(); 5004 5005 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5006 | PackageManager.GET_RESOLVED_FILTER, userId); 5007 5008 if (DEBUG_INTENT_MATCHING) { 5009 Log.v(TAG, "Query " + intent + ": " + results); 5010 } 5011 5012 int specificsPos = 0; 5013 int N; 5014 5015 // todo: note that the algorithm used here is O(N^2). This 5016 // isn't a problem in our current environment, but if we start running 5017 // into situations where we have more than 5 or 10 matches then this 5018 // should probably be changed to something smarter... 5019 5020 // First we go through and resolve each of the specific items 5021 // that were supplied, taking care of removing any corresponding 5022 // duplicate items in the generic resolve list. 5023 if (specifics != null) { 5024 for (int i=0; i<specifics.length; i++) { 5025 final Intent sintent = specifics[i]; 5026 if (sintent == null) { 5027 continue; 5028 } 5029 5030 if (DEBUG_INTENT_MATCHING) { 5031 Log.v(TAG, "Specific #" + i + ": " + sintent); 5032 } 5033 5034 String action = sintent.getAction(); 5035 if (resultsAction != null && resultsAction.equals(action)) { 5036 // If this action was explicitly requested, then don't 5037 // remove things that have it. 5038 action = null; 5039 } 5040 5041 ResolveInfo ri = null; 5042 ActivityInfo ai = null; 5043 5044 ComponentName comp = sintent.getComponent(); 5045 if (comp == null) { 5046 ri = resolveIntent( 5047 sintent, 5048 specificTypes != null ? specificTypes[i] : null, 5049 flags, userId); 5050 if (ri == null) { 5051 continue; 5052 } 5053 if (ri == mResolveInfo) { 5054 // ACK! Must do something better with this. 5055 } 5056 ai = ri.activityInfo; 5057 comp = new ComponentName(ai.applicationInfo.packageName, 5058 ai.name); 5059 } else { 5060 ai = getActivityInfo(comp, flags, userId); 5061 if (ai == null) { 5062 continue; 5063 } 5064 } 5065 5066 // Look for any generic query activities that are duplicates 5067 // of this specific one, and remove them from the results. 5068 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5069 N = results.size(); 5070 int j; 5071 for (j=specificsPos; j<N; j++) { 5072 ResolveInfo sri = results.get(j); 5073 if ((sri.activityInfo.name.equals(comp.getClassName()) 5074 && sri.activityInfo.applicationInfo.packageName.equals( 5075 comp.getPackageName())) 5076 || (action != null && sri.filter.matchAction(action))) { 5077 results.remove(j); 5078 if (DEBUG_INTENT_MATCHING) Log.v( 5079 TAG, "Removing duplicate item from " + j 5080 + " due to specific " + specificsPos); 5081 if (ri == null) { 5082 ri = sri; 5083 } 5084 j--; 5085 N--; 5086 } 5087 } 5088 5089 // Add this specific item to its proper place. 5090 if (ri == null) { 5091 ri = new ResolveInfo(); 5092 ri.activityInfo = ai; 5093 } 5094 results.add(specificsPos, ri); 5095 ri.specificIndex = i; 5096 specificsPos++; 5097 } 5098 } 5099 5100 // Now we go through the remaining generic results and remove any 5101 // duplicate actions that are found here. 5102 N = results.size(); 5103 for (int i=specificsPos; i<N-1; i++) { 5104 final ResolveInfo rii = results.get(i); 5105 if (rii.filter == null) { 5106 continue; 5107 } 5108 5109 // Iterate over all of the actions of this result's intent 5110 // filter... typically this should be just one. 5111 final Iterator<String> it = rii.filter.actionsIterator(); 5112 if (it == null) { 5113 continue; 5114 } 5115 while (it.hasNext()) { 5116 final String action = it.next(); 5117 if (resultsAction != null && resultsAction.equals(action)) { 5118 // If this action was explicitly requested, then don't 5119 // remove things that have it. 5120 continue; 5121 } 5122 for (int j=i+1; j<N; j++) { 5123 final ResolveInfo rij = results.get(j); 5124 if (rij.filter != null && rij.filter.hasAction(action)) { 5125 results.remove(j); 5126 if (DEBUG_INTENT_MATCHING) Log.v( 5127 TAG, "Removing duplicate item from " + j 5128 + " due to action " + action + " at " + i); 5129 j--; 5130 N--; 5131 } 5132 } 5133 } 5134 5135 // If the caller didn't request filter information, drop it now 5136 // so we don't have to marshall/unmarshall it. 5137 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5138 rii.filter = null; 5139 } 5140 } 5141 5142 // Filter out the caller activity if so requested. 5143 if (caller != null) { 5144 N = results.size(); 5145 for (int i=0; i<N; i++) { 5146 ActivityInfo ainfo = results.get(i).activityInfo; 5147 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5148 && caller.getClassName().equals(ainfo.name)) { 5149 results.remove(i); 5150 break; 5151 } 5152 } 5153 } 5154 5155 // If the caller didn't request filter information, 5156 // drop them now so we don't have to 5157 // marshall/unmarshall it. 5158 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5159 N = results.size(); 5160 for (int i=0; i<N; i++) { 5161 results.get(i).filter = null; 5162 } 5163 } 5164 5165 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5166 return results; 5167 } 5168 5169 @Override 5170 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5171 int userId) { 5172 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5173 flags = augmentFlagsForUser(flags, userId); 5174 ComponentName comp = intent.getComponent(); 5175 if (comp == null) { 5176 if (intent.getSelector() != null) { 5177 intent = intent.getSelector(); 5178 comp = intent.getComponent(); 5179 } 5180 } 5181 if (comp != null) { 5182 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5183 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5184 if (ai != null) { 5185 ResolveInfo ri = new ResolveInfo(); 5186 ri.activityInfo = ai; 5187 list.add(ri); 5188 } 5189 return list; 5190 } 5191 5192 // reader 5193 synchronized (mPackages) { 5194 String pkgName = intent.getPackage(); 5195 if (pkgName == null) { 5196 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5197 } 5198 final PackageParser.Package pkg = mPackages.get(pkgName); 5199 if (pkg != null) { 5200 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5201 userId); 5202 } 5203 return null; 5204 } 5205 } 5206 5207 @Override 5208 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5209 if (!sUserManager.exists(userId)) return null; 5210 flags = augmentFlagsForUser(flags, userId); 5211 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5212 if (query != null) { 5213 if (query.size() >= 1) { 5214 // If there is more than one service with the same priority, 5215 // just arbitrarily pick the first one. 5216 return query.get(0); 5217 } 5218 } 5219 return null; 5220 } 5221 5222 @Override 5223 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5224 int userId) { 5225 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5226 flags = augmentFlagsForUser(flags, userId); 5227 ComponentName comp = intent.getComponent(); 5228 if (comp == null) { 5229 if (intent.getSelector() != null) { 5230 intent = intent.getSelector(); 5231 comp = intent.getComponent(); 5232 } 5233 } 5234 if (comp != null) { 5235 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5236 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5237 if (si != null) { 5238 final ResolveInfo ri = new ResolveInfo(); 5239 ri.serviceInfo = si; 5240 list.add(ri); 5241 } 5242 return list; 5243 } 5244 5245 // reader 5246 synchronized (mPackages) { 5247 String pkgName = intent.getPackage(); 5248 if (pkgName == null) { 5249 return mServices.queryIntent(intent, resolvedType, flags, userId); 5250 } 5251 final PackageParser.Package pkg = mPackages.get(pkgName); 5252 if (pkg != null) { 5253 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5254 userId); 5255 } 5256 return null; 5257 } 5258 } 5259 5260 @Override 5261 public List<ResolveInfo> queryIntentContentProviders( 5262 Intent intent, String resolvedType, int flags, int userId) { 5263 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5264 flags = augmentFlagsForUser(flags, userId); 5265 ComponentName comp = intent.getComponent(); 5266 if (comp == null) { 5267 if (intent.getSelector() != null) { 5268 intent = intent.getSelector(); 5269 comp = intent.getComponent(); 5270 } 5271 } 5272 if (comp != null) { 5273 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5274 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5275 if (pi != null) { 5276 final ResolveInfo ri = new ResolveInfo(); 5277 ri.providerInfo = pi; 5278 list.add(ri); 5279 } 5280 return list; 5281 } 5282 5283 // reader 5284 synchronized (mPackages) { 5285 String pkgName = intent.getPackage(); 5286 if (pkgName == null) { 5287 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5288 } 5289 final PackageParser.Package pkg = mPackages.get(pkgName); 5290 if (pkg != null) { 5291 return mProviders.queryIntentForPackage( 5292 intent, resolvedType, flags, pkg.providers, userId); 5293 } 5294 return null; 5295 } 5296 } 5297 5298 @Override 5299 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5300 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5301 5302 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5303 5304 // writer 5305 synchronized (mPackages) { 5306 ArrayList<PackageInfo> list; 5307 if (listUninstalled) { 5308 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5309 for (PackageSetting ps : mSettings.mPackages.values()) { 5310 PackageInfo pi; 5311 if (ps.pkg != null) { 5312 pi = generatePackageInfo(ps.pkg, flags, userId); 5313 } else { 5314 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5315 } 5316 if (pi != null) { 5317 list.add(pi); 5318 } 5319 } 5320 } else { 5321 list = new ArrayList<PackageInfo>(mPackages.size()); 5322 for (PackageParser.Package p : mPackages.values()) { 5323 PackageInfo pi = generatePackageInfo(p, flags, userId); 5324 if (pi != null) { 5325 list.add(pi); 5326 } 5327 } 5328 } 5329 5330 return new ParceledListSlice<PackageInfo>(list); 5331 } 5332 } 5333 5334 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5335 String[] permissions, boolean[] tmp, int flags, int userId) { 5336 int numMatch = 0; 5337 final PermissionsState permissionsState = ps.getPermissionsState(); 5338 for (int i=0; i<permissions.length; i++) { 5339 final String permission = permissions[i]; 5340 if (permissionsState.hasPermission(permission, userId)) { 5341 tmp[i] = true; 5342 numMatch++; 5343 } else { 5344 tmp[i] = false; 5345 } 5346 } 5347 if (numMatch == 0) { 5348 return; 5349 } 5350 PackageInfo pi; 5351 if (ps.pkg != null) { 5352 pi = generatePackageInfo(ps.pkg, flags, userId); 5353 } else { 5354 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5355 } 5356 // The above might return null in cases of uninstalled apps or install-state 5357 // skew across users/profiles. 5358 if (pi != null) { 5359 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5360 if (numMatch == permissions.length) { 5361 pi.requestedPermissions = permissions; 5362 } else { 5363 pi.requestedPermissions = new String[numMatch]; 5364 numMatch = 0; 5365 for (int i=0; i<permissions.length; i++) { 5366 if (tmp[i]) { 5367 pi.requestedPermissions[numMatch] = permissions[i]; 5368 numMatch++; 5369 } 5370 } 5371 } 5372 } 5373 list.add(pi); 5374 } 5375 } 5376 5377 @Override 5378 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5379 String[] permissions, int flags, int userId) { 5380 if (!sUserManager.exists(userId)) return null; 5381 flags = augmentFlagsForUser(flags, userId); 5382 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5383 5384 // writer 5385 synchronized (mPackages) { 5386 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5387 boolean[] tmpBools = new boolean[permissions.length]; 5388 if (listUninstalled) { 5389 for (PackageSetting ps : mSettings.mPackages.values()) { 5390 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5391 } 5392 } else { 5393 for (PackageParser.Package pkg : mPackages.values()) { 5394 PackageSetting ps = (PackageSetting)pkg.mExtras; 5395 if (ps != null) { 5396 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5397 userId); 5398 } 5399 } 5400 } 5401 5402 return new ParceledListSlice<PackageInfo>(list); 5403 } 5404 } 5405 5406 @Override 5407 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5408 if (!sUserManager.exists(userId)) return null; 5409 flags = augmentFlagsForUser(flags, userId); 5410 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5411 5412 // writer 5413 synchronized (mPackages) { 5414 ArrayList<ApplicationInfo> list; 5415 if (listUninstalled) { 5416 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5417 for (PackageSetting ps : mSettings.mPackages.values()) { 5418 ApplicationInfo ai; 5419 if (ps.pkg != null) { 5420 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5421 ps.readUserState(userId), userId); 5422 } else { 5423 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5424 } 5425 if (ai != null) { 5426 list.add(ai); 5427 } 5428 } 5429 } else { 5430 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5431 for (PackageParser.Package p : mPackages.values()) { 5432 if (p.mExtras != null) { 5433 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5434 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5435 if (ai != null) { 5436 list.add(ai); 5437 } 5438 } 5439 } 5440 } 5441 5442 return new ParceledListSlice<ApplicationInfo>(list); 5443 } 5444 } 5445 5446 public List<ApplicationInfo> getPersistentApplications(int flags) { 5447 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5448 5449 // reader 5450 synchronized (mPackages) { 5451 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5452 final int userId = UserHandle.getCallingUserId(); 5453 while (i.hasNext()) { 5454 final PackageParser.Package p = i.next(); 5455 if (p.applicationInfo != null 5456 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5457 && (!mSafeMode || isSystemApp(p))) { 5458 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5459 if (ps != null) { 5460 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5461 ps.readUserState(userId), userId); 5462 if (ai != null) { 5463 finalList.add(ai); 5464 } 5465 } 5466 } 5467 } 5468 } 5469 5470 return finalList; 5471 } 5472 5473 @Override 5474 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5475 if (!sUserManager.exists(userId)) return null; 5476 flags = augmentFlagsForUser(flags, userId); 5477 // reader 5478 synchronized (mPackages) { 5479 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5480 PackageSetting ps = provider != null 5481 ? mSettings.mPackages.get(provider.owner.packageName) 5482 : null; 5483 return ps != null 5484 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5485 && (!mSafeMode || (provider.info.applicationInfo.flags 5486 &ApplicationInfo.FLAG_SYSTEM) != 0) 5487 ? PackageParser.generateProviderInfo(provider, flags, 5488 ps.readUserState(userId), userId) 5489 : null; 5490 } 5491 } 5492 5493 /** 5494 * @deprecated 5495 */ 5496 @Deprecated 5497 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5498 // reader 5499 synchronized (mPackages) { 5500 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5501 .entrySet().iterator(); 5502 final int userId = UserHandle.getCallingUserId(); 5503 while (i.hasNext()) { 5504 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5505 PackageParser.Provider p = entry.getValue(); 5506 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5507 5508 if (ps != null && p.syncable 5509 && (!mSafeMode || (p.info.applicationInfo.flags 5510 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5511 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5512 ps.readUserState(userId), userId); 5513 if (info != null) { 5514 outNames.add(entry.getKey()); 5515 outInfo.add(info); 5516 } 5517 } 5518 } 5519 } 5520 } 5521 5522 @Override 5523 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5524 int uid, int flags) { 5525 final int userId = processName != null ? UserHandle.getUserId(uid) 5526 : UserHandle.getCallingUserId(); 5527 if (!sUserManager.exists(userId)) return null; 5528 flags = augmentFlagsForUser(flags, userId); 5529 5530 ArrayList<ProviderInfo> finalList = null; 5531 // reader 5532 synchronized (mPackages) { 5533 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5534 while (i.hasNext()) { 5535 final PackageParser.Provider p = i.next(); 5536 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5537 if (ps != null && p.info.authority != null 5538 && (processName == null 5539 || (p.info.processName.equals(processName) 5540 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5541 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5542 && (!mSafeMode 5543 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5544 if (finalList == null) { 5545 finalList = new ArrayList<ProviderInfo>(3); 5546 } 5547 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5548 ps.readUserState(userId), userId); 5549 if (info != null) { 5550 finalList.add(info); 5551 } 5552 } 5553 } 5554 } 5555 5556 if (finalList != null) { 5557 Collections.sort(finalList, mProviderInitOrderSorter); 5558 return new ParceledListSlice<ProviderInfo>(finalList); 5559 } 5560 5561 return null; 5562 } 5563 5564 @Override 5565 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5566 int flags) { 5567 // reader 5568 synchronized (mPackages) { 5569 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5570 return PackageParser.generateInstrumentationInfo(i, flags); 5571 } 5572 } 5573 5574 @Override 5575 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5576 int flags) { 5577 ArrayList<InstrumentationInfo> finalList = 5578 new ArrayList<InstrumentationInfo>(); 5579 5580 // reader 5581 synchronized (mPackages) { 5582 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5583 while (i.hasNext()) { 5584 final PackageParser.Instrumentation p = i.next(); 5585 if (targetPackage == null 5586 || targetPackage.equals(p.info.targetPackage)) { 5587 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5588 flags); 5589 if (ii != null) { 5590 finalList.add(ii); 5591 } 5592 } 5593 } 5594 } 5595 5596 return finalList; 5597 } 5598 5599 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5600 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5601 if (overlays == null) { 5602 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5603 return; 5604 } 5605 for (PackageParser.Package opkg : overlays.values()) { 5606 // Not much to do if idmap fails: we already logged the error 5607 // and we certainly don't want to abort installation of pkg simply 5608 // because an overlay didn't fit properly. For these reasons, 5609 // ignore the return value of createIdmapForPackagePairLI. 5610 createIdmapForPackagePairLI(pkg, opkg); 5611 } 5612 } 5613 5614 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5615 PackageParser.Package opkg) { 5616 if (!opkg.mTrustedOverlay) { 5617 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5618 opkg.baseCodePath + ": overlay not trusted"); 5619 return false; 5620 } 5621 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5622 if (overlaySet == null) { 5623 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5624 opkg.baseCodePath + " but target package has no known overlays"); 5625 return false; 5626 } 5627 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5628 // TODO: generate idmap for split APKs 5629 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5630 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5631 + opkg.baseCodePath); 5632 return false; 5633 } 5634 PackageParser.Package[] overlayArray = 5635 overlaySet.values().toArray(new PackageParser.Package[0]); 5636 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5637 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5638 return p1.mOverlayPriority - p2.mOverlayPriority; 5639 } 5640 }; 5641 Arrays.sort(overlayArray, cmp); 5642 5643 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5644 int i = 0; 5645 for (PackageParser.Package p : overlayArray) { 5646 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5647 } 5648 return true; 5649 } 5650 5651 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5652 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5653 try { 5654 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5655 } finally { 5656 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5657 } 5658 } 5659 5660 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5661 final File[] files = dir.listFiles(); 5662 if (ArrayUtils.isEmpty(files)) { 5663 Log.d(TAG, "No files in app dir " + dir); 5664 return; 5665 } 5666 5667 if (DEBUG_PACKAGE_SCANNING) { 5668 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5669 + " flags=0x" + Integer.toHexString(parseFlags)); 5670 } 5671 5672 for (File file : files) { 5673 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5674 && !PackageInstallerService.isStageName(file.getName()); 5675 if (!isPackage) { 5676 // Ignore entries which are not packages 5677 continue; 5678 } 5679 try { 5680 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5681 scanFlags, currentTime, null); 5682 } catch (PackageManagerException e) { 5683 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5684 5685 // Delete invalid userdata apps 5686 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5687 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5688 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5689 if (file.isDirectory()) { 5690 mInstaller.rmPackageDir(file.getAbsolutePath()); 5691 } else { 5692 file.delete(); 5693 } 5694 } 5695 } 5696 } 5697 } 5698 5699 private static File getSettingsProblemFile() { 5700 File dataDir = Environment.getDataDirectory(); 5701 File systemDir = new File(dataDir, "system"); 5702 File fname = new File(systemDir, "uiderrors.txt"); 5703 return fname; 5704 } 5705 5706 static void reportSettingsProblem(int priority, String msg) { 5707 logCriticalInfo(priority, msg); 5708 } 5709 5710 static void logCriticalInfo(int priority, String msg) { 5711 Slog.println(priority, TAG, msg); 5712 EventLogTags.writePmCriticalInfo(msg); 5713 try { 5714 File fname = getSettingsProblemFile(); 5715 FileOutputStream out = new FileOutputStream(fname, true); 5716 PrintWriter pw = new FastPrintWriter(out); 5717 SimpleDateFormat formatter = new SimpleDateFormat(); 5718 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5719 pw.println(dateString + ": " + msg); 5720 pw.close(); 5721 FileUtils.setPermissions( 5722 fname.toString(), 5723 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5724 -1, -1); 5725 } catch (java.io.IOException e) { 5726 } 5727 } 5728 5729 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5730 PackageParser.Package pkg, File srcFile, int parseFlags) 5731 throws PackageManagerException { 5732 if (ps != null 5733 && ps.codePath.equals(srcFile) 5734 && ps.timeStamp == srcFile.lastModified() 5735 && !isCompatSignatureUpdateNeeded(pkg) 5736 && !isRecoverSignatureUpdateNeeded(pkg)) { 5737 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5738 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5739 ArraySet<PublicKey> signingKs; 5740 synchronized (mPackages) { 5741 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5742 } 5743 if (ps.signatures.mSignatures != null 5744 && ps.signatures.mSignatures.length != 0 5745 && signingKs != null) { 5746 // Optimization: reuse the existing cached certificates 5747 // if the package appears to be unchanged. 5748 pkg.mSignatures = ps.signatures.mSignatures; 5749 pkg.mSigningKeys = signingKs; 5750 return; 5751 } 5752 5753 Slog.w(TAG, "PackageSetting for " + ps.name 5754 + " is missing signatures. Collecting certs again to recover them."); 5755 } else { 5756 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5757 } 5758 5759 try { 5760 pp.collectCertificates(pkg, parseFlags); 5761 pp.collectManifestDigest(pkg); 5762 } catch (PackageParserException e) { 5763 throw PackageManagerException.from(e); 5764 } 5765 } 5766 5767 /** 5768 * Traces a package scan. 5769 * @see #scanPackageLI(File, int, int, long, UserHandle) 5770 */ 5771 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5772 long currentTime, UserHandle user) throws PackageManagerException { 5773 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5774 try { 5775 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5776 } finally { 5777 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5778 } 5779 } 5780 5781 /** 5782 * Scans a package and returns the newly parsed package. 5783 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5784 */ 5785 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5786 long currentTime, UserHandle user) throws PackageManagerException { 5787 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5788 parseFlags |= mDefParseFlags; 5789 PackageParser pp = new PackageParser(); 5790 pp.setSeparateProcesses(mSeparateProcesses); 5791 pp.setOnlyCoreApps(mOnlyCore); 5792 pp.setDisplayMetrics(mMetrics); 5793 5794 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5795 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5796 } 5797 5798 final PackageParser.Package pkg; 5799 try { 5800 pkg = pp.parsePackage(scanFile, parseFlags); 5801 } catch (PackageParserException e) { 5802 throw PackageManagerException.from(e); 5803 } 5804 5805 PackageSetting ps = null; 5806 PackageSetting updatedPkg; 5807 // reader 5808 synchronized (mPackages) { 5809 // Look to see if we already know about this package. 5810 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5811 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5812 // This package has been renamed to its original name. Let's 5813 // use that. 5814 ps = mSettings.peekPackageLPr(oldName); 5815 } 5816 // If there was no original package, see one for the real package name. 5817 if (ps == null) { 5818 ps = mSettings.peekPackageLPr(pkg.packageName); 5819 } 5820 // Check to see if this package could be hiding/updating a system 5821 // package. Must look for it either under the original or real 5822 // package name depending on our state. 5823 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5824 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5825 } 5826 boolean updatedPkgBetter = false; 5827 // First check if this is a system package that may involve an update 5828 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5829 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5830 // it needs to drop FLAG_PRIVILEGED. 5831 if (locationIsPrivileged(scanFile)) { 5832 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5833 } else { 5834 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5835 } 5836 5837 if (ps != null && !ps.codePath.equals(scanFile)) { 5838 // The path has changed from what was last scanned... check the 5839 // version of the new path against what we have stored to determine 5840 // what to do. 5841 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5842 if (pkg.mVersionCode <= ps.versionCode) { 5843 // The system package has been updated and the code path does not match 5844 // Ignore entry. Skip it. 5845 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5846 + " ignored: updated version " + ps.versionCode 5847 + " better than this " + pkg.mVersionCode); 5848 if (!updatedPkg.codePath.equals(scanFile)) { 5849 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5850 + ps.name + " changing from " + updatedPkg.codePathString 5851 + " to " + scanFile); 5852 updatedPkg.codePath = scanFile; 5853 updatedPkg.codePathString = scanFile.toString(); 5854 updatedPkg.resourcePath = scanFile; 5855 updatedPkg.resourcePathString = scanFile.toString(); 5856 } 5857 updatedPkg.pkg = pkg; 5858 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5859 "Package " + ps.name + " at " + scanFile 5860 + " ignored: updated version " + ps.versionCode 5861 + " better than this " + pkg.mVersionCode); 5862 } else { 5863 // The current app on the system partition is better than 5864 // what we have updated to on the data partition; switch 5865 // back to the system partition version. 5866 // At this point, its safely assumed that package installation for 5867 // apps in system partition will go through. If not there won't be a working 5868 // version of the app 5869 // writer 5870 synchronized (mPackages) { 5871 // Just remove the loaded entries from package lists. 5872 mPackages.remove(ps.name); 5873 } 5874 5875 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5876 + " reverting from " + ps.codePathString 5877 + ": new version " + pkg.mVersionCode 5878 + " better than installed " + ps.versionCode); 5879 5880 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5881 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5882 synchronized (mInstallLock) { 5883 args.cleanUpResourcesLI(); 5884 } 5885 synchronized (mPackages) { 5886 mSettings.enableSystemPackageLPw(ps.name); 5887 } 5888 updatedPkgBetter = true; 5889 } 5890 } 5891 } 5892 5893 if (updatedPkg != null) { 5894 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5895 // initially 5896 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5897 5898 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5899 // flag set initially 5900 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5901 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5902 } 5903 } 5904 5905 // Verify certificates against what was last scanned 5906 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5907 5908 /* 5909 * A new system app appeared, but we already had a non-system one of the 5910 * same name installed earlier. 5911 */ 5912 boolean shouldHideSystemApp = false; 5913 if (updatedPkg == null && ps != null 5914 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5915 /* 5916 * Check to make sure the signatures match first. If they don't, 5917 * wipe the installed application and its data. 5918 */ 5919 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5920 != PackageManager.SIGNATURE_MATCH) { 5921 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5922 + " signatures don't match existing userdata copy; removing"); 5923 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5924 ps = null; 5925 } else { 5926 /* 5927 * If the newly-added system app is an older version than the 5928 * already installed version, hide it. It will be scanned later 5929 * and re-added like an update. 5930 */ 5931 if (pkg.mVersionCode <= ps.versionCode) { 5932 shouldHideSystemApp = true; 5933 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5934 + " but new version " + pkg.mVersionCode + " better than installed " 5935 + ps.versionCode + "; hiding system"); 5936 } else { 5937 /* 5938 * The newly found system app is a newer version that the 5939 * one previously installed. Simply remove the 5940 * already-installed application and replace it with our own 5941 * while keeping the application data. 5942 */ 5943 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5944 + " reverting from " + ps.codePathString + ": new version " 5945 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5946 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5947 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5948 synchronized (mInstallLock) { 5949 args.cleanUpResourcesLI(); 5950 } 5951 } 5952 } 5953 } 5954 5955 // The apk is forward locked (not public) if its code and resources 5956 // are kept in different files. (except for app in either system or 5957 // vendor path). 5958 // TODO grab this value from PackageSettings 5959 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5960 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5961 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5962 } 5963 } 5964 5965 // TODO: extend to support forward-locked splits 5966 String resourcePath = null; 5967 String baseResourcePath = null; 5968 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5969 if (ps != null && ps.resourcePathString != null) { 5970 resourcePath = ps.resourcePathString; 5971 baseResourcePath = ps.resourcePathString; 5972 } else { 5973 // Should not happen at all. Just log an error. 5974 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5975 } 5976 } else { 5977 resourcePath = pkg.codePath; 5978 baseResourcePath = pkg.baseCodePath; 5979 } 5980 5981 // Set application objects path explicitly. 5982 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5983 pkg.applicationInfo.setCodePath(pkg.codePath); 5984 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5985 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5986 pkg.applicationInfo.setResourcePath(resourcePath); 5987 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5988 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5989 5990 // Note that we invoke the following method only if we are about to unpack an application 5991 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5992 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5993 5994 /* 5995 * If the system app should be overridden by a previously installed 5996 * data, hide the system app now and let the /data/app scan pick it up 5997 * again. 5998 */ 5999 if (shouldHideSystemApp) { 6000 synchronized (mPackages) { 6001 mSettings.disableSystemPackageLPw(pkg.packageName); 6002 } 6003 } 6004 6005 return scannedPkg; 6006 } 6007 6008 private static String fixProcessName(String defProcessName, 6009 String processName, int uid) { 6010 if (processName == null) { 6011 return defProcessName; 6012 } 6013 return processName; 6014 } 6015 6016 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6017 throws PackageManagerException { 6018 if (pkgSetting.signatures.mSignatures != null) { 6019 // Already existing package. Make sure signatures match 6020 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6021 == PackageManager.SIGNATURE_MATCH; 6022 if (!match) { 6023 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6024 == PackageManager.SIGNATURE_MATCH; 6025 } 6026 if (!match) { 6027 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6028 == PackageManager.SIGNATURE_MATCH; 6029 } 6030 if (!match) { 6031 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6032 + pkg.packageName + " signatures do not match the " 6033 + "previously installed version; ignoring!"); 6034 } 6035 } 6036 6037 // Check for shared user signatures 6038 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6039 // Already existing package. Make sure signatures match 6040 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6041 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6042 if (!match) { 6043 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6044 == PackageManager.SIGNATURE_MATCH; 6045 } 6046 if (!match) { 6047 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6048 == PackageManager.SIGNATURE_MATCH; 6049 } 6050 if (!match) { 6051 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6052 "Package " + pkg.packageName 6053 + " has no signatures that match those in shared user " 6054 + pkgSetting.sharedUser.name + "; ignoring!"); 6055 } 6056 } 6057 } 6058 6059 /** 6060 * Enforces that only the system UID or root's UID can call a method exposed 6061 * via Binder. 6062 * 6063 * @param message used as message if SecurityException is thrown 6064 * @throws SecurityException if the caller is not system or root 6065 */ 6066 private static final void enforceSystemOrRoot(String message) { 6067 final int uid = Binder.getCallingUid(); 6068 if (uid != Process.SYSTEM_UID && uid != 0) { 6069 throw new SecurityException(message); 6070 } 6071 } 6072 6073 @Override 6074 public void performFstrimIfNeeded() { 6075 enforceSystemOrRoot("Only the system can request fstrim"); 6076 6077 // Before everything else, see whether we need to fstrim. 6078 try { 6079 IMountService ms = PackageHelper.getMountService(); 6080 if (ms != null) { 6081 final boolean isUpgrade = isUpgrade(); 6082 boolean doTrim = isUpgrade; 6083 if (doTrim) { 6084 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6085 } else { 6086 final long interval = android.provider.Settings.Global.getLong( 6087 mContext.getContentResolver(), 6088 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6089 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6090 if (interval > 0) { 6091 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6092 if (timeSinceLast > interval) { 6093 doTrim = true; 6094 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6095 + "; running immediately"); 6096 } 6097 } 6098 } 6099 if (doTrim) { 6100 if (!isFirstBoot()) { 6101 try { 6102 ActivityManagerNative.getDefault().showBootMessage( 6103 mContext.getResources().getString( 6104 R.string.android_upgrading_fstrim), true); 6105 } catch (RemoteException e) { 6106 } 6107 } 6108 ms.runMaintenance(); 6109 } 6110 } else { 6111 Slog.e(TAG, "Mount service unavailable!"); 6112 } 6113 } catch (RemoteException e) { 6114 // Can't happen; MountService is local 6115 } 6116 } 6117 6118 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6119 List<ResolveInfo> ris = null; 6120 try { 6121 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6122 intent, null, 0, userId); 6123 } catch (RemoteException e) { 6124 } 6125 ArraySet<String> pkgNames = new ArraySet<String>(); 6126 if (ris != null) { 6127 for (ResolveInfo ri : ris) { 6128 pkgNames.add(ri.activityInfo.packageName); 6129 } 6130 } 6131 return pkgNames; 6132 } 6133 6134 @Override 6135 public void notifyPackageUse(String packageName) { 6136 synchronized (mPackages) { 6137 PackageParser.Package p = mPackages.get(packageName); 6138 if (p == null) { 6139 return; 6140 } 6141 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6142 } 6143 } 6144 6145 @Override 6146 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6147 return performDexOptTraced(packageName, instructionSet); 6148 } 6149 6150 public boolean performDexOpt(String packageName, String instructionSet) { 6151 return performDexOptTraced(packageName, instructionSet); 6152 } 6153 6154 private boolean performDexOptTraced(String packageName, String instructionSet) { 6155 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6156 try { 6157 return performDexOptInternal(packageName, instructionSet); 6158 } finally { 6159 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6160 } 6161 } 6162 6163 private boolean performDexOptInternal(String packageName, String instructionSet) { 6164 PackageParser.Package p; 6165 final String targetInstructionSet; 6166 synchronized (mPackages) { 6167 p = mPackages.get(packageName); 6168 if (p == null) { 6169 return false; 6170 } 6171 mPackageUsage.write(false); 6172 6173 targetInstructionSet = instructionSet != null ? instructionSet : 6174 getPrimaryInstructionSet(p.applicationInfo); 6175 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6176 return false; 6177 } 6178 } 6179 long callingId = Binder.clearCallingIdentity(); 6180 try { 6181 synchronized (mInstallLock) { 6182 final String[] instructionSets = new String[] { targetInstructionSet }; 6183 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6184 true /* inclDependencies */); 6185 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6186 } 6187 } finally { 6188 Binder.restoreCallingIdentity(callingId); 6189 } 6190 } 6191 6192 public ArraySet<String> getPackagesThatNeedDexOpt() { 6193 ArraySet<String> pkgs = null; 6194 synchronized (mPackages) { 6195 for (PackageParser.Package p : mPackages.values()) { 6196 if (DEBUG_DEXOPT) { 6197 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6198 } 6199 if (!p.mDexOptPerformed.isEmpty()) { 6200 continue; 6201 } 6202 if (pkgs == null) { 6203 pkgs = new ArraySet<String>(); 6204 } 6205 pkgs.add(p.packageName); 6206 } 6207 } 6208 return pkgs; 6209 } 6210 6211 public void shutdown() { 6212 mPackageUsage.write(true); 6213 } 6214 6215 @Override 6216 public void forceDexOpt(String packageName) { 6217 enforceSystemOrRoot("forceDexOpt"); 6218 6219 PackageParser.Package pkg; 6220 synchronized (mPackages) { 6221 pkg = mPackages.get(packageName); 6222 if (pkg == null) { 6223 throw new IllegalArgumentException("Missing package: " + packageName); 6224 } 6225 } 6226 6227 synchronized (mInstallLock) { 6228 final String[] instructionSets = new String[] { 6229 getPrimaryInstructionSet(pkg.applicationInfo) }; 6230 6231 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6232 6233 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6234 true /* inclDependencies */); 6235 6236 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6237 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6238 throw new IllegalStateException("Failed to dexopt: " + res); 6239 } 6240 } 6241 } 6242 6243 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6244 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6245 Slog.w(TAG, "Unable to update from " + oldPkg.name 6246 + " to " + newPkg.packageName 6247 + ": old package not in system partition"); 6248 return false; 6249 } else if (mPackages.get(oldPkg.name) != null) { 6250 Slog.w(TAG, "Unable to update from " + oldPkg.name 6251 + " to " + newPkg.packageName 6252 + ": old package still exists"); 6253 return false; 6254 } 6255 return true; 6256 } 6257 6258 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6259 int[] users = sUserManager.getUserIds(); 6260 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6261 if (res < 0) { 6262 return res; 6263 } 6264 for (int user : users) { 6265 if (user != 0) { 6266 res = mInstaller.createUserData(volumeUuid, packageName, 6267 UserHandle.getUid(user, uid), user, seinfo); 6268 if (res < 0) { 6269 return res; 6270 } 6271 } 6272 } 6273 return res; 6274 } 6275 6276 private int removeDataDirsLI(String volumeUuid, String packageName) { 6277 int[] users = sUserManager.getUserIds(); 6278 int res = 0; 6279 for (int user : users) { 6280 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6281 if (resInner < 0) { 6282 res = resInner; 6283 } 6284 } 6285 6286 return res; 6287 } 6288 6289 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6290 int[] users = sUserManager.getUserIds(); 6291 int res = 0; 6292 for (int user : users) { 6293 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6294 if (resInner < 0) { 6295 res = resInner; 6296 } 6297 } 6298 return res; 6299 } 6300 6301 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6302 PackageParser.Package changingLib) { 6303 if (file.path != null) { 6304 usesLibraryFiles.add(file.path); 6305 return; 6306 } 6307 PackageParser.Package p = mPackages.get(file.apk); 6308 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6309 // If we are doing this while in the middle of updating a library apk, 6310 // then we need to make sure to use that new apk for determining the 6311 // dependencies here. (We haven't yet finished committing the new apk 6312 // to the package manager state.) 6313 if (p == null || p.packageName.equals(changingLib.packageName)) { 6314 p = changingLib; 6315 } 6316 } 6317 if (p != null) { 6318 usesLibraryFiles.addAll(p.getAllCodePaths()); 6319 } 6320 } 6321 6322 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6323 PackageParser.Package changingLib) throws PackageManagerException { 6324 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6325 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6326 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6327 for (int i=0; i<N; i++) { 6328 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6329 if (file == null) { 6330 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6331 "Package " + pkg.packageName + " requires unavailable shared library " 6332 + pkg.usesLibraries.get(i) + "; failing!"); 6333 } 6334 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6335 } 6336 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6337 for (int i=0; i<N; i++) { 6338 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6339 if (file == null) { 6340 Slog.w(TAG, "Package " + pkg.packageName 6341 + " desires unavailable shared library " 6342 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6343 } else { 6344 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6345 } 6346 } 6347 N = usesLibraryFiles.size(); 6348 if (N > 0) { 6349 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6350 } else { 6351 pkg.usesLibraryFiles = null; 6352 } 6353 } 6354 } 6355 6356 private static boolean hasString(List<String> list, List<String> which) { 6357 if (list == null) { 6358 return false; 6359 } 6360 for (int i=list.size()-1; i>=0; i--) { 6361 for (int j=which.size()-1; j>=0; j--) { 6362 if (which.get(j).equals(list.get(i))) { 6363 return true; 6364 } 6365 } 6366 } 6367 return false; 6368 } 6369 6370 private void updateAllSharedLibrariesLPw() { 6371 for (PackageParser.Package pkg : mPackages.values()) { 6372 try { 6373 updateSharedLibrariesLPw(pkg, null); 6374 } catch (PackageManagerException e) { 6375 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6376 } 6377 } 6378 } 6379 6380 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6381 PackageParser.Package changingPkg) { 6382 ArrayList<PackageParser.Package> res = null; 6383 for (PackageParser.Package pkg : mPackages.values()) { 6384 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6385 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6386 if (res == null) { 6387 res = new ArrayList<PackageParser.Package>(); 6388 } 6389 res.add(pkg); 6390 try { 6391 updateSharedLibrariesLPw(pkg, changingPkg); 6392 } catch (PackageManagerException e) { 6393 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6394 } 6395 } 6396 } 6397 return res; 6398 } 6399 6400 /** 6401 * Derive the value of the {@code cpuAbiOverride} based on the provided 6402 * value and an optional stored value from the package settings. 6403 */ 6404 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6405 String cpuAbiOverride = null; 6406 6407 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6408 cpuAbiOverride = null; 6409 } else if (abiOverride != null) { 6410 cpuAbiOverride = abiOverride; 6411 } else if (settings != null) { 6412 cpuAbiOverride = settings.cpuAbiOverrideString; 6413 } 6414 6415 return cpuAbiOverride; 6416 } 6417 6418 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6419 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6420 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6421 try { 6422 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6423 } finally { 6424 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6425 } 6426 } 6427 6428 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6429 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6430 boolean success = false; 6431 try { 6432 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6433 currentTime, user); 6434 success = true; 6435 return res; 6436 } finally { 6437 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6438 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6439 } 6440 } 6441 } 6442 6443 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6444 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6445 final File scanFile = new File(pkg.codePath); 6446 if (pkg.applicationInfo.getCodePath() == null || 6447 pkg.applicationInfo.getResourcePath() == null) { 6448 // Bail out. The resource and code paths haven't been set. 6449 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6450 "Code and resource paths haven't been set correctly"); 6451 } 6452 6453 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6454 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6455 } else { 6456 // Only allow system apps to be flagged as core apps. 6457 pkg.coreApp = false; 6458 } 6459 6460 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6461 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6462 } 6463 6464 if (mCustomResolverComponentName != null && 6465 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6466 setUpCustomResolverActivity(pkg); 6467 } 6468 6469 if (pkg.packageName.equals("android")) { 6470 synchronized (mPackages) { 6471 if (mAndroidApplication != null) { 6472 Slog.w(TAG, "*************************************************"); 6473 Slog.w(TAG, "Core android package being redefined. Skipping."); 6474 Slog.w(TAG, " file=" + scanFile); 6475 Slog.w(TAG, "*************************************************"); 6476 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6477 "Core android package being redefined. Skipping."); 6478 } 6479 6480 // Set up information for our fall-back user intent resolution activity. 6481 mPlatformPackage = pkg; 6482 pkg.mVersionCode = mSdkVersion; 6483 mAndroidApplication = pkg.applicationInfo; 6484 6485 if (!mResolverReplaced) { 6486 mResolveActivity.applicationInfo = mAndroidApplication; 6487 mResolveActivity.name = ResolverActivity.class.getName(); 6488 mResolveActivity.packageName = mAndroidApplication.packageName; 6489 mResolveActivity.processName = "system:ui"; 6490 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6491 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6492 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6493 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6494 mResolveActivity.exported = true; 6495 mResolveActivity.enabled = true; 6496 mResolveInfo.activityInfo = mResolveActivity; 6497 mResolveInfo.priority = 0; 6498 mResolveInfo.preferredOrder = 0; 6499 mResolveInfo.match = 0; 6500 mResolveComponentName = new ComponentName( 6501 mAndroidApplication.packageName, mResolveActivity.name); 6502 } 6503 } 6504 } 6505 6506 if (DEBUG_PACKAGE_SCANNING) { 6507 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6508 Log.d(TAG, "Scanning package " + pkg.packageName); 6509 } 6510 6511 if (mPackages.containsKey(pkg.packageName) 6512 || mSharedLibraries.containsKey(pkg.packageName)) { 6513 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6514 "Application package " + pkg.packageName 6515 + " already installed. Skipping duplicate."); 6516 } 6517 6518 // If we're only installing presumed-existing packages, require that the 6519 // scanned APK is both already known and at the path previously established 6520 // for it. Previously unknown packages we pick up normally, but if we have an 6521 // a priori expectation about this package's install presence, enforce it. 6522 // With a singular exception for new system packages. When an OTA contains 6523 // a new system package, we allow the codepath to change from a system location 6524 // to the user-installed location. If we don't allow this change, any newer, 6525 // user-installed version of the application will be ignored. 6526 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6527 if (mExpectingBetter.containsKey(pkg.packageName)) { 6528 logCriticalInfo(Log.WARN, 6529 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6530 } else { 6531 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6532 if (known != null) { 6533 if (DEBUG_PACKAGE_SCANNING) { 6534 Log.d(TAG, "Examining " + pkg.codePath 6535 + " and requiring known paths " + known.codePathString 6536 + " & " + known.resourcePathString); 6537 } 6538 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6539 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6540 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6541 "Application package " + pkg.packageName 6542 + " found at " + pkg.applicationInfo.getCodePath() 6543 + " but expected at " + known.codePathString + "; ignoring."); 6544 } 6545 } 6546 } 6547 } 6548 6549 // Initialize package source and resource directories 6550 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6551 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6552 6553 SharedUserSetting suid = null; 6554 PackageSetting pkgSetting = null; 6555 6556 if (!isSystemApp(pkg)) { 6557 // Only system apps can use these features. 6558 pkg.mOriginalPackages = null; 6559 pkg.mRealPackage = null; 6560 pkg.mAdoptPermissions = null; 6561 } 6562 6563 // writer 6564 synchronized (mPackages) { 6565 if (pkg.mSharedUserId != null) { 6566 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6567 if (suid == null) { 6568 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6569 "Creating application package " + pkg.packageName 6570 + " for shared user failed"); 6571 } 6572 if (DEBUG_PACKAGE_SCANNING) { 6573 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6574 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6575 + "): packages=" + suid.packages); 6576 } 6577 } 6578 6579 // Check if we are renaming from an original package name. 6580 PackageSetting origPackage = null; 6581 String realName = null; 6582 if (pkg.mOriginalPackages != null) { 6583 // This package may need to be renamed to a previously 6584 // installed name. Let's check on that... 6585 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6586 if (pkg.mOriginalPackages.contains(renamed)) { 6587 // This package had originally been installed as the 6588 // original name, and we have already taken care of 6589 // transitioning to the new one. Just update the new 6590 // one to continue using the old name. 6591 realName = pkg.mRealPackage; 6592 if (!pkg.packageName.equals(renamed)) { 6593 // Callers into this function may have already taken 6594 // care of renaming the package; only do it here if 6595 // it is not already done. 6596 pkg.setPackageName(renamed); 6597 } 6598 6599 } else { 6600 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6601 if ((origPackage = mSettings.peekPackageLPr( 6602 pkg.mOriginalPackages.get(i))) != null) { 6603 // We do have the package already installed under its 6604 // original name... should we use it? 6605 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6606 // New package is not compatible with original. 6607 origPackage = null; 6608 continue; 6609 } else if (origPackage.sharedUser != null) { 6610 // Make sure uid is compatible between packages. 6611 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6612 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6613 + " to " + pkg.packageName + ": old uid " 6614 + origPackage.sharedUser.name 6615 + " differs from " + pkg.mSharedUserId); 6616 origPackage = null; 6617 continue; 6618 } 6619 } else { 6620 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6621 + pkg.packageName + " to old name " + origPackage.name); 6622 } 6623 break; 6624 } 6625 } 6626 } 6627 } 6628 6629 if (mTransferedPackages.contains(pkg.packageName)) { 6630 Slog.w(TAG, "Package " + pkg.packageName 6631 + " was transferred to another, but its .apk remains"); 6632 } 6633 6634 // Just create the setting, don't add it yet. For already existing packages 6635 // the PkgSetting exists already and doesn't have to be created. 6636 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6637 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6638 pkg.applicationInfo.primaryCpuAbi, 6639 pkg.applicationInfo.secondaryCpuAbi, 6640 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6641 user, false); 6642 if (pkgSetting == null) { 6643 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6644 "Creating application package " + pkg.packageName + " failed"); 6645 } 6646 6647 if (pkgSetting.origPackage != null) { 6648 // If we are first transitioning from an original package, 6649 // fix up the new package's name now. We need to do this after 6650 // looking up the package under its new name, so getPackageLP 6651 // can take care of fiddling things correctly. 6652 pkg.setPackageName(origPackage.name); 6653 6654 // File a report about this. 6655 String msg = "New package " + pkgSetting.realName 6656 + " renamed to replace old package " + pkgSetting.name; 6657 reportSettingsProblem(Log.WARN, msg); 6658 6659 // Make a note of it. 6660 mTransferedPackages.add(origPackage.name); 6661 6662 // No longer need to retain this. 6663 pkgSetting.origPackage = null; 6664 } 6665 6666 if (realName != null) { 6667 // Make a note of it. 6668 mTransferedPackages.add(pkg.packageName); 6669 } 6670 6671 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6672 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6673 } 6674 6675 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6676 // Check all shared libraries and map to their actual file path. 6677 // We only do this here for apps not on a system dir, because those 6678 // are the only ones that can fail an install due to this. We 6679 // will take care of the system apps by updating all of their 6680 // library paths after the scan is done. 6681 updateSharedLibrariesLPw(pkg, null); 6682 } 6683 6684 if (mFoundPolicyFile) { 6685 SELinuxMMAC.assignSeinfoValue(pkg); 6686 } 6687 6688 pkg.applicationInfo.uid = pkgSetting.appId; 6689 pkg.mExtras = pkgSetting; 6690 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6691 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6692 // We just determined the app is signed correctly, so bring 6693 // over the latest parsed certs. 6694 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6695 } else { 6696 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6697 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6698 "Package " + pkg.packageName + " upgrade keys do not match the " 6699 + "previously installed version"); 6700 } else { 6701 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6702 String msg = "System package " + pkg.packageName 6703 + " signature changed; retaining data."; 6704 reportSettingsProblem(Log.WARN, msg); 6705 } 6706 } 6707 } else { 6708 try { 6709 verifySignaturesLP(pkgSetting, pkg); 6710 // We just determined the app is signed correctly, so bring 6711 // over the latest parsed certs. 6712 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6713 } catch (PackageManagerException e) { 6714 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6715 throw e; 6716 } 6717 // The signature has changed, but this package is in the system 6718 // image... let's recover! 6719 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6720 // However... if this package is part of a shared user, but it 6721 // doesn't match the signature of the shared user, let's fail. 6722 // What this means is that you can't change the signatures 6723 // associated with an overall shared user, which doesn't seem all 6724 // that unreasonable. 6725 if (pkgSetting.sharedUser != null) { 6726 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6727 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6728 throw new PackageManagerException( 6729 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6730 "Signature mismatch for shared user : " 6731 + pkgSetting.sharedUser); 6732 } 6733 } 6734 // File a report about this. 6735 String msg = "System package " + pkg.packageName 6736 + " signature changed; retaining data."; 6737 reportSettingsProblem(Log.WARN, msg); 6738 } 6739 } 6740 // Verify that this new package doesn't have any content providers 6741 // that conflict with existing packages. Only do this if the 6742 // package isn't already installed, since we don't want to break 6743 // things that are installed. 6744 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6745 final int N = pkg.providers.size(); 6746 int i; 6747 for (i=0; i<N; i++) { 6748 PackageParser.Provider p = pkg.providers.get(i); 6749 if (p.info.authority != null) { 6750 String names[] = p.info.authority.split(";"); 6751 for (int j = 0; j < names.length; j++) { 6752 if (mProvidersByAuthority.containsKey(names[j])) { 6753 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6754 final String otherPackageName = 6755 ((other != null && other.getComponentName() != null) ? 6756 other.getComponentName().getPackageName() : "?"); 6757 throw new PackageManagerException( 6758 INSTALL_FAILED_CONFLICTING_PROVIDER, 6759 "Can't install because provider name " + names[j] 6760 + " (in package " + pkg.applicationInfo.packageName 6761 + ") is already used by " + otherPackageName); 6762 } 6763 } 6764 } 6765 } 6766 } 6767 6768 if (pkg.mAdoptPermissions != null) { 6769 // This package wants to adopt ownership of permissions from 6770 // another package. 6771 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6772 final String origName = pkg.mAdoptPermissions.get(i); 6773 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6774 if (orig != null) { 6775 if (verifyPackageUpdateLPr(orig, pkg)) { 6776 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6777 + pkg.packageName); 6778 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6779 } 6780 } 6781 } 6782 } 6783 } 6784 6785 final String pkgName = pkg.packageName; 6786 6787 final long scanFileTime = scanFile.lastModified(); 6788 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6789 pkg.applicationInfo.processName = fixProcessName( 6790 pkg.applicationInfo.packageName, 6791 pkg.applicationInfo.processName, 6792 pkg.applicationInfo.uid); 6793 6794 if (pkg != mPlatformPackage) { 6795 // This is a normal package, need to make its data directory. 6796 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 6797 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 6798 6799 boolean uidError = false; 6800 if (dataPath.exists()) { 6801 int currentUid = 0; 6802 try { 6803 StructStat stat = Os.stat(dataPath.getPath()); 6804 currentUid = stat.st_uid; 6805 } catch (ErrnoException e) { 6806 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6807 } 6808 6809 // If we have mismatched owners for the data path, we have a problem. 6810 if (currentUid != pkg.applicationInfo.uid) { 6811 boolean recovered = false; 6812 if (currentUid == 0) { 6813 // The directory somehow became owned by root. Wow. 6814 // This is probably because the system was stopped while 6815 // installd was in the middle of messing with its libs 6816 // directory. Ask installd to fix that. 6817 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6818 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6819 if (ret >= 0) { 6820 recovered = true; 6821 String msg = "Package " + pkg.packageName 6822 + " unexpectedly changed to uid 0; recovered to " + 6823 + pkg.applicationInfo.uid; 6824 reportSettingsProblem(Log.WARN, msg); 6825 } 6826 } 6827 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6828 || (scanFlags&SCAN_BOOTING) != 0)) { 6829 // If this is a system app, we can at least delete its 6830 // current data so the application will still work. 6831 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6832 if (ret >= 0) { 6833 // TODO: Kill the processes first 6834 // Old data gone! 6835 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6836 ? "System package " : "Third party package "; 6837 String msg = prefix + pkg.packageName 6838 + " has changed from uid: " 6839 + currentUid + " to " 6840 + pkg.applicationInfo.uid + "; old data erased"; 6841 reportSettingsProblem(Log.WARN, msg); 6842 recovered = true; 6843 6844 // And now re-install the app. 6845 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6846 pkg.applicationInfo.seinfo); 6847 if (ret == -1) { 6848 // Ack should not happen! 6849 msg = prefix + pkg.packageName 6850 + " could not have data directory re-created after delete."; 6851 reportSettingsProblem(Log.WARN, msg); 6852 throw new PackageManagerException( 6853 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6854 } 6855 } 6856 if (!recovered) { 6857 mHasSystemUidErrors = true; 6858 } 6859 } else if (!recovered) { 6860 // If we allow this install to proceed, we will be broken. 6861 // Abort, abort! 6862 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6863 "scanPackageLI"); 6864 } 6865 if (!recovered) { 6866 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6867 + pkg.applicationInfo.uid + "/fs_" 6868 + currentUid; 6869 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6870 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6871 String msg = "Package " + pkg.packageName 6872 + " has mismatched uid: " 6873 + currentUid + " on disk, " 6874 + pkg.applicationInfo.uid + " in settings"; 6875 // writer 6876 synchronized (mPackages) { 6877 mSettings.mReadMessages.append(msg); 6878 mSettings.mReadMessages.append('\n'); 6879 uidError = true; 6880 if (!pkgSetting.uidError) { 6881 reportSettingsProblem(Log.ERROR, msg); 6882 } 6883 } 6884 } 6885 } 6886 6887 if (mShouldRestoreconData) { 6888 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6889 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6890 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6891 } 6892 } else { 6893 if (DEBUG_PACKAGE_SCANNING) { 6894 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6895 Log.v(TAG, "Want this data dir: " + dataPath); 6896 } 6897 //invoke installer to do the actual installation 6898 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6899 pkg.applicationInfo.seinfo); 6900 if (ret < 0) { 6901 // Error from installer 6902 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6903 "Unable to create data dirs [errorCode=" + ret + "]"); 6904 } 6905 } 6906 6907 // Get all of our default paths setup 6908 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 6909 6910 pkgSetting.uidError = uidError; 6911 } 6912 6913 final String path = scanFile.getPath(); 6914 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6915 6916 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6917 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6918 6919 // Some system apps still use directory structure for native libraries 6920 // in which case we might end up not detecting abi solely based on apk 6921 // structure. Try to detect abi based on directory structure. 6922 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6923 pkg.applicationInfo.primaryCpuAbi == null) { 6924 setBundledAppAbisAndRoots(pkg, pkgSetting); 6925 setNativeLibraryPaths(pkg); 6926 } 6927 6928 } else { 6929 if ((scanFlags & SCAN_MOVE) != 0) { 6930 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6931 // but we already have this packages package info in the PackageSetting. We just 6932 // use that and derive the native library path based on the new codepath. 6933 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6934 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6935 } 6936 6937 // Set native library paths again. For moves, the path will be updated based on the 6938 // ABIs we've determined above. For non-moves, the path will be updated based on the 6939 // ABIs we determined during compilation, but the path will depend on the final 6940 // package path (after the rename away from the stage path). 6941 setNativeLibraryPaths(pkg); 6942 } 6943 6944 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6945 final int[] userIds = sUserManager.getUserIds(); 6946 synchronized (mInstallLock) { 6947 // Make sure all user data directories are ready to roll; we're okay 6948 // if they already exist 6949 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6950 for (int userId : userIds) { 6951 if (userId != UserHandle.USER_SYSTEM) { 6952 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6953 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6954 pkg.applicationInfo.seinfo); 6955 } 6956 } 6957 } 6958 6959 // Create a native library symlink only if we have native libraries 6960 // and if the native libraries are 32 bit libraries. We do not provide 6961 // this symlink for 64 bit libraries. 6962 if (pkg.applicationInfo.primaryCpuAbi != null && 6963 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6964 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 6965 try { 6966 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6967 for (int userId : userIds) { 6968 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6969 nativeLibPath, userId) < 0) { 6970 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6971 "Failed linking native library dir (user=" + userId + ")"); 6972 } 6973 } 6974 } finally { 6975 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6976 } 6977 } 6978 } 6979 6980 // This is a special case for the "system" package, where the ABI is 6981 // dictated by the zygote configuration (and init.rc). We should keep track 6982 // of this ABI so that we can deal with "normal" applications that run under 6983 // the same UID correctly. 6984 if (mPlatformPackage == pkg) { 6985 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6986 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6987 } 6988 6989 // If there's a mismatch between the abi-override in the package setting 6990 // and the abiOverride specified for the install. Warn about this because we 6991 // would've already compiled the app without taking the package setting into 6992 // account. 6993 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6994 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6995 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6996 " for package: " + pkg.packageName); 6997 } 6998 } 6999 7000 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7001 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7002 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7003 7004 // Copy the derived override back to the parsed package, so that we can 7005 // update the package settings accordingly. 7006 pkg.cpuAbiOverride = cpuAbiOverride; 7007 7008 if (DEBUG_ABI_SELECTION) { 7009 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7010 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7011 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7012 } 7013 7014 // Push the derived path down into PackageSettings so we know what to 7015 // clean up at uninstall time. 7016 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7017 7018 if (DEBUG_ABI_SELECTION) { 7019 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7020 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7021 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7022 } 7023 7024 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7025 // We don't do this here during boot because we can do it all 7026 // at once after scanning all existing packages. 7027 // 7028 // We also do this *before* we perform dexopt on this package, so that 7029 // we can avoid redundant dexopts, and also to make sure we've got the 7030 // code and package path correct. 7031 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7032 pkg, true /* boot complete */); 7033 } 7034 7035 if (mFactoryTest && pkg.requestedPermissions.contains( 7036 android.Manifest.permission.FACTORY_TEST)) { 7037 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7038 } 7039 7040 ArrayList<PackageParser.Package> clientLibPkgs = null; 7041 7042 // writer 7043 synchronized (mPackages) { 7044 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7045 // Only system apps can add new shared libraries. 7046 if (pkg.libraryNames != null) { 7047 for (int i=0; i<pkg.libraryNames.size(); i++) { 7048 String name = pkg.libraryNames.get(i); 7049 boolean allowed = false; 7050 if (pkg.isUpdatedSystemApp()) { 7051 // New library entries can only be added through the 7052 // system image. This is important to get rid of a lot 7053 // of nasty edge cases: for example if we allowed a non- 7054 // system update of the app to add a library, then uninstalling 7055 // the update would make the library go away, and assumptions 7056 // we made such as through app install filtering would now 7057 // have allowed apps on the device which aren't compatible 7058 // with it. Better to just have the restriction here, be 7059 // conservative, and create many fewer cases that can negatively 7060 // impact the user experience. 7061 final PackageSetting sysPs = mSettings 7062 .getDisabledSystemPkgLPr(pkg.packageName); 7063 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7064 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7065 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7066 allowed = true; 7067 break; 7068 } 7069 } 7070 } 7071 } else { 7072 allowed = true; 7073 } 7074 if (allowed) { 7075 if (!mSharedLibraries.containsKey(name)) { 7076 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7077 } else if (!name.equals(pkg.packageName)) { 7078 Slog.w(TAG, "Package " + pkg.packageName + " library " 7079 + name + " already exists; skipping"); 7080 } 7081 } else { 7082 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7083 + name + " that is not declared on system image; skipping"); 7084 } 7085 } 7086 if ((scanFlags & SCAN_BOOTING) == 0) { 7087 // If we are not booting, we need to update any applications 7088 // that are clients of our shared library. If we are booting, 7089 // this will all be done once the scan is complete. 7090 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7091 } 7092 } 7093 } 7094 } 7095 7096 // Request the ActivityManager to kill the process(only for existing packages) 7097 // so that we do not end up in a confused state while the user is still using the older 7098 // version of the application while the new one gets installed. 7099 if ((scanFlags & SCAN_REPLACING) != 0) { 7100 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7101 7102 killApplication(pkg.applicationInfo.packageName, 7103 pkg.applicationInfo.uid, "replace pkg"); 7104 7105 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7106 } 7107 7108 // Also need to kill any apps that are dependent on the library. 7109 if (clientLibPkgs != null) { 7110 for (int i=0; i<clientLibPkgs.size(); i++) { 7111 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7112 killApplication(clientPkg.applicationInfo.packageName, 7113 clientPkg.applicationInfo.uid, "update lib"); 7114 } 7115 } 7116 7117 // Make sure we're not adding any bogus keyset info 7118 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7119 ksms.assertScannedPackageValid(pkg); 7120 7121 // writer 7122 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7123 7124 boolean createIdmapFailed = false; 7125 synchronized (mPackages) { 7126 // We don't expect installation to fail beyond this point 7127 7128 // Add the new setting to mSettings 7129 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7130 // Add the new setting to mPackages 7131 mPackages.put(pkg.applicationInfo.packageName, pkg); 7132 // Make sure we don't accidentally delete its data. 7133 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7134 while (iter.hasNext()) { 7135 PackageCleanItem item = iter.next(); 7136 if (pkgName.equals(item.packageName)) { 7137 iter.remove(); 7138 } 7139 } 7140 7141 // Take care of first install / last update times. 7142 if (currentTime != 0) { 7143 if (pkgSetting.firstInstallTime == 0) { 7144 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7145 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7146 pkgSetting.lastUpdateTime = currentTime; 7147 } 7148 } else if (pkgSetting.firstInstallTime == 0) { 7149 // We need *something*. Take time time stamp of the file. 7150 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7151 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7152 if (scanFileTime != pkgSetting.timeStamp) { 7153 // A package on the system image has changed; consider this 7154 // to be an update. 7155 pkgSetting.lastUpdateTime = scanFileTime; 7156 } 7157 } 7158 7159 // Add the package's KeySets to the global KeySetManagerService 7160 ksms.addScannedPackageLPw(pkg); 7161 7162 int N = pkg.providers.size(); 7163 StringBuilder r = null; 7164 int i; 7165 for (i=0; i<N; i++) { 7166 PackageParser.Provider p = pkg.providers.get(i); 7167 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7168 p.info.processName, pkg.applicationInfo.uid); 7169 mProviders.addProvider(p); 7170 p.syncable = p.info.isSyncable; 7171 if (p.info.authority != null) { 7172 String names[] = p.info.authority.split(";"); 7173 p.info.authority = null; 7174 for (int j = 0; j < names.length; j++) { 7175 if (j == 1 && p.syncable) { 7176 // We only want the first authority for a provider to possibly be 7177 // syncable, so if we already added this provider using a different 7178 // authority clear the syncable flag. We copy the provider before 7179 // changing it because the mProviders object contains a reference 7180 // to a provider that we don't want to change. 7181 // Only do this for the second authority since the resulting provider 7182 // object can be the same for all future authorities for this provider. 7183 p = new PackageParser.Provider(p); 7184 p.syncable = false; 7185 } 7186 if (!mProvidersByAuthority.containsKey(names[j])) { 7187 mProvidersByAuthority.put(names[j], p); 7188 if (p.info.authority == null) { 7189 p.info.authority = names[j]; 7190 } else { 7191 p.info.authority = p.info.authority + ";" + names[j]; 7192 } 7193 if (DEBUG_PACKAGE_SCANNING) { 7194 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7195 Log.d(TAG, "Registered content provider: " + names[j] 7196 + ", className = " + p.info.name + ", isSyncable = " 7197 + p.info.isSyncable); 7198 } 7199 } else { 7200 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7201 Slog.w(TAG, "Skipping provider name " + names[j] + 7202 " (in package " + pkg.applicationInfo.packageName + 7203 "): name already used by " 7204 + ((other != null && other.getComponentName() != null) 7205 ? other.getComponentName().getPackageName() : "?")); 7206 } 7207 } 7208 } 7209 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7210 if (r == null) { 7211 r = new StringBuilder(256); 7212 } else { 7213 r.append(' '); 7214 } 7215 r.append(p.info.name); 7216 } 7217 } 7218 if (r != null) { 7219 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7220 } 7221 7222 N = pkg.services.size(); 7223 r = null; 7224 for (i=0; i<N; i++) { 7225 PackageParser.Service s = pkg.services.get(i); 7226 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7227 s.info.processName, pkg.applicationInfo.uid); 7228 mServices.addService(s); 7229 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7230 if (r == null) { 7231 r = new StringBuilder(256); 7232 } else { 7233 r.append(' '); 7234 } 7235 r.append(s.info.name); 7236 } 7237 } 7238 if (r != null) { 7239 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7240 } 7241 7242 N = pkg.receivers.size(); 7243 r = null; 7244 for (i=0; i<N; i++) { 7245 PackageParser.Activity a = pkg.receivers.get(i); 7246 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7247 a.info.processName, pkg.applicationInfo.uid); 7248 mReceivers.addActivity(a, "receiver"); 7249 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7250 if (r == null) { 7251 r = new StringBuilder(256); 7252 } else { 7253 r.append(' '); 7254 } 7255 r.append(a.info.name); 7256 } 7257 } 7258 if (r != null) { 7259 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7260 } 7261 7262 N = pkg.activities.size(); 7263 r = null; 7264 for (i=0; i<N; i++) { 7265 PackageParser.Activity a = pkg.activities.get(i); 7266 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7267 a.info.processName, pkg.applicationInfo.uid); 7268 mActivities.addActivity(a, "activity"); 7269 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7270 if (r == null) { 7271 r = new StringBuilder(256); 7272 } else { 7273 r.append(' '); 7274 } 7275 r.append(a.info.name); 7276 } 7277 } 7278 if (r != null) { 7279 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7280 } 7281 7282 N = pkg.permissionGroups.size(); 7283 r = null; 7284 for (i=0; i<N; i++) { 7285 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7286 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7287 if (cur == null) { 7288 mPermissionGroups.put(pg.info.name, pg); 7289 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7290 if (r == null) { 7291 r = new StringBuilder(256); 7292 } else { 7293 r.append(' '); 7294 } 7295 r.append(pg.info.name); 7296 } 7297 } else { 7298 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7299 + pg.info.packageName + " ignored: original from " 7300 + cur.info.packageName); 7301 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7302 if (r == null) { 7303 r = new StringBuilder(256); 7304 } else { 7305 r.append(' '); 7306 } 7307 r.append("DUP:"); 7308 r.append(pg.info.name); 7309 } 7310 } 7311 } 7312 if (r != null) { 7313 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7314 } 7315 7316 N = pkg.permissions.size(); 7317 r = null; 7318 for (i=0; i<N; i++) { 7319 PackageParser.Permission p = pkg.permissions.get(i); 7320 7321 // Assume by default that we did not install this permission into the system. 7322 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7323 7324 // Now that permission groups have a special meaning, we ignore permission 7325 // groups for legacy apps to prevent unexpected behavior. In particular, 7326 // permissions for one app being granted to someone just becuase they happen 7327 // to be in a group defined by another app (before this had no implications). 7328 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7329 p.group = mPermissionGroups.get(p.info.group); 7330 // Warn for a permission in an unknown group. 7331 if (p.info.group != null && p.group == null) { 7332 Slog.w(TAG, "Permission " + p.info.name + " from package " 7333 + p.info.packageName + " in an unknown group " + p.info.group); 7334 } 7335 } 7336 7337 ArrayMap<String, BasePermission> permissionMap = 7338 p.tree ? mSettings.mPermissionTrees 7339 : mSettings.mPermissions; 7340 BasePermission bp = permissionMap.get(p.info.name); 7341 7342 // Allow system apps to redefine non-system permissions 7343 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7344 final boolean currentOwnerIsSystem = (bp.perm != null 7345 && isSystemApp(bp.perm.owner)); 7346 if (isSystemApp(p.owner)) { 7347 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7348 // It's a built-in permission and no owner, take ownership now 7349 bp.packageSetting = pkgSetting; 7350 bp.perm = p; 7351 bp.uid = pkg.applicationInfo.uid; 7352 bp.sourcePackage = p.info.packageName; 7353 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7354 } else if (!currentOwnerIsSystem) { 7355 String msg = "New decl " + p.owner + " of permission " 7356 + p.info.name + " is system; overriding " + bp.sourcePackage; 7357 reportSettingsProblem(Log.WARN, msg); 7358 bp = null; 7359 } 7360 } 7361 } 7362 7363 if (bp == null) { 7364 bp = new BasePermission(p.info.name, p.info.packageName, 7365 BasePermission.TYPE_NORMAL); 7366 permissionMap.put(p.info.name, bp); 7367 } 7368 7369 if (bp.perm == null) { 7370 if (bp.sourcePackage == null 7371 || bp.sourcePackage.equals(p.info.packageName)) { 7372 BasePermission tree = findPermissionTreeLP(p.info.name); 7373 if (tree == null 7374 || tree.sourcePackage.equals(p.info.packageName)) { 7375 bp.packageSetting = pkgSetting; 7376 bp.perm = p; 7377 bp.uid = pkg.applicationInfo.uid; 7378 bp.sourcePackage = p.info.packageName; 7379 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7380 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7381 if (r == null) { 7382 r = new StringBuilder(256); 7383 } else { 7384 r.append(' '); 7385 } 7386 r.append(p.info.name); 7387 } 7388 } else { 7389 Slog.w(TAG, "Permission " + p.info.name + " from package " 7390 + p.info.packageName + " ignored: base tree " 7391 + tree.name + " is from package " 7392 + tree.sourcePackage); 7393 } 7394 } else { 7395 Slog.w(TAG, "Permission " + p.info.name + " from package " 7396 + p.info.packageName + " ignored: original from " 7397 + bp.sourcePackage); 7398 } 7399 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7400 if (r == null) { 7401 r = new StringBuilder(256); 7402 } else { 7403 r.append(' '); 7404 } 7405 r.append("DUP:"); 7406 r.append(p.info.name); 7407 } 7408 if (bp.perm == p) { 7409 bp.protectionLevel = p.info.protectionLevel; 7410 } 7411 } 7412 7413 if (r != null) { 7414 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7415 } 7416 7417 N = pkg.instrumentation.size(); 7418 r = null; 7419 for (i=0; i<N; i++) { 7420 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7421 a.info.packageName = pkg.applicationInfo.packageName; 7422 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7423 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7424 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7425 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7426 a.info.dataDir = pkg.applicationInfo.dataDir; 7427 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7428 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7429 7430 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7431 // need other information about the application, like the ABI and what not ? 7432 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7433 mInstrumentation.put(a.getComponentName(), a); 7434 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7435 if (r == null) { 7436 r = new StringBuilder(256); 7437 } else { 7438 r.append(' '); 7439 } 7440 r.append(a.info.name); 7441 } 7442 } 7443 if (r != null) { 7444 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7445 } 7446 7447 if (pkg.protectedBroadcasts != null) { 7448 N = pkg.protectedBroadcasts.size(); 7449 for (i=0; i<N; i++) { 7450 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7451 } 7452 } 7453 7454 pkgSetting.setTimeStamp(scanFileTime); 7455 7456 // Create idmap files for pairs of (packages, overlay packages). 7457 // Note: "android", ie framework-res.apk, is handled by native layers. 7458 if (pkg.mOverlayTarget != null) { 7459 // This is an overlay package. 7460 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7461 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7462 mOverlays.put(pkg.mOverlayTarget, 7463 new ArrayMap<String, PackageParser.Package>()); 7464 } 7465 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7466 map.put(pkg.packageName, pkg); 7467 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7468 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7469 createIdmapFailed = true; 7470 } 7471 } 7472 } else if (mOverlays.containsKey(pkg.packageName) && 7473 !pkg.packageName.equals("android")) { 7474 // This is a regular package, with one or more known overlay packages. 7475 createIdmapsForPackageLI(pkg); 7476 } 7477 } 7478 7479 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7480 7481 if (createIdmapFailed) { 7482 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7483 "scanPackageLI failed to createIdmap"); 7484 } 7485 return pkg; 7486 } 7487 7488 /** 7489 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7490 * is derived purely on the basis of the contents of {@code scanFile} and 7491 * {@code cpuAbiOverride}. 7492 * 7493 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7494 */ 7495 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7496 String cpuAbiOverride, boolean extractLibs) 7497 throws PackageManagerException { 7498 // TODO: We can probably be smarter about this stuff. For installed apps, 7499 // we can calculate this information at install time once and for all. For 7500 // system apps, we can probably assume that this information doesn't change 7501 // after the first boot scan. As things stand, we do lots of unnecessary work. 7502 7503 // Give ourselves some initial paths; we'll come back for another 7504 // pass once we've determined ABI below. 7505 setNativeLibraryPaths(pkg); 7506 7507 // We would never need to extract libs for forward-locked and external packages, 7508 // since the container service will do it for us. We shouldn't attempt to 7509 // extract libs from system app when it was not updated. 7510 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7511 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7512 extractLibs = false; 7513 } 7514 7515 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7516 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7517 7518 NativeLibraryHelper.Handle handle = null; 7519 try { 7520 handle = NativeLibraryHelper.Handle.create(pkg); 7521 // TODO(multiArch): This can be null for apps that didn't go through the 7522 // usual installation process. We can calculate it again, like we 7523 // do during install time. 7524 // 7525 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7526 // unnecessary. 7527 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7528 7529 // Null out the abis so that they can be recalculated. 7530 pkg.applicationInfo.primaryCpuAbi = null; 7531 pkg.applicationInfo.secondaryCpuAbi = null; 7532 if (isMultiArch(pkg.applicationInfo)) { 7533 // Warn if we've set an abiOverride for multi-lib packages.. 7534 // By definition, we need to copy both 32 and 64 bit libraries for 7535 // such packages. 7536 if (pkg.cpuAbiOverride != null 7537 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7538 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7539 } 7540 7541 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7542 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7543 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7544 if (extractLibs) { 7545 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7546 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7547 useIsaSpecificSubdirs); 7548 } else { 7549 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7550 } 7551 } 7552 7553 maybeThrowExceptionForMultiArchCopy( 7554 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7555 7556 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7557 if (extractLibs) { 7558 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7559 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7560 useIsaSpecificSubdirs); 7561 } else { 7562 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7563 } 7564 } 7565 7566 maybeThrowExceptionForMultiArchCopy( 7567 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7568 7569 if (abi64 >= 0) { 7570 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7571 } 7572 7573 if (abi32 >= 0) { 7574 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7575 if (abi64 >= 0) { 7576 pkg.applicationInfo.secondaryCpuAbi = abi; 7577 } else { 7578 pkg.applicationInfo.primaryCpuAbi = abi; 7579 } 7580 } 7581 } else { 7582 String[] abiList = (cpuAbiOverride != null) ? 7583 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7584 7585 // Enable gross and lame hacks for apps that are built with old 7586 // SDK tools. We must scan their APKs for renderscript bitcode and 7587 // not launch them if it's present. Don't bother checking on devices 7588 // that don't have 64 bit support. 7589 boolean needsRenderScriptOverride = false; 7590 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7591 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7592 abiList = Build.SUPPORTED_32_BIT_ABIS; 7593 needsRenderScriptOverride = true; 7594 } 7595 7596 final int copyRet; 7597 if (extractLibs) { 7598 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7599 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7600 } else { 7601 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7602 } 7603 7604 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7605 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7606 "Error unpackaging native libs for app, errorCode=" + copyRet); 7607 } 7608 7609 if (copyRet >= 0) { 7610 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7611 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7612 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7613 } else if (needsRenderScriptOverride) { 7614 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7615 } 7616 } 7617 } catch (IOException ioe) { 7618 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7619 } finally { 7620 IoUtils.closeQuietly(handle); 7621 } 7622 7623 // Now that we've calculated the ABIs and determined if it's an internal app, 7624 // we will go ahead and populate the nativeLibraryPath. 7625 setNativeLibraryPaths(pkg); 7626 } 7627 7628 /** 7629 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7630 * i.e, so that all packages can be run inside a single process if required. 7631 * 7632 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7633 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7634 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7635 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7636 * updating a package that belongs to a shared user. 7637 * 7638 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7639 * adds unnecessary complexity. 7640 */ 7641 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7642 PackageParser.Package scannedPackage, boolean bootComplete) { 7643 String requiredInstructionSet = null; 7644 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7645 requiredInstructionSet = VMRuntime.getInstructionSet( 7646 scannedPackage.applicationInfo.primaryCpuAbi); 7647 } 7648 7649 PackageSetting requirer = null; 7650 for (PackageSetting ps : packagesForUser) { 7651 // If packagesForUser contains scannedPackage, we skip it. This will happen 7652 // when scannedPackage is an update of an existing package. Without this check, 7653 // we will never be able to change the ABI of any package belonging to a shared 7654 // user, even if it's compatible with other packages. 7655 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7656 if (ps.primaryCpuAbiString == null) { 7657 continue; 7658 } 7659 7660 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7661 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7662 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7663 // this but there's not much we can do. 7664 String errorMessage = "Instruction set mismatch, " 7665 + ((requirer == null) ? "[caller]" : requirer) 7666 + " requires " + requiredInstructionSet + " whereas " + ps 7667 + " requires " + instructionSet; 7668 Slog.w(TAG, errorMessage); 7669 } 7670 7671 if (requiredInstructionSet == null) { 7672 requiredInstructionSet = instructionSet; 7673 requirer = ps; 7674 } 7675 } 7676 } 7677 7678 if (requiredInstructionSet != null) { 7679 String adjustedAbi; 7680 if (requirer != null) { 7681 // requirer != null implies that either scannedPackage was null or that scannedPackage 7682 // did not require an ABI, in which case we have to adjust scannedPackage to match 7683 // the ABI of the set (which is the same as requirer's ABI) 7684 adjustedAbi = requirer.primaryCpuAbiString; 7685 if (scannedPackage != null) { 7686 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7687 } 7688 } else { 7689 // requirer == null implies that we're updating all ABIs in the set to 7690 // match scannedPackage. 7691 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7692 } 7693 7694 for (PackageSetting ps : packagesForUser) { 7695 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7696 if (ps.primaryCpuAbiString != null) { 7697 continue; 7698 } 7699 7700 ps.primaryCpuAbiString = adjustedAbi; 7701 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7702 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7703 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7704 mInstaller.rmdex(ps.codePathString, 7705 getDexCodeInstructionSet(getPreferredInstructionSet())); 7706 } 7707 } 7708 } 7709 } 7710 } 7711 7712 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7713 synchronized (mPackages) { 7714 mResolverReplaced = true; 7715 // Set up information for custom user intent resolution activity. 7716 mResolveActivity.applicationInfo = pkg.applicationInfo; 7717 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7718 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7719 mResolveActivity.processName = pkg.applicationInfo.packageName; 7720 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7721 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7722 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7723 mResolveActivity.theme = 0; 7724 mResolveActivity.exported = true; 7725 mResolveActivity.enabled = true; 7726 mResolveInfo.activityInfo = mResolveActivity; 7727 mResolveInfo.priority = 0; 7728 mResolveInfo.preferredOrder = 0; 7729 mResolveInfo.match = 0; 7730 mResolveComponentName = mCustomResolverComponentName; 7731 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7732 mResolveComponentName); 7733 } 7734 } 7735 7736 private static String calculateBundledApkRoot(final String codePathString) { 7737 final File codePath = new File(codePathString); 7738 final File codeRoot; 7739 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7740 codeRoot = Environment.getRootDirectory(); 7741 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7742 codeRoot = Environment.getOemDirectory(); 7743 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7744 codeRoot = Environment.getVendorDirectory(); 7745 } else { 7746 // Unrecognized code path; take its top real segment as the apk root: 7747 // e.g. /something/app/blah.apk => /something 7748 try { 7749 File f = codePath.getCanonicalFile(); 7750 File parent = f.getParentFile(); // non-null because codePath is a file 7751 File tmp; 7752 while ((tmp = parent.getParentFile()) != null) { 7753 f = parent; 7754 parent = tmp; 7755 } 7756 codeRoot = f; 7757 Slog.w(TAG, "Unrecognized code path " 7758 + codePath + " - using " + codeRoot); 7759 } catch (IOException e) { 7760 // Can't canonicalize the code path -- shenanigans? 7761 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7762 return Environment.getRootDirectory().getPath(); 7763 } 7764 } 7765 return codeRoot.getPath(); 7766 } 7767 7768 /** 7769 * Derive and set the location of native libraries for the given package, 7770 * which varies depending on where and how the package was installed. 7771 */ 7772 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7773 final ApplicationInfo info = pkg.applicationInfo; 7774 final String codePath = pkg.codePath; 7775 final File codeFile = new File(codePath); 7776 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7777 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7778 7779 info.nativeLibraryRootDir = null; 7780 info.nativeLibraryRootRequiresIsa = false; 7781 info.nativeLibraryDir = null; 7782 info.secondaryNativeLibraryDir = null; 7783 7784 if (isApkFile(codeFile)) { 7785 // Monolithic install 7786 if (bundledApp) { 7787 // If "/system/lib64/apkname" exists, assume that is the per-package 7788 // native library directory to use; otherwise use "/system/lib/apkname". 7789 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7790 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7791 getPrimaryInstructionSet(info)); 7792 7793 // This is a bundled system app so choose the path based on the ABI. 7794 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7795 // is just the default path. 7796 final String apkName = deriveCodePathName(codePath); 7797 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7798 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7799 apkName).getAbsolutePath(); 7800 7801 if (info.secondaryCpuAbi != null) { 7802 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7803 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7804 secondaryLibDir, apkName).getAbsolutePath(); 7805 } 7806 } else if (asecApp) { 7807 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7808 .getAbsolutePath(); 7809 } else { 7810 final String apkName = deriveCodePathName(codePath); 7811 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7812 .getAbsolutePath(); 7813 } 7814 7815 info.nativeLibraryRootRequiresIsa = false; 7816 info.nativeLibraryDir = info.nativeLibraryRootDir; 7817 } else { 7818 // Cluster install 7819 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7820 info.nativeLibraryRootRequiresIsa = true; 7821 7822 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7823 getPrimaryInstructionSet(info)).getAbsolutePath(); 7824 7825 if (info.secondaryCpuAbi != null) { 7826 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7827 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7828 } 7829 } 7830 } 7831 7832 /** 7833 * Calculate the abis and roots for a bundled app. These can uniquely 7834 * be determined from the contents of the system partition, i.e whether 7835 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7836 * of this information, and instead assume that the system was built 7837 * sensibly. 7838 */ 7839 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7840 PackageSetting pkgSetting) { 7841 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7842 7843 // If "/system/lib64/apkname" exists, assume that is the per-package 7844 // native library directory to use; otherwise use "/system/lib/apkname". 7845 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7846 setBundledAppAbi(pkg, apkRoot, apkName); 7847 // pkgSetting might be null during rescan following uninstall of updates 7848 // to a bundled app, so accommodate that possibility. The settings in 7849 // that case will be established later from the parsed package. 7850 // 7851 // If the settings aren't null, sync them up with what we've just derived. 7852 // note that apkRoot isn't stored in the package settings. 7853 if (pkgSetting != null) { 7854 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7855 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7856 } 7857 } 7858 7859 /** 7860 * Deduces the ABI of a bundled app and sets the relevant fields on the 7861 * parsed pkg object. 7862 * 7863 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7864 * under which system libraries are installed. 7865 * @param apkName the name of the installed package. 7866 */ 7867 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7868 final File codeFile = new File(pkg.codePath); 7869 7870 final boolean has64BitLibs; 7871 final boolean has32BitLibs; 7872 if (isApkFile(codeFile)) { 7873 // Monolithic install 7874 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7875 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7876 } else { 7877 // Cluster install 7878 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7879 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7880 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7881 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7882 has64BitLibs = (new File(rootDir, isa)).exists(); 7883 } else { 7884 has64BitLibs = false; 7885 } 7886 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7887 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7888 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7889 has32BitLibs = (new File(rootDir, isa)).exists(); 7890 } else { 7891 has32BitLibs = false; 7892 } 7893 } 7894 7895 if (has64BitLibs && !has32BitLibs) { 7896 // The package has 64 bit libs, but not 32 bit libs. Its primary 7897 // ABI should be 64 bit. We can safely assume here that the bundled 7898 // native libraries correspond to the most preferred ABI in the list. 7899 7900 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7901 pkg.applicationInfo.secondaryCpuAbi = null; 7902 } else if (has32BitLibs && !has64BitLibs) { 7903 // The package has 32 bit libs but not 64 bit libs. Its primary 7904 // ABI should be 32 bit. 7905 7906 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7907 pkg.applicationInfo.secondaryCpuAbi = null; 7908 } else if (has32BitLibs && has64BitLibs) { 7909 // The application has both 64 and 32 bit bundled libraries. We check 7910 // here that the app declares multiArch support, and warn if it doesn't. 7911 // 7912 // We will be lenient here and record both ABIs. The primary will be the 7913 // ABI that's higher on the list, i.e, a device that's configured to prefer 7914 // 64 bit apps will see a 64 bit primary ABI, 7915 7916 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7917 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7918 } 7919 7920 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7921 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7922 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7923 } else { 7924 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7925 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7926 } 7927 } else { 7928 pkg.applicationInfo.primaryCpuAbi = null; 7929 pkg.applicationInfo.secondaryCpuAbi = null; 7930 } 7931 } 7932 7933 private void killApplication(String pkgName, int appId, String reason) { 7934 // Request the ActivityManager to kill the process(only for existing packages) 7935 // so that we do not end up in a confused state while the user is still using the older 7936 // version of the application while the new one gets installed. 7937 IActivityManager am = ActivityManagerNative.getDefault(); 7938 if (am != null) { 7939 try { 7940 am.killApplicationWithAppId(pkgName, appId, reason); 7941 } catch (RemoteException e) { 7942 } 7943 } 7944 } 7945 7946 void removePackageLI(PackageSetting ps, boolean chatty) { 7947 if (DEBUG_INSTALL) { 7948 if (chatty) 7949 Log.d(TAG, "Removing package " + ps.name); 7950 } 7951 7952 // writer 7953 synchronized (mPackages) { 7954 mPackages.remove(ps.name); 7955 final PackageParser.Package pkg = ps.pkg; 7956 if (pkg != null) { 7957 cleanPackageDataStructuresLILPw(pkg, chatty); 7958 } 7959 } 7960 } 7961 7962 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7963 if (DEBUG_INSTALL) { 7964 if (chatty) 7965 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7966 } 7967 7968 // writer 7969 synchronized (mPackages) { 7970 mPackages.remove(pkg.applicationInfo.packageName); 7971 cleanPackageDataStructuresLILPw(pkg, chatty); 7972 } 7973 } 7974 7975 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7976 int N = pkg.providers.size(); 7977 StringBuilder r = null; 7978 int i; 7979 for (i=0; i<N; i++) { 7980 PackageParser.Provider p = pkg.providers.get(i); 7981 mProviders.removeProvider(p); 7982 if (p.info.authority == null) { 7983 7984 /* There was another ContentProvider with this authority when 7985 * this app was installed so this authority is null, 7986 * Ignore it as we don't have to unregister the provider. 7987 */ 7988 continue; 7989 } 7990 String names[] = p.info.authority.split(";"); 7991 for (int j = 0; j < names.length; j++) { 7992 if (mProvidersByAuthority.get(names[j]) == p) { 7993 mProvidersByAuthority.remove(names[j]); 7994 if (DEBUG_REMOVE) { 7995 if (chatty) 7996 Log.d(TAG, "Unregistered content provider: " + names[j] 7997 + ", className = " + p.info.name + ", isSyncable = " 7998 + p.info.isSyncable); 7999 } 8000 } 8001 } 8002 if (DEBUG_REMOVE && chatty) { 8003 if (r == null) { 8004 r = new StringBuilder(256); 8005 } else { 8006 r.append(' '); 8007 } 8008 r.append(p.info.name); 8009 } 8010 } 8011 if (r != null) { 8012 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8013 } 8014 8015 N = pkg.services.size(); 8016 r = null; 8017 for (i=0; i<N; i++) { 8018 PackageParser.Service s = pkg.services.get(i); 8019 mServices.removeService(s); 8020 if (chatty) { 8021 if (r == null) { 8022 r = new StringBuilder(256); 8023 } else { 8024 r.append(' '); 8025 } 8026 r.append(s.info.name); 8027 } 8028 } 8029 if (r != null) { 8030 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8031 } 8032 8033 N = pkg.receivers.size(); 8034 r = null; 8035 for (i=0; i<N; i++) { 8036 PackageParser.Activity a = pkg.receivers.get(i); 8037 mReceivers.removeActivity(a, "receiver"); 8038 if (DEBUG_REMOVE && chatty) { 8039 if (r == null) { 8040 r = new StringBuilder(256); 8041 } else { 8042 r.append(' '); 8043 } 8044 r.append(a.info.name); 8045 } 8046 } 8047 if (r != null) { 8048 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8049 } 8050 8051 N = pkg.activities.size(); 8052 r = null; 8053 for (i=0; i<N; i++) { 8054 PackageParser.Activity a = pkg.activities.get(i); 8055 mActivities.removeActivity(a, "activity"); 8056 if (DEBUG_REMOVE && chatty) { 8057 if (r == null) { 8058 r = new StringBuilder(256); 8059 } else { 8060 r.append(' '); 8061 } 8062 r.append(a.info.name); 8063 } 8064 } 8065 if (r != null) { 8066 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8067 } 8068 8069 N = pkg.permissions.size(); 8070 r = null; 8071 for (i=0; i<N; i++) { 8072 PackageParser.Permission p = pkg.permissions.get(i); 8073 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8074 if (bp == null) { 8075 bp = mSettings.mPermissionTrees.get(p.info.name); 8076 } 8077 if (bp != null && bp.perm == p) { 8078 bp.perm = null; 8079 if (DEBUG_REMOVE && chatty) { 8080 if (r == null) { 8081 r = new StringBuilder(256); 8082 } else { 8083 r.append(' '); 8084 } 8085 r.append(p.info.name); 8086 } 8087 } 8088 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8089 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8090 if (appOpPerms != null) { 8091 appOpPerms.remove(pkg.packageName); 8092 } 8093 } 8094 } 8095 if (r != null) { 8096 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8097 } 8098 8099 N = pkg.requestedPermissions.size(); 8100 r = null; 8101 for (i=0; i<N; i++) { 8102 String perm = pkg.requestedPermissions.get(i); 8103 BasePermission bp = mSettings.mPermissions.get(perm); 8104 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8105 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8106 if (appOpPerms != null) { 8107 appOpPerms.remove(pkg.packageName); 8108 if (appOpPerms.isEmpty()) { 8109 mAppOpPermissionPackages.remove(perm); 8110 } 8111 } 8112 } 8113 } 8114 if (r != null) { 8115 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8116 } 8117 8118 N = pkg.instrumentation.size(); 8119 r = null; 8120 for (i=0; i<N; i++) { 8121 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8122 mInstrumentation.remove(a.getComponentName()); 8123 if (DEBUG_REMOVE && chatty) { 8124 if (r == null) { 8125 r = new StringBuilder(256); 8126 } else { 8127 r.append(' '); 8128 } 8129 r.append(a.info.name); 8130 } 8131 } 8132 if (r != null) { 8133 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8134 } 8135 8136 r = null; 8137 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8138 // Only system apps can hold shared libraries. 8139 if (pkg.libraryNames != null) { 8140 for (i=0; i<pkg.libraryNames.size(); i++) { 8141 String name = pkg.libraryNames.get(i); 8142 SharedLibraryEntry cur = mSharedLibraries.get(name); 8143 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8144 mSharedLibraries.remove(name); 8145 if (DEBUG_REMOVE && chatty) { 8146 if (r == null) { 8147 r = new StringBuilder(256); 8148 } else { 8149 r.append(' '); 8150 } 8151 r.append(name); 8152 } 8153 } 8154 } 8155 } 8156 } 8157 if (r != null) { 8158 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8159 } 8160 } 8161 8162 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8163 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8164 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8165 return true; 8166 } 8167 } 8168 return false; 8169 } 8170 8171 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8172 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8173 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8174 8175 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8176 int flags) { 8177 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8178 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8179 } 8180 8181 private void updatePermissionsLPw(String changingPkg, 8182 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8183 // Make sure there are no dangling permission trees. 8184 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8185 while (it.hasNext()) { 8186 final BasePermission bp = it.next(); 8187 if (bp.packageSetting == null) { 8188 // We may not yet have parsed the package, so just see if 8189 // we still know about its settings. 8190 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8191 } 8192 if (bp.packageSetting == null) { 8193 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8194 + " from package " + bp.sourcePackage); 8195 it.remove(); 8196 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8197 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8198 Slog.i(TAG, "Removing old permission tree: " + bp.name 8199 + " from package " + bp.sourcePackage); 8200 flags |= UPDATE_PERMISSIONS_ALL; 8201 it.remove(); 8202 } 8203 } 8204 } 8205 8206 // Make sure all dynamic permissions have been assigned to a package, 8207 // and make sure there are no dangling permissions. 8208 it = mSettings.mPermissions.values().iterator(); 8209 while (it.hasNext()) { 8210 final BasePermission bp = it.next(); 8211 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8212 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8213 + bp.name + " pkg=" + bp.sourcePackage 8214 + " info=" + bp.pendingInfo); 8215 if (bp.packageSetting == null && bp.pendingInfo != null) { 8216 final BasePermission tree = findPermissionTreeLP(bp.name); 8217 if (tree != null && tree.perm != null) { 8218 bp.packageSetting = tree.packageSetting; 8219 bp.perm = new PackageParser.Permission(tree.perm.owner, 8220 new PermissionInfo(bp.pendingInfo)); 8221 bp.perm.info.packageName = tree.perm.info.packageName; 8222 bp.perm.info.name = bp.name; 8223 bp.uid = tree.uid; 8224 } 8225 } 8226 } 8227 if (bp.packageSetting == null) { 8228 // We may not yet have parsed the package, so just see if 8229 // we still know about its settings. 8230 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8231 } 8232 if (bp.packageSetting == null) { 8233 Slog.w(TAG, "Removing dangling permission: " + bp.name 8234 + " from package " + bp.sourcePackage); 8235 it.remove(); 8236 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8237 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8238 Slog.i(TAG, "Removing old permission: " + bp.name 8239 + " from package " + bp.sourcePackage); 8240 flags |= UPDATE_PERMISSIONS_ALL; 8241 it.remove(); 8242 } 8243 } 8244 } 8245 8246 // Now update the permissions for all packages, in particular 8247 // replace the granted permissions of the system packages. 8248 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8249 for (PackageParser.Package pkg : mPackages.values()) { 8250 if (pkg != pkgInfo) { 8251 // Only replace for packages on requested volume 8252 final String volumeUuid = getVolumeUuidForPackage(pkg); 8253 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8254 && Objects.equals(replaceVolumeUuid, volumeUuid); 8255 grantPermissionsLPw(pkg, replace, changingPkg); 8256 } 8257 } 8258 } 8259 8260 if (pkgInfo != null) { 8261 // Only replace for packages on requested volume 8262 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8263 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8264 && Objects.equals(replaceVolumeUuid, volumeUuid); 8265 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8266 } 8267 } 8268 8269 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8270 String packageOfInterest) { 8271 // IMPORTANT: There are two types of permissions: install and runtime. 8272 // Install time permissions are granted when the app is installed to 8273 // all device users and users added in the future. Runtime permissions 8274 // are granted at runtime explicitly to specific users. Normal and signature 8275 // protected permissions are install time permissions. Dangerous permissions 8276 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8277 // otherwise they are runtime permissions. This function does not manage 8278 // runtime permissions except for the case an app targeting Lollipop MR1 8279 // being upgraded to target a newer SDK, in which case dangerous permissions 8280 // are transformed from install time to runtime ones. 8281 8282 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8283 if (ps == null) { 8284 return; 8285 } 8286 8287 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8288 8289 PermissionsState permissionsState = ps.getPermissionsState(); 8290 PermissionsState origPermissions = permissionsState; 8291 8292 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8293 8294 boolean runtimePermissionsRevoked = false; 8295 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8296 8297 boolean changedInstallPermission = false; 8298 8299 if (replace) { 8300 ps.installPermissionsFixed = false; 8301 if (!ps.isSharedUser()) { 8302 origPermissions = new PermissionsState(permissionsState); 8303 permissionsState.reset(); 8304 } else { 8305 // We need to know only about runtime permission changes since the 8306 // calling code always writes the install permissions state but 8307 // the runtime ones are written only if changed. The only cases of 8308 // changed runtime permissions here are promotion of an install to 8309 // runtime and revocation of a runtime from a shared user. 8310 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8311 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8312 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8313 runtimePermissionsRevoked = true; 8314 } 8315 } 8316 } 8317 8318 permissionsState.setGlobalGids(mGlobalGids); 8319 8320 final int N = pkg.requestedPermissions.size(); 8321 for (int i=0; i<N; i++) { 8322 final String name = pkg.requestedPermissions.get(i); 8323 final BasePermission bp = mSettings.mPermissions.get(name); 8324 8325 if (DEBUG_INSTALL) { 8326 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8327 } 8328 8329 if (bp == null || bp.packageSetting == null) { 8330 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8331 Slog.w(TAG, "Unknown permission " + name 8332 + " in package " + pkg.packageName); 8333 } 8334 continue; 8335 } 8336 8337 final String perm = bp.name; 8338 boolean allowedSig = false; 8339 int grant = GRANT_DENIED; 8340 8341 // Keep track of app op permissions. 8342 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8343 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8344 if (pkgs == null) { 8345 pkgs = new ArraySet<>(); 8346 mAppOpPermissionPackages.put(bp.name, pkgs); 8347 } 8348 pkgs.add(pkg.packageName); 8349 } 8350 8351 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8352 switch (level) { 8353 case PermissionInfo.PROTECTION_NORMAL: { 8354 // For all apps normal permissions are install time ones. 8355 grant = GRANT_INSTALL; 8356 } break; 8357 8358 case PermissionInfo.PROTECTION_DANGEROUS: { 8359 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8360 // For legacy apps dangerous permissions are install time ones. 8361 grant = GRANT_INSTALL_LEGACY; 8362 } else if (origPermissions.hasInstallPermission(bp.name)) { 8363 // For legacy apps that became modern, install becomes runtime. 8364 grant = GRANT_UPGRADE; 8365 } else if (mPromoteSystemApps 8366 && isSystemApp(ps) 8367 && mExistingSystemPackages.contains(ps.name)) { 8368 // For legacy system apps, install becomes runtime. 8369 // We cannot check hasInstallPermission() for system apps since those 8370 // permissions were granted implicitly and not persisted pre-M. 8371 grant = GRANT_UPGRADE; 8372 } else { 8373 // For modern apps keep runtime permissions unchanged. 8374 grant = GRANT_RUNTIME; 8375 } 8376 } break; 8377 8378 case PermissionInfo.PROTECTION_SIGNATURE: { 8379 // For all apps signature permissions are install time ones. 8380 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8381 if (allowedSig) { 8382 grant = GRANT_INSTALL; 8383 } 8384 } break; 8385 } 8386 8387 if (DEBUG_INSTALL) { 8388 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8389 } 8390 8391 if (grant != GRANT_DENIED) { 8392 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8393 // If this is an existing, non-system package, then 8394 // we can't add any new permissions to it. 8395 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8396 // Except... if this is a permission that was added 8397 // to the platform (note: need to only do this when 8398 // updating the platform). 8399 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8400 grant = GRANT_DENIED; 8401 } 8402 } 8403 } 8404 8405 switch (grant) { 8406 case GRANT_INSTALL: { 8407 // Revoke this as runtime permission to handle the case of 8408 // a runtime permission being downgraded to an install one. 8409 for (int userId : UserManagerService.getInstance().getUserIds()) { 8410 if (origPermissions.getRuntimePermissionState( 8411 bp.name, userId) != null) { 8412 // Revoke the runtime permission and clear the flags. 8413 origPermissions.revokeRuntimePermission(bp, userId); 8414 origPermissions.updatePermissionFlags(bp, userId, 8415 PackageManager.MASK_PERMISSION_FLAGS, 0); 8416 // If we revoked a permission permission, we have to write. 8417 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8418 changedRuntimePermissionUserIds, userId); 8419 } 8420 } 8421 // Grant an install permission. 8422 if (permissionsState.grantInstallPermission(bp) != 8423 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8424 changedInstallPermission = true; 8425 } 8426 } break; 8427 8428 case GRANT_INSTALL_LEGACY: { 8429 // Grant an install permission. 8430 if (permissionsState.grantInstallPermission(bp) != 8431 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8432 changedInstallPermission = true; 8433 } 8434 } break; 8435 8436 case GRANT_RUNTIME: { 8437 // Grant previously granted runtime permissions. 8438 for (int userId : UserManagerService.getInstance().getUserIds()) { 8439 PermissionState permissionState = origPermissions 8440 .getRuntimePermissionState(bp.name, userId); 8441 final int flags = permissionState != null 8442 ? permissionState.getFlags() : 0; 8443 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8444 if (permissionsState.grantRuntimePermission(bp, userId) == 8445 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8446 // If we cannot put the permission as it was, we have to write. 8447 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8448 changedRuntimePermissionUserIds, userId); 8449 } 8450 } 8451 // Propagate the permission flags. 8452 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8453 } 8454 } break; 8455 8456 case GRANT_UPGRADE: { 8457 // Grant runtime permissions for a previously held install permission. 8458 PermissionState permissionState = origPermissions 8459 .getInstallPermissionState(bp.name); 8460 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8461 8462 if (origPermissions.revokeInstallPermission(bp) 8463 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8464 // We will be transferring the permission flags, so clear them. 8465 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8466 PackageManager.MASK_PERMISSION_FLAGS, 0); 8467 changedInstallPermission = true; 8468 } 8469 8470 // If the permission is not to be promoted to runtime we ignore it and 8471 // also its other flags as they are not applicable to install permissions. 8472 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8473 for (int userId : currentUserIds) { 8474 if (permissionsState.grantRuntimePermission(bp, userId) != 8475 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8476 // Transfer the permission flags. 8477 permissionsState.updatePermissionFlags(bp, userId, 8478 flags, flags); 8479 // If we granted the permission, we have to write. 8480 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8481 changedRuntimePermissionUserIds, userId); 8482 } 8483 } 8484 } 8485 } break; 8486 8487 default: { 8488 if (packageOfInterest == null 8489 || packageOfInterest.equals(pkg.packageName)) { 8490 Slog.w(TAG, "Not granting permission " + perm 8491 + " to package " + pkg.packageName 8492 + " because it was previously installed without"); 8493 } 8494 } break; 8495 } 8496 } else { 8497 if (permissionsState.revokeInstallPermission(bp) != 8498 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8499 // Also drop the permission flags. 8500 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8501 PackageManager.MASK_PERMISSION_FLAGS, 0); 8502 changedInstallPermission = true; 8503 Slog.i(TAG, "Un-granting permission " + perm 8504 + " from package " + pkg.packageName 8505 + " (protectionLevel=" + bp.protectionLevel 8506 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8507 + ")"); 8508 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8509 // Don't print warning for app op permissions, since it is fine for them 8510 // not to be granted, there is a UI for the user to decide. 8511 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8512 Slog.w(TAG, "Not granting permission " + perm 8513 + " to package " + pkg.packageName 8514 + " (protectionLevel=" + bp.protectionLevel 8515 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8516 + ")"); 8517 } 8518 } 8519 } 8520 } 8521 8522 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8523 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8524 // This is the first that we have heard about this package, so the 8525 // permissions we have now selected are fixed until explicitly 8526 // changed. 8527 ps.installPermissionsFixed = true; 8528 } 8529 8530 // Persist the runtime permissions state for users with changes. If permissions 8531 // were revoked because no app in the shared user declares them we have to 8532 // write synchronously to avoid losing runtime permissions state. 8533 for (int userId : changedRuntimePermissionUserIds) { 8534 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8535 } 8536 8537 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8538 } 8539 8540 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8541 boolean allowed = false; 8542 final int NP = PackageParser.NEW_PERMISSIONS.length; 8543 for (int ip=0; ip<NP; ip++) { 8544 final PackageParser.NewPermissionInfo npi 8545 = PackageParser.NEW_PERMISSIONS[ip]; 8546 if (npi.name.equals(perm) 8547 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8548 allowed = true; 8549 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8550 + pkg.packageName); 8551 break; 8552 } 8553 } 8554 return allowed; 8555 } 8556 8557 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8558 BasePermission bp, PermissionsState origPermissions) { 8559 boolean allowed; 8560 allowed = (compareSignatures( 8561 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8562 == PackageManager.SIGNATURE_MATCH) 8563 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8564 == PackageManager.SIGNATURE_MATCH); 8565 if (!allowed && (bp.protectionLevel 8566 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8567 if (isSystemApp(pkg)) { 8568 // For updated system applications, a system permission 8569 // is granted only if it had been defined by the original application. 8570 if (pkg.isUpdatedSystemApp()) { 8571 final PackageSetting sysPs = mSettings 8572 .getDisabledSystemPkgLPr(pkg.packageName); 8573 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8574 // If the original was granted this permission, we take 8575 // that grant decision as read and propagate it to the 8576 // update. 8577 if (sysPs.isPrivileged()) { 8578 allowed = true; 8579 } 8580 } else { 8581 // The system apk may have been updated with an older 8582 // version of the one on the data partition, but which 8583 // granted a new system permission that it didn't have 8584 // before. In this case we do want to allow the app to 8585 // now get the new permission if the ancestral apk is 8586 // privileged to get it. 8587 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8588 for (int j=0; 8589 j<sysPs.pkg.requestedPermissions.size(); j++) { 8590 if (perm.equals( 8591 sysPs.pkg.requestedPermissions.get(j))) { 8592 allowed = true; 8593 break; 8594 } 8595 } 8596 } 8597 } 8598 } else { 8599 allowed = isPrivilegedApp(pkg); 8600 } 8601 } 8602 } 8603 if (!allowed) { 8604 if (!allowed && (bp.protectionLevel 8605 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8606 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8607 // If this was a previously normal/dangerous permission that got moved 8608 // to a system permission as part of the runtime permission redesign, then 8609 // we still want to blindly grant it to old apps. 8610 allowed = true; 8611 } 8612 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8613 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8614 // If this permission is to be granted to the system installer and 8615 // this app is an installer, then it gets the permission. 8616 allowed = true; 8617 } 8618 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8619 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8620 // If this permission is to be granted to the system verifier and 8621 // this app is a verifier, then it gets the permission. 8622 allowed = true; 8623 } 8624 if (!allowed && (bp.protectionLevel 8625 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8626 && isSystemApp(pkg)) { 8627 // Any pre-installed system app is allowed to get this permission. 8628 allowed = true; 8629 } 8630 if (!allowed && (bp.protectionLevel 8631 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8632 // For development permissions, a development permission 8633 // is granted only if it was already granted. 8634 allowed = origPermissions.hasInstallPermission(perm); 8635 } 8636 } 8637 return allowed; 8638 } 8639 8640 final class ActivityIntentResolver 8641 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8642 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8643 boolean defaultOnly, int userId) { 8644 if (!sUserManager.exists(userId)) return null; 8645 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8646 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8647 } 8648 8649 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8650 int userId) { 8651 if (!sUserManager.exists(userId)) return null; 8652 mFlags = flags; 8653 return super.queryIntent(intent, resolvedType, 8654 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8655 } 8656 8657 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8658 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8659 if (!sUserManager.exists(userId)) return null; 8660 if (packageActivities == null) { 8661 return null; 8662 } 8663 mFlags = flags; 8664 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8665 final int N = packageActivities.size(); 8666 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8667 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8668 8669 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8670 for (int i = 0; i < N; ++i) { 8671 intentFilters = packageActivities.get(i).intents; 8672 if (intentFilters != null && intentFilters.size() > 0) { 8673 PackageParser.ActivityIntentInfo[] array = 8674 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8675 intentFilters.toArray(array); 8676 listCut.add(array); 8677 } 8678 } 8679 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8680 } 8681 8682 public final void addActivity(PackageParser.Activity a, String type) { 8683 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8684 mActivities.put(a.getComponentName(), a); 8685 if (DEBUG_SHOW_INFO) 8686 Log.v( 8687 TAG, " " + type + " " + 8688 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8689 if (DEBUG_SHOW_INFO) 8690 Log.v(TAG, " Class=" + a.info.name); 8691 final int NI = a.intents.size(); 8692 for (int j=0; j<NI; j++) { 8693 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8694 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8695 intent.setPriority(0); 8696 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8697 + a.className + " with priority > 0, forcing to 0"); 8698 } 8699 if (DEBUG_SHOW_INFO) { 8700 Log.v(TAG, " IntentFilter:"); 8701 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8702 } 8703 if (!intent.debugCheck()) { 8704 Log.w(TAG, "==> For Activity " + a.info.name); 8705 } 8706 addFilter(intent); 8707 } 8708 } 8709 8710 public final void removeActivity(PackageParser.Activity a, String type) { 8711 mActivities.remove(a.getComponentName()); 8712 if (DEBUG_SHOW_INFO) { 8713 Log.v(TAG, " " + type + " " 8714 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8715 : a.info.name) + ":"); 8716 Log.v(TAG, " Class=" + a.info.name); 8717 } 8718 final int NI = a.intents.size(); 8719 for (int j=0; j<NI; j++) { 8720 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8721 if (DEBUG_SHOW_INFO) { 8722 Log.v(TAG, " IntentFilter:"); 8723 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8724 } 8725 removeFilter(intent); 8726 } 8727 } 8728 8729 @Override 8730 protected boolean allowFilterResult( 8731 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8732 ActivityInfo filterAi = filter.activity.info; 8733 for (int i=dest.size()-1; i>=0; i--) { 8734 ActivityInfo destAi = dest.get(i).activityInfo; 8735 if (destAi.name == filterAi.name 8736 && destAi.packageName == filterAi.packageName) { 8737 return false; 8738 } 8739 } 8740 return true; 8741 } 8742 8743 @Override 8744 protected ActivityIntentInfo[] newArray(int size) { 8745 return new ActivityIntentInfo[size]; 8746 } 8747 8748 @Override 8749 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8750 if (!sUserManager.exists(userId)) return true; 8751 PackageParser.Package p = filter.activity.owner; 8752 if (p != null) { 8753 PackageSetting ps = (PackageSetting)p.mExtras; 8754 if (ps != null) { 8755 // System apps are never considered stopped for purposes of 8756 // filtering, because there may be no way for the user to 8757 // actually re-launch them. 8758 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8759 && ps.getStopped(userId); 8760 } 8761 } 8762 return false; 8763 } 8764 8765 @Override 8766 protected boolean isPackageForFilter(String packageName, 8767 PackageParser.ActivityIntentInfo info) { 8768 return packageName.equals(info.activity.owner.packageName); 8769 } 8770 8771 @Override 8772 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8773 int match, int userId) { 8774 if (!sUserManager.exists(userId)) return null; 8775 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 8776 return null; 8777 } 8778 final PackageParser.Activity activity = info.activity; 8779 if (mSafeMode && (activity.info.applicationInfo.flags 8780 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8781 return null; 8782 } 8783 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8784 if (ps == null) { 8785 return null; 8786 } 8787 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8788 ps.readUserState(userId), userId); 8789 if (ai == null) { 8790 return null; 8791 } 8792 final ResolveInfo res = new ResolveInfo(); 8793 res.activityInfo = ai; 8794 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8795 res.filter = info; 8796 } 8797 if (info != null) { 8798 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8799 } 8800 res.priority = info.getPriority(); 8801 res.preferredOrder = activity.owner.mPreferredOrder; 8802 //System.out.println("Result: " + res.activityInfo.className + 8803 // " = " + res.priority); 8804 res.match = match; 8805 res.isDefault = info.hasDefault; 8806 res.labelRes = info.labelRes; 8807 res.nonLocalizedLabel = info.nonLocalizedLabel; 8808 if (userNeedsBadging(userId)) { 8809 res.noResourceId = true; 8810 } else { 8811 res.icon = info.icon; 8812 } 8813 res.iconResourceId = info.icon; 8814 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8815 return res; 8816 } 8817 8818 @Override 8819 protected void sortResults(List<ResolveInfo> results) { 8820 Collections.sort(results, mResolvePrioritySorter); 8821 } 8822 8823 @Override 8824 protected void dumpFilter(PrintWriter out, String prefix, 8825 PackageParser.ActivityIntentInfo filter) { 8826 out.print(prefix); out.print( 8827 Integer.toHexString(System.identityHashCode(filter.activity))); 8828 out.print(' '); 8829 filter.activity.printComponentShortName(out); 8830 out.print(" filter "); 8831 out.println(Integer.toHexString(System.identityHashCode(filter))); 8832 } 8833 8834 @Override 8835 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8836 return filter.activity; 8837 } 8838 8839 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8840 PackageParser.Activity activity = (PackageParser.Activity)label; 8841 out.print(prefix); out.print( 8842 Integer.toHexString(System.identityHashCode(activity))); 8843 out.print(' '); 8844 activity.printComponentShortName(out); 8845 if (count > 1) { 8846 out.print(" ("); out.print(count); out.print(" filters)"); 8847 } 8848 out.println(); 8849 } 8850 8851// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8852// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8853// final List<ResolveInfo> retList = Lists.newArrayList(); 8854// while (i.hasNext()) { 8855// final ResolveInfo resolveInfo = i.next(); 8856// if (isEnabledLP(resolveInfo.activityInfo)) { 8857// retList.add(resolveInfo); 8858// } 8859// } 8860// return retList; 8861// } 8862 8863 // Keys are String (activity class name), values are Activity. 8864 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8865 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8866 private int mFlags; 8867 } 8868 8869 private final class ServiceIntentResolver 8870 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8871 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8872 boolean defaultOnly, int userId) { 8873 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8874 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8875 } 8876 8877 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8878 int userId) { 8879 if (!sUserManager.exists(userId)) return null; 8880 mFlags = flags; 8881 return super.queryIntent(intent, resolvedType, 8882 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8883 } 8884 8885 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8886 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8887 if (!sUserManager.exists(userId)) return null; 8888 if (packageServices == null) { 8889 return null; 8890 } 8891 mFlags = flags; 8892 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8893 final int N = packageServices.size(); 8894 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8895 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8896 8897 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8898 for (int i = 0; i < N; ++i) { 8899 intentFilters = packageServices.get(i).intents; 8900 if (intentFilters != null && intentFilters.size() > 0) { 8901 PackageParser.ServiceIntentInfo[] array = 8902 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8903 intentFilters.toArray(array); 8904 listCut.add(array); 8905 } 8906 } 8907 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8908 } 8909 8910 public final void addService(PackageParser.Service s) { 8911 mServices.put(s.getComponentName(), s); 8912 if (DEBUG_SHOW_INFO) { 8913 Log.v(TAG, " " 8914 + (s.info.nonLocalizedLabel != null 8915 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8916 Log.v(TAG, " Class=" + s.info.name); 8917 } 8918 final int NI = s.intents.size(); 8919 int j; 8920 for (j=0; j<NI; j++) { 8921 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8922 if (DEBUG_SHOW_INFO) { 8923 Log.v(TAG, " IntentFilter:"); 8924 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8925 } 8926 if (!intent.debugCheck()) { 8927 Log.w(TAG, "==> For Service " + s.info.name); 8928 } 8929 addFilter(intent); 8930 } 8931 } 8932 8933 public final void removeService(PackageParser.Service s) { 8934 mServices.remove(s.getComponentName()); 8935 if (DEBUG_SHOW_INFO) { 8936 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8937 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8938 Log.v(TAG, " Class=" + s.info.name); 8939 } 8940 final int NI = s.intents.size(); 8941 int j; 8942 for (j=0; j<NI; j++) { 8943 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8944 if (DEBUG_SHOW_INFO) { 8945 Log.v(TAG, " IntentFilter:"); 8946 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8947 } 8948 removeFilter(intent); 8949 } 8950 } 8951 8952 @Override 8953 protected boolean allowFilterResult( 8954 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8955 ServiceInfo filterSi = filter.service.info; 8956 for (int i=dest.size()-1; i>=0; i--) { 8957 ServiceInfo destAi = dest.get(i).serviceInfo; 8958 if (destAi.name == filterSi.name 8959 && destAi.packageName == filterSi.packageName) { 8960 return false; 8961 } 8962 } 8963 return true; 8964 } 8965 8966 @Override 8967 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8968 return new PackageParser.ServiceIntentInfo[size]; 8969 } 8970 8971 @Override 8972 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8973 if (!sUserManager.exists(userId)) return true; 8974 PackageParser.Package p = filter.service.owner; 8975 if (p != null) { 8976 PackageSetting ps = (PackageSetting)p.mExtras; 8977 if (ps != null) { 8978 // System apps are never considered stopped for purposes of 8979 // filtering, because there may be no way for the user to 8980 // actually re-launch them. 8981 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8982 && ps.getStopped(userId); 8983 } 8984 } 8985 return false; 8986 } 8987 8988 @Override 8989 protected boolean isPackageForFilter(String packageName, 8990 PackageParser.ServiceIntentInfo info) { 8991 return packageName.equals(info.service.owner.packageName); 8992 } 8993 8994 @Override 8995 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8996 int match, int userId) { 8997 if (!sUserManager.exists(userId)) return null; 8998 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8999 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9000 return null; 9001 } 9002 final PackageParser.Service service = info.service; 9003 if (mSafeMode && (service.info.applicationInfo.flags 9004 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9005 return null; 9006 } 9007 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9008 if (ps == null) { 9009 return null; 9010 } 9011 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9012 ps.readUserState(userId), userId); 9013 if (si == null) { 9014 return null; 9015 } 9016 final ResolveInfo res = new ResolveInfo(); 9017 res.serviceInfo = si; 9018 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9019 res.filter = filter; 9020 } 9021 res.priority = info.getPriority(); 9022 res.preferredOrder = service.owner.mPreferredOrder; 9023 res.match = match; 9024 res.isDefault = info.hasDefault; 9025 res.labelRes = info.labelRes; 9026 res.nonLocalizedLabel = info.nonLocalizedLabel; 9027 res.icon = info.icon; 9028 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9029 return res; 9030 } 9031 9032 @Override 9033 protected void sortResults(List<ResolveInfo> results) { 9034 Collections.sort(results, mResolvePrioritySorter); 9035 } 9036 9037 @Override 9038 protected void dumpFilter(PrintWriter out, String prefix, 9039 PackageParser.ServiceIntentInfo filter) { 9040 out.print(prefix); out.print( 9041 Integer.toHexString(System.identityHashCode(filter.service))); 9042 out.print(' '); 9043 filter.service.printComponentShortName(out); 9044 out.print(" filter "); 9045 out.println(Integer.toHexString(System.identityHashCode(filter))); 9046 } 9047 9048 @Override 9049 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9050 return filter.service; 9051 } 9052 9053 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9054 PackageParser.Service service = (PackageParser.Service)label; 9055 out.print(prefix); out.print( 9056 Integer.toHexString(System.identityHashCode(service))); 9057 out.print(' '); 9058 service.printComponentShortName(out); 9059 if (count > 1) { 9060 out.print(" ("); out.print(count); out.print(" filters)"); 9061 } 9062 out.println(); 9063 } 9064 9065// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9066// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9067// final List<ResolveInfo> retList = Lists.newArrayList(); 9068// while (i.hasNext()) { 9069// final ResolveInfo resolveInfo = (ResolveInfo) i; 9070// if (isEnabledLP(resolveInfo.serviceInfo)) { 9071// retList.add(resolveInfo); 9072// } 9073// } 9074// return retList; 9075// } 9076 9077 // Keys are String (activity class name), values are Activity. 9078 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9079 = new ArrayMap<ComponentName, PackageParser.Service>(); 9080 private int mFlags; 9081 }; 9082 9083 private final class ProviderIntentResolver 9084 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9085 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9086 boolean defaultOnly, int userId) { 9087 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9088 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9089 } 9090 9091 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9092 int userId) { 9093 if (!sUserManager.exists(userId)) 9094 return null; 9095 mFlags = flags; 9096 return super.queryIntent(intent, resolvedType, 9097 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9098 } 9099 9100 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9101 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9102 if (!sUserManager.exists(userId)) 9103 return null; 9104 if (packageProviders == null) { 9105 return null; 9106 } 9107 mFlags = flags; 9108 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9109 final int N = packageProviders.size(); 9110 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9111 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9112 9113 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9114 for (int i = 0; i < N; ++i) { 9115 intentFilters = packageProviders.get(i).intents; 9116 if (intentFilters != null && intentFilters.size() > 0) { 9117 PackageParser.ProviderIntentInfo[] array = 9118 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9119 intentFilters.toArray(array); 9120 listCut.add(array); 9121 } 9122 } 9123 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9124 } 9125 9126 public final void addProvider(PackageParser.Provider p) { 9127 if (mProviders.containsKey(p.getComponentName())) { 9128 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9129 return; 9130 } 9131 9132 mProviders.put(p.getComponentName(), p); 9133 if (DEBUG_SHOW_INFO) { 9134 Log.v(TAG, " " 9135 + (p.info.nonLocalizedLabel != null 9136 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9137 Log.v(TAG, " Class=" + p.info.name); 9138 } 9139 final int NI = p.intents.size(); 9140 int j; 9141 for (j = 0; j < NI; j++) { 9142 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9143 if (DEBUG_SHOW_INFO) { 9144 Log.v(TAG, " IntentFilter:"); 9145 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9146 } 9147 if (!intent.debugCheck()) { 9148 Log.w(TAG, "==> For Provider " + p.info.name); 9149 } 9150 addFilter(intent); 9151 } 9152 } 9153 9154 public final void removeProvider(PackageParser.Provider p) { 9155 mProviders.remove(p.getComponentName()); 9156 if (DEBUG_SHOW_INFO) { 9157 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9158 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9159 Log.v(TAG, " Class=" + p.info.name); 9160 } 9161 final int NI = p.intents.size(); 9162 int j; 9163 for (j = 0; j < NI; j++) { 9164 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9165 if (DEBUG_SHOW_INFO) { 9166 Log.v(TAG, " IntentFilter:"); 9167 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9168 } 9169 removeFilter(intent); 9170 } 9171 } 9172 9173 @Override 9174 protected boolean allowFilterResult( 9175 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9176 ProviderInfo filterPi = filter.provider.info; 9177 for (int i = dest.size() - 1; i >= 0; i--) { 9178 ProviderInfo destPi = dest.get(i).providerInfo; 9179 if (destPi.name == filterPi.name 9180 && destPi.packageName == filterPi.packageName) { 9181 return false; 9182 } 9183 } 9184 return true; 9185 } 9186 9187 @Override 9188 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9189 return new PackageParser.ProviderIntentInfo[size]; 9190 } 9191 9192 @Override 9193 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9194 if (!sUserManager.exists(userId)) 9195 return true; 9196 PackageParser.Package p = filter.provider.owner; 9197 if (p != null) { 9198 PackageSetting ps = (PackageSetting) p.mExtras; 9199 if (ps != null) { 9200 // System apps are never considered stopped for purposes of 9201 // filtering, because there may be no way for the user to 9202 // actually re-launch them. 9203 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9204 && ps.getStopped(userId); 9205 } 9206 } 9207 return false; 9208 } 9209 9210 @Override 9211 protected boolean isPackageForFilter(String packageName, 9212 PackageParser.ProviderIntentInfo info) { 9213 return packageName.equals(info.provider.owner.packageName); 9214 } 9215 9216 @Override 9217 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9218 int match, int userId) { 9219 if (!sUserManager.exists(userId)) 9220 return null; 9221 final PackageParser.ProviderIntentInfo info = filter; 9222 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9223 return null; 9224 } 9225 final PackageParser.Provider provider = info.provider; 9226 if (mSafeMode && (provider.info.applicationInfo.flags 9227 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9228 return null; 9229 } 9230 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9231 if (ps == null) { 9232 return null; 9233 } 9234 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9235 ps.readUserState(userId), userId); 9236 if (pi == null) { 9237 return null; 9238 } 9239 final ResolveInfo res = new ResolveInfo(); 9240 res.providerInfo = pi; 9241 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9242 res.filter = filter; 9243 } 9244 res.priority = info.getPriority(); 9245 res.preferredOrder = provider.owner.mPreferredOrder; 9246 res.match = match; 9247 res.isDefault = info.hasDefault; 9248 res.labelRes = info.labelRes; 9249 res.nonLocalizedLabel = info.nonLocalizedLabel; 9250 res.icon = info.icon; 9251 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9252 return res; 9253 } 9254 9255 @Override 9256 protected void sortResults(List<ResolveInfo> results) { 9257 Collections.sort(results, mResolvePrioritySorter); 9258 } 9259 9260 @Override 9261 protected void dumpFilter(PrintWriter out, String prefix, 9262 PackageParser.ProviderIntentInfo filter) { 9263 out.print(prefix); 9264 out.print( 9265 Integer.toHexString(System.identityHashCode(filter.provider))); 9266 out.print(' '); 9267 filter.provider.printComponentShortName(out); 9268 out.print(" filter "); 9269 out.println(Integer.toHexString(System.identityHashCode(filter))); 9270 } 9271 9272 @Override 9273 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9274 return filter.provider; 9275 } 9276 9277 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9278 PackageParser.Provider provider = (PackageParser.Provider)label; 9279 out.print(prefix); out.print( 9280 Integer.toHexString(System.identityHashCode(provider))); 9281 out.print(' '); 9282 provider.printComponentShortName(out); 9283 if (count > 1) { 9284 out.print(" ("); out.print(count); out.print(" filters)"); 9285 } 9286 out.println(); 9287 } 9288 9289 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9290 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9291 private int mFlags; 9292 }; 9293 9294 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9295 new Comparator<ResolveInfo>() { 9296 public int compare(ResolveInfo r1, ResolveInfo r2) { 9297 int v1 = r1.priority; 9298 int v2 = r2.priority; 9299 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9300 if (v1 != v2) { 9301 return (v1 > v2) ? -1 : 1; 9302 } 9303 v1 = r1.preferredOrder; 9304 v2 = r2.preferredOrder; 9305 if (v1 != v2) { 9306 return (v1 > v2) ? -1 : 1; 9307 } 9308 if (r1.isDefault != r2.isDefault) { 9309 return r1.isDefault ? -1 : 1; 9310 } 9311 v1 = r1.match; 9312 v2 = r2.match; 9313 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9314 if (v1 != v2) { 9315 return (v1 > v2) ? -1 : 1; 9316 } 9317 if (r1.system != r2.system) { 9318 return r1.system ? -1 : 1; 9319 } 9320 return 0; 9321 } 9322 }; 9323 9324 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9325 new Comparator<ProviderInfo>() { 9326 public int compare(ProviderInfo p1, ProviderInfo p2) { 9327 final int v1 = p1.initOrder; 9328 final int v2 = p2.initOrder; 9329 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9330 } 9331 }; 9332 9333 final void sendPackageBroadcast(final String action, final String pkg, 9334 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9335 final int[] userIds) { 9336 mHandler.post(new Runnable() { 9337 @Override 9338 public void run() { 9339 try { 9340 final IActivityManager am = ActivityManagerNative.getDefault(); 9341 if (am == null) return; 9342 final int[] resolvedUserIds; 9343 if (userIds == null) { 9344 resolvedUserIds = am.getRunningUserIds(); 9345 } else { 9346 resolvedUserIds = userIds; 9347 } 9348 for (int id : resolvedUserIds) { 9349 final Intent intent = new Intent(action, 9350 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9351 if (extras != null) { 9352 intent.putExtras(extras); 9353 } 9354 if (targetPkg != null) { 9355 intent.setPackage(targetPkg); 9356 } 9357 // Modify the UID when posting to other users 9358 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9359 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9360 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9361 intent.putExtra(Intent.EXTRA_UID, uid); 9362 } 9363 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9364 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9365 if (DEBUG_BROADCASTS) { 9366 RuntimeException here = new RuntimeException("here"); 9367 here.fillInStackTrace(); 9368 Slog.d(TAG, "Sending to user " + id + ": " 9369 + intent.toShortString(false, true, false, false) 9370 + " " + intent.getExtras(), here); 9371 } 9372 am.broadcastIntent(null, intent, null, finishedReceiver, 9373 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9374 null, finishedReceiver != null, false, id); 9375 } 9376 } catch (RemoteException ex) { 9377 } 9378 } 9379 }); 9380 } 9381 9382 /** 9383 * Check if the external storage media is available. This is true if there 9384 * is a mounted external storage medium or if the external storage is 9385 * emulated. 9386 */ 9387 private boolean isExternalMediaAvailable() { 9388 return mMediaMounted || Environment.isExternalStorageEmulated(); 9389 } 9390 9391 @Override 9392 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9393 // writer 9394 synchronized (mPackages) { 9395 if (!isExternalMediaAvailable()) { 9396 // If the external storage is no longer mounted at this point, 9397 // the caller may not have been able to delete all of this 9398 // packages files and can not delete any more. Bail. 9399 return null; 9400 } 9401 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9402 if (lastPackage != null) { 9403 pkgs.remove(lastPackage); 9404 } 9405 if (pkgs.size() > 0) { 9406 return pkgs.get(0); 9407 } 9408 } 9409 return null; 9410 } 9411 9412 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9413 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9414 userId, andCode ? 1 : 0, packageName); 9415 if (mSystemReady) { 9416 msg.sendToTarget(); 9417 } else { 9418 if (mPostSystemReadyMessages == null) { 9419 mPostSystemReadyMessages = new ArrayList<>(); 9420 } 9421 mPostSystemReadyMessages.add(msg); 9422 } 9423 } 9424 9425 void startCleaningPackages() { 9426 // reader 9427 synchronized (mPackages) { 9428 if (!isExternalMediaAvailable()) { 9429 return; 9430 } 9431 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9432 return; 9433 } 9434 } 9435 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9436 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9437 IActivityManager am = ActivityManagerNative.getDefault(); 9438 if (am != null) { 9439 try { 9440 am.startService(null, intent, null, mContext.getOpPackageName(), 9441 UserHandle.USER_SYSTEM); 9442 } catch (RemoteException e) { 9443 } 9444 } 9445 } 9446 9447 @Override 9448 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9449 int installFlags, String installerPackageName, VerificationParams verificationParams, 9450 String packageAbiOverride) { 9451 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9452 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9453 } 9454 9455 @Override 9456 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9457 int installFlags, String installerPackageName, VerificationParams verificationParams, 9458 String packageAbiOverride, int userId) { 9459 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9460 9461 final int callingUid = Binder.getCallingUid(); 9462 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9463 9464 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9465 try { 9466 if (observer != null) { 9467 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9468 } 9469 } catch (RemoteException re) { 9470 } 9471 return; 9472 } 9473 9474 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9475 installFlags |= PackageManager.INSTALL_FROM_ADB; 9476 9477 } else { 9478 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9479 // about installerPackageName. 9480 9481 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9482 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9483 } 9484 9485 UserHandle user; 9486 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9487 user = UserHandle.ALL; 9488 } else { 9489 user = new UserHandle(userId); 9490 } 9491 9492 // Only system components can circumvent runtime permissions when installing. 9493 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9494 && mContext.checkCallingOrSelfPermission(Manifest.permission 9495 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9496 throw new SecurityException("You need the " 9497 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9498 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9499 } 9500 9501 verificationParams.setInstallerUid(callingUid); 9502 9503 final File originFile = new File(originPath); 9504 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9505 9506 final Message msg = mHandler.obtainMessage(INIT_COPY); 9507 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9508 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9509 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9510 msg.obj = params; 9511 9512 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9513 System.identityHashCode(msg.obj)); 9514 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9515 System.identityHashCode(msg.obj)); 9516 9517 mHandler.sendMessage(msg); 9518 } 9519 9520 void installStage(String packageName, File stagedDir, String stagedCid, 9521 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9522 String installerPackageName, int installerUid, UserHandle user) { 9523 final VerificationParams verifParams = new VerificationParams( 9524 null, sessionParams.originatingUri, sessionParams.referrerUri, 9525 sessionParams.originatingUid, null); 9526 verifParams.setInstallerUid(installerUid); 9527 9528 final OriginInfo origin; 9529 if (stagedDir != null) { 9530 origin = OriginInfo.fromStagedFile(stagedDir); 9531 } else { 9532 origin = OriginInfo.fromStagedContainer(stagedCid); 9533 } 9534 9535 final Message msg = mHandler.obtainMessage(INIT_COPY); 9536 final InstallParams params = new InstallParams(origin, null, observer, 9537 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9538 verifParams, user, sessionParams.abiOverride, 9539 sessionParams.grantedRuntimePermissions); 9540 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9541 msg.obj = params; 9542 9543 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9544 System.identityHashCode(msg.obj)); 9545 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9546 System.identityHashCode(msg.obj)); 9547 9548 mHandler.sendMessage(msg); 9549 } 9550 9551 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9552 Bundle extras = new Bundle(1); 9553 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9554 9555 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9556 packageName, extras, null, null, new int[] {userId}); 9557 try { 9558 IActivityManager am = ActivityManagerNative.getDefault(); 9559 final boolean isSystem = 9560 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9561 if (isSystem && am.isUserRunning(userId, 0)) { 9562 // The just-installed/enabled app is bundled on the system, so presumed 9563 // to be able to run automatically without needing an explicit launch. 9564 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9565 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9566 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9567 .setPackage(packageName); 9568 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9569 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9570 } 9571 } catch (RemoteException e) { 9572 // shouldn't happen 9573 Slog.w(TAG, "Unable to bootstrap installed package", e); 9574 } 9575 } 9576 9577 @Override 9578 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9579 int userId) { 9580 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9581 PackageSetting pkgSetting; 9582 final int uid = Binder.getCallingUid(); 9583 enforceCrossUserPermission(uid, userId, true, true, 9584 "setApplicationHiddenSetting for user " + userId); 9585 9586 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9587 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9588 return false; 9589 } 9590 9591 long callingId = Binder.clearCallingIdentity(); 9592 try { 9593 boolean sendAdded = false; 9594 boolean sendRemoved = false; 9595 // writer 9596 synchronized (mPackages) { 9597 pkgSetting = mSettings.mPackages.get(packageName); 9598 if (pkgSetting == null) { 9599 return false; 9600 } 9601 if (pkgSetting.getHidden(userId) != hidden) { 9602 pkgSetting.setHidden(hidden, userId); 9603 mSettings.writePackageRestrictionsLPr(userId); 9604 if (hidden) { 9605 sendRemoved = true; 9606 } else { 9607 sendAdded = true; 9608 } 9609 } 9610 } 9611 if (sendAdded) { 9612 sendPackageAddedForUser(packageName, pkgSetting, userId); 9613 return true; 9614 } 9615 if (sendRemoved) { 9616 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9617 "hiding pkg"); 9618 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9619 return true; 9620 } 9621 } finally { 9622 Binder.restoreCallingIdentity(callingId); 9623 } 9624 return false; 9625 } 9626 9627 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9628 int userId) { 9629 final PackageRemovedInfo info = new PackageRemovedInfo(); 9630 info.removedPackage = packageName; 9631 info.removedUsers = new int[] {userId}; 9632 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9633 info.sendBroadcast(false, false, false); 9634 } 9635 9636 /** 9637 * Returns true if application is not found or there was an error. Otherwise it returns 9638 * the hidden state of the package for the given user. 9639 */ 9640 @Override 9641 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9642 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9643 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9644 false, "getApplicationHidden for user " + userId); 9645 PackageSetting pkgSetting; 9646 long callingId = Binder.clearCallingIdentity(); 9647 try { 9648 // writer 9649 synchronized (mPackages) { 9650 pkgSetting = mSettings.mPackages.get(packageName); 9651 if (pkgSetting == null) { 9652 return true; 9653 } 9654 return pkgSetting.getHidden(userId); 9655 } 9656 } finally { 9657 Binder.restoreCallingIdentity(callingId); 9658 } 9659 } 9660 9661 /** 9662 * @hide 9663 */ 9664 @Override 9665 public int installExistingPackageAsUser(String packageName, int userId) { 9666 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9667 null); 9668 PackageSetting pkgSetting; 9669 final int uid = Binder.getCallingUid(); 9670 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9671 + userId); 9672 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9673 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9674 } 9675 9676 long callingId = Binder.clearCallingIdentity(); 9677 try { 9678 boolean sendAdded = false; 9679 9680 // writer 9681 synchronized (mPackages) { 9682 pkgSetting = mSettings.mPackages.get(packageName); 9683 if (pkgSetting == null) { 9684 return PackageManager.INSTALL_FAILED_INVALID_URI; 9685 } 9686 if (!pkgSetting.getInstalled(userId)) { 9687 pkgSetting.setInstalled(true, userId); 9688 pkgSetting.setHidden(false, userId); 9689 mSettings.writePackageRestrictionsLPr(userId); 9690 sendAdded = true; 9691 } 9692 } 9693 9694 if (sendAdded) { 9695 sendPackageAddedForUser(packageName, pkgSetting, userId); 9696 } 9697 } finally { 9698 Binder.restoreCallingIdentity(callingId); 9699 } 9700 9701 return PackageManager.INSTALL_SUCCEEDED; 9702 } 9703 9704 boolean isUserRestricted(int userId, String restrictionKey) { 9705 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9706 if (restrictions.getBoolean(restrictionKey, false)) { 9707 Log.w(TAG, "User is restricted: " + restrictionKey); 9708 return true; 9709 } 9710 return false; 9711 } 9712 9713 @Override 9714 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9715 mContext.enforceCallingOrSelfPermission( 9716 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9717 "Only package verification agents can verify applications"); 9718 9719 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9720 final PackageVerificationResponse response = new PackageVerificationResponse( 9721 verificationCode, Binder.getCallingUid()); 9722 msg.arg1 = id; 9723 msg.obj = response; 9724 mHandler.sendMessage(msg); 9725 } 9726 9727 @Override 9728 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9729 long millisecondsToDelay) { 9730 mContext.enforceCallingOrSelfPermission( 9731 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9732 "Only package verification agents can extend verification timeouts"); 9733 9734 final PackageVerificationState state = mPendingVerification.get(id); 9735 final PackageVerificationResponse response = new PackageVerificationResponse( 9736 verificationCodeAtTimeout, Binder.getCallingUid()); 9737 9738 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9739 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9740 } 9741 if (millisecondsToDelay < 0) { 9742 millisecondsToDelay = 0; 9743 } 9744 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9745 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9746 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9747 } 9748 9749 if ((state != null) && !state.timeoutExtended()) { 9750 state.extendTimeout(); 9751 9752 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9753 msg.arg1 = id; 9754 msg.obj = response; 9755 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9756 } 9757 } 9758 9759 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9760 int verificationCode, UserHandle user) { 9761 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9762 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9763 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9764 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9765 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9766 9767 mContext.sendBroadcastAsUser(intent, user, 9768 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9769 } 9770 9771 private ComponentName matchComponentForVerifier(String packageName, 9772 List<ResolveInfo> receivers) { 9773 ActivityInfo targetReceiver = null; 9774 9775 final int NR = receivers.size(); 9776 for (int i = 0; i < NR; i++) { 9777 final ResolveInfo info = receivers.get(i); 9778 if (info.activityInfo == null) { 9779 continue; 9780 } 9781 9782 if (packageName.equals(info.activityInfo.packageName)) { 9783 targetReceiver = info.activityInfo; 9784 break; 9785 } 9786 } 9787 9788 if (targetReceiver == null) { 9789 return null; 9790 } 9791 9792 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9793 } 9794 9795 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9796 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9797 if (pkgInfo.verifiers.length == 0) { 9798 return null; 9799 } 9800 9801 final int N = pkgInfo.verifiers.length; 9802 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9803 for (int i = 0; i < N; i++) { 9804 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9805 9806 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9807 receivers); 9808 if (comp == null) { 9809 continue; 9810 } 9811 9812 final int verifierUid = getUidForVerifier(verifierInfo); 9813 if (verifierUid == -1) { 9814 continue; 9815 } 9816 9817 if (DEBUG_VERIFY) { 9818 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9819 + " with the correct signature"); 9820 } 9821 sufficientVerifiers.add(comp); 9822 verificationState.addSufficientVerifier(verifierUid); 9823 } 9824 9825 return sufficientVerifiers; 9826 } 9827 9828 private int getUidForVerifier(VerifierInfo verifierInfo) { 9829 synchronized (mPackages) { 9830 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9831 if (pkg == null) { 9832 return -1; 9833 } else if (pkg.mSignatures.length != 1) { 9834 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9835 + " has more than one signature; ignoring"); 9836 return -1; 9837 } 9838 9839 /* 9840 * If the public key of the package's signature does not match 9841 * our expected public key, then this is a different package and 9842 * we should skip. 9843 */ 9844 9845 final byte[] expectedPublicKey; 9846 try { 9847 final Signature verifierSig = pkg.mSignatures[0]; 9848 final PublicKey publicKey = verifierSig.getPublicKey(); 9849 expectedPublicKey = publicKey.getEncoded(); 9850 } catch (CertificateException e) { 9851 return -1; 9852 } 9853 9854 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9855 9856 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9857 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9858 + " does not have the expected public key; ignoring"); 9859 return -1; 9860 } 9861 9862 return pkg.applicationInfo.uid; 9863 } 9864 } 9865 9866 @Override 9867 public void finishPackageInstall(int token) { 9868 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9869 9870 if (DEBUG_INSTALL) { 9871 Slog.v(TAG, "BM finishing package install for " + token); 9872 } 9873 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 9874 9875 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9876 mHandler.sendMessage(msg); 9877 } 9878 9879 /** 9880 * Get the verification agent timeout. 9881 * 9882 * @return verification timeout in milliseconds 9883 */ 9884 private long getVerificationTimeout() { 9885 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9886 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9887 DEFAULT_VERIFICATION_TIMEOUT); 9888 } 9889 9890 /** 9891 * Get the default verification agent response code. 9892 * 9893 * @return default verification response code 9894 */ 9895 private int getDefaultVerificationResponse() { 9896 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9897 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9898 DEFAULT_VERIFICATION_RESPONSE); 9899 } 9900 9901 /** 9902 * Check whether or not package verification has been enabled. 9903 * 9904 * @return true if verification should be performed 9905 */ 9906 private boolean isVerificationEnabled(int userId, int installFlags) { 9907 if (!DEFAULT_VERIFY_ENABLE) { 9908 return false; 9909 } 9910 // TODO: fix b/25118622; don't bypass verification 9911 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 9912 return false; 9913 } 9914 9915 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9916 9917 // Check if installing from ADB 9918 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9919 // Do not run verification in a test harness environment 9920 if (ActivityManager.isRunningInTestHarness()) { 9921 return false; 9922 } 9923 if (ensureVerifyAppsEnabled) { 9924 return true; 9925 } 9926 // Check if the developer does not want package verification for ADB installs 9927 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9928 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9929 return false; 9930 } 9931 } 9932 9933 if (ensureVerifyAppsEnabled) { 9934 return true; 9935 } 9936 9937 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9938 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9939 } 9940 9941 @Override 9942 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9943 throws RemoteException { 9944 mContext.enforceCallingOrSelfPermission( 9945 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9946 "Only intentfilter verification agents can verify applications"); 9947 9948 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9949 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9950 Binder.getCallingUid(), verificationCode, failedDomains); 9951 msg.arg1 = id; 9952 msg.obj = response; 9953 mHandler.sendMessage(msg); 9954 } 9955 9956 @Override 9957 public int getIntentVerificationStatus(String packageName, int userId) { 9958 synchronized (mPackages) { 9959 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9960 } 9961 } 9962 9963 @Override 9964 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9965 mContext.enforceCallingOrSelfPermission( 9966 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9967 9968 boolean result = false; 9969 synchronized (mPackages) { 9970 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9971 } 9972 if (result) { 9973 scheduleWritePackageRestrictionsLocked(userId); 9974 } 9975 return result; 9976 } 9977 9978 @Override 9979 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9980 synchronized (mPackages) { 9981 return mSettings.getIntentFilterVerificationsLPr(packageName); 9982 } 9983 } 9984 9985 @Override 9986 public List<IntentFilter> getAllIntentFilters(String packageName) { 9987 if (TextUtils.isEmpty(packageName)) { 9988 return Collections.<IntentFilter>emptyList(); 9989 } 9990 synchronized (mPackages) { 9991 PackageParser.Package pkg = mPackages.get(packageName); 9992 if (pkg == null || pkg.activities == null) { 9993 return Collections.<IntentFilter>emptyList(); 9994 } 9995 final int count = pkg.activities.size(); 9996 ArrayList<IntentFilter> result = new ArrayList<>(); 9997 for (int n=0; n<count; n++) { 9998 PackageParser.Activity activity = pkg.activities.get(n); 9999 if (activity.intents != null || activity.intents.size() > 0) { 10000 result.addAll(activity.intents); 10001 } 10002 } 10003 return result; 10004 } 10005 } 10006 10007 @Override 10008 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10009 mContext.enforceCallingOrSelfPermission( 10010 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10011 10012 synchronized (mPackages) { 10013 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10014 if (packageName != null) { 10015 result |= updateIntentVerificationStatus(packageName, 10016 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10017 userId); 10018 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10019 packageName, userId); 10020 } 10021 return result; 10022 } 10023 } 10024 10025 @Override 10026 public String getDefaultBrowserPackageName(int userId) { 10027 synchronized (mPackages) { 10028 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10029 } 10030 } 10031 10032 /** 10033 * Get the "allow unknown sources" setting. 10034 * 10035 * @return the current "allow unknown sources" setting 10036 */ 10037 private int getUnknownSourcesSettings() { 10038 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10039 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10040 -1); 10041 } 10042 10043 @Override 10044 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10045 final int uid = Binder.getCallingUid(); 10046 // writer 10047 synchronized (mPackages) { 10048 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10049 if (targetPackageSetting == null) { 10050 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10051 } 10052 10053 PackageSetting installerPackageSetting; 10054 if (installerPackageName != null) { 10055 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10056 if (installerPackageSetting == null) { 10057 throw new IllegalArgumentException("Unknown installer package: " 10058 + installerPackageName); 10059 } 10060 } else { 10061 installerPackageSetting = null; 10062 } 10063 10064 Signature[] callerSignature; 10065 Object obj = mSettings.getUserIdLPr(uid); 10066 if (obj != null) { 10067 if (obj instanceof SharedUserSetting) { 10068 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10069 } else if (obj instanceof PackageSetting) { 10070 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10071 } else { 10072 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10073 } 10074 } else { 10075 throw new SecurityException("Unknown calling uid " + uid); 10076 } 10077 10078 // Verify: can't set installerPackageName to a package that is 10079 // not signed with the same cert as the caller. 10080 if (installerPackageSetting != null) { 10081 if (compareSignatures(callerSignature, 10082 installerPackageSetting.signatures.mSignatures) 10083 != PackageManager.SIGNATURE_MATCH) { 10084 throw new SecurityException( 10085 "Caller does not have same cert as new installer package " 10086 + installerPackageName); 10087 } 10088 } 10089 10090 // Verify: if target already has an installer package, it must 10091 // be signed with the same cert as the caller. 10092 if (targetPackageSetting.installerPackageName != null) { 10093 PackageSetting setting = mSettings.mPackages.get( 10094 targetPackageSetting.installerPackageName); 10095 // If the currently set package isn't valid, then it's always 10096 // okay to change it. 10097 if (setting != null) { 10098 if (compareSignatures(callerSignature, 10099 setting.signatures.mSignatures) 10100 != PackageManager.SIGNATURE_MATCH) { 10101 throw new SecurityException( 10102 "Caller does not have same cert as old installer package " 10103 + targetPackageSetting.installerPackageName); 10104 } 10105 } 10106 } 10107 10108 // Okay! 10109 targetPackageSetting.installerPackageName = installerPackageName; 10110 scheduleWriteSettingsLocked(); 10111 } 10112 } 10113 10114 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10115 // Queue up an async operation since the package installation may take a little while. 10116 mHandler.post(new Runnable() { 10117 public void run() { 10118 mHandler.removeCallbacks(this); 10119 // Result object to be returned 10120 PackageInstalledInfo res = new PackageInstalledInfo(); 10121 res.returnCode = currentStatus; 10122 res.uid = -1; 10123 res.pkg = null; 10124 res.removedInfo = new PackageRemovedInfo(); 10125 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10126 args.doPreInstall(res.returnCode); 10127 synchronized (mInstallLock) { 10128 installPackageTracedLI(args, res); 10129 } 10130 args.doPostInstall(res.returnCode, res.uid); 10131 } 10132 10133 // A restore should be performed at this point if (a) the install 10134 // succeeded, (b) the operation is not an update, and (c) the new 10135 // package has not opted out of backup participation. 10136 final boolean update = res.removedInfo.removedPackage != null; 10137 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10138 boolean doRestore = !update 10139 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10140 10141 // Set up the post-install work request bookkeeping. This will be used 10142 // and cleaned up by the post-install event handling regardless of whether 10143 // there's a restore pass performed. Token values are >= 1. 10144 int token; 10145 if (mNextInstallToken < 0) mNextInstallToken = 1; 10146 token = mNextInstallToken++; 10147 10148 PostInstallData data = new PostInstallData(args, res); 10149 mRunningInstalls.put(token, data); 10150 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10151 10152 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10153 // Pass responsibility to the Backup Manager. It will perform a 10154 // restore if appropriate, then pass responsibility back to the 10155 // Package Manager to run the post-install observer callbacks 10156 // and broadcasts. 10157 IBackupManager bm = IBackupManager.Stub.asInterface( 10158 ServiceManager.getService(Context.BACKUP_SERVICE)); 10159 if (bm != null) { 10160 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10161 + " to BM for possible restore"); 10162 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10163 try { 10164 // TODO: http://b/22388012 10165 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10166 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10167 } else { 10168 doRestore = false; 10169 } 10170 } catch (RemoteException e) { 10171 // can't happen; the backup manager is local 10172 } catch (Exception e) { 10173 Slog.e(TAG, "Exception trying to enqueue restore", e); 10174 doRestore = false; 10175 } 10176 } else { 10177 Slog.e(TAG, "Backup Manager not found!"); 10178 doRestore = false; 10179 } 10180 } 10181 10182 if (!doRestore) { 10183 // No restore possible, or the Backup Manager was mysteriously not 10184 // available -- just fire the post-install work request directly. 10185 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10186 10187 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10188 10189 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10190 mHandler.sendMessage(msg); 10191 } 10192 } 10193 }); 10194 } 10195 10196 private abstract class HandlerParams { 10197 private static final int MAX_RETRIES = 4; 10198 10199 /** 10200 * Number of times startCopy() has been attempted and had a non-fatal 10201 * error. 10202 */ 10203 private int mRetries = 0; 10204 10205 /** User handle for the user requesting the information or installation. */ 10206 private final UserHandle mUser; 10207 String traceMethod; 10208 int traceCookie; 10209 10210 HandlerParams(UserHandle user) { 10211 mUser = user; 10212 } 10213 10214 UserHandle getUser() { 10215 return mUser; 10216 } 10217 10218 HandlerParams setTraceMethod(String traceMethod) { 10219 this.traceMethod = traceMethod; 10220 return this; 10221 } 10222 10223 HandlerParams setTraceCookie(int traceCookie) { 10224 this.traceCookie = traceCookie; 10225 return this; 10226 } 10227 10228 final boolean startCopy() { 10229 boolean res; 10230 try { 10231 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10232 10233 if (++mRetries > MAX_RETRIES) { 10234 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10235 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10236 handleServiceError(); 10237 return false; 10238 } else { 10239 handleStartCopy(); 10240 res = true; 10241 } 10242 } catch (RemoteException e) { 10243 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10244 mHandler.sendEmptyMessage(MCS_RECONNECT); 10245 res = false; 10246 } 10247 handleReturnCode(); 10248 return res; 10249 } 10250 10251 final void serviceError() { 10252 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10253 handleServiceError(); 10254 handleReturnCode(); 10255 } 10256 10257 abstract void handleStartCopy() throws RemoteException; 10258 abstract void handleServiceError(); 10259 abstract void handleReturnCode(); 10260 } 10261 10262 class MeasureParams extends HandlerParams { 10263 private final PackageStats mStats; 10264 private boolean mSuccess; 10265 10266 private final IPackageStatsObserver mObserver; 10267 10268 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10269 super(new UserHandle(stats.userHandle)); 10270 mObserver = observer; 10271 mStats = stats; 10272 } 10273 10274 @Override 10275 public String toString() { 10276 return "MeasureParams{" 10277 + Integer.toHexString(System.identityHashCode(this)) 10278 + " " + mStats.packageName + "}"; 10279 } 10280 10281 @Override 10282 void handleStartCopy() throws RemoteException { 10283 synchronized (mInstallLock) { 10284 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10285 } 10286 10287 if (mSuccess) { 10288 final boolean mounted; 10289 if (Environment.isExternalStorageEmulated()) { 10290 mounted = true; 10291 } else { 10292 final String status = Environment.getExternalStorageState(); 10293 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10294 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10295 } 10296 10297 if (mounted) { 10298 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10299 10300 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10301 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10302 10303 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10304 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10305 10306 // Always subtract cache size, since it's a subdirectory 10307 mStats.externalDataSize -= mStats.externalCacheSize; 10308 10309 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10310 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10311 10312 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10313 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10314 } 10315 } 10316 } 10317 10318 @Override 10319 void handleReturnCode() { 10320 if (mObserver != null) { 10321 try { 10322 mObserver.onGetStatsCompleted(mStats, mSuccess); 10323 } catch (RemoteException e) { 10324 Slog.i(TAG, "Observer no longer exists."); 10325 } 10326 } 10327 } 10328 10329 @Override 10330 void handleServiceError() { 10331 Slog.e(TAG, "Could not measure application " + mStats.packageName 10332 + " external storage"); 10333 } 10334 } 10335 10336 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10337 throws RemoteException { 10338 long result = 0; 10339 for (File path : paths) { 10340 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10341 } 10342 return result; 10343 } 10344 10345 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10346 for (File path : paths) { 10347 try { 10348 mcs.clearDirectory(path.getAbsolutePath()); 10349 } catch (RemoteException e) { 10350 } 10351 } 10352 } 10353 10354 static class OriginInfo { 10355 /** 10356 * Location where install is coming from, before it has been 10357 * copied/renamed into place. This could be a single monolithic APK 10358 * file, or a cluster directory. This location may be untrusted. 10359 */ 10360 final File file; 10361 final String cid; 10362 10363 /** 10364 * Flag indicating that {@link #file} or {@link #cid} has already been 10365 * staged, meaning downstream users don't need to defensively copy the 10366 * contents. 10367 */ 10368 final boolean staged; 10369 10370 /** 10371 * Flag indicating that {@link #file} or {@link #cid} is an already 10372 * installed app that is being moved. 10373 */ 10374 final boolean existing; 10375 10376 final String resolvedPath; 10377 final File resolvedFile; 10378 10379 static OriginInfo fromNothing() { 10380 return new OriginInfo(null, null, false, false); 10381 } 10382 10383 static OriginInfo fromUntrustedFile(File file) { 10384 return new OriginInfo(file, null, false, false); 10385 } 10386 10387 static OriginInfo fromExistingFile(File file) { 10388 return new OriginInfo(file, null, false, true); 10389 } 10390 10391 static OriginInfo fromStagedFile(File file) { 10392 return new OriginInfo(file, null, true, false); 10393 } 10394 10395 static OriginInfo fromStagedContainer(String cid) { 10396 return new OriginInfo(null, cid, true, false); 10397 } 10398 10399 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10400 this.file = file; 10401 this.cid = cid; 10402 this.staged = staged; 10403 this.existing = existing; 10404 10405 if (cid != null) { 10406 resolvedPath = PackageHelper.getSdDir(cid); 10407 resolvedFile = new File(resolvedPath); 10408 } else if (file != null) { 10409 resolvedPath = file.getAbsolutePath(); 10410 resolvedFile = file; 10411 } else { 10412 resolvedPath = null; 10413 resolvedFile = null; 10414 } 10415 } 10416 } 10417 10418 class MoveInfo { 10419 final int moveId; 10420 final String fromUuid; 10421 final String toUuid; 10422 final String packageName; 10423 final String dataAppName; 10424 final int appId; 10425 final String seinfo; 10426 10427 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10428 String dataAppName, int appId, String seinfo) { 10429 this.moveId = moveId; 10430 this.fromUuid = fromUuid; 10431 this.toUuid = toUuid; 10432 this.packageName = packageName; 10433 this.dataAppName = dataAppName; 10434 this.appId = appId; 10435 this.seinfo = seinfo; 10436 } 10437 } 10438 10439 class InstallParams extends HandlerParams { 10440 final OriginInfo origin; 10441 final MoveInfo move; 10442 final IPackageInstallObserver2 observer; 10443 int installFlags; 10444 final String installerPackageName; 10445 final String volumeUuid; 10446 final VerificationParams verificationParams; 10447 private InstallArgs mArgs; 10448 private int mRet; 10449 final String packageAbiOverride; 10450 final String[] grantedRuntimePermissions; 10451 10452 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10453 int installFlags, String installerPackageName, String volumeUuid, 10454 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10455 String[] grantedPermissions) { 10456 super(user); 10457 this.origin = origin; 10458 this.move = move; 10459 this.observer = observer; 10460 this.installFlags = installFlags; 10461 this.installerPackageName = installerPackageName; 10462 this.volumeUuid = volumeUuid; 10463 this.verificationParams = verificationParams; 10464 this.packageAbiOverride = packageAbiOverride; 10465 this.grantedRuntimePermissions = grantedPermissions; 10466 } 10467 10468 @Override 10469 public String toString() { 10470 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10471 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10472 } 10473 10474 public ManifestDigest getManifestDigest() { 10475 if (verificationParams == null) { 10476 return null; 10477 } 10478 return verificationParams.getManifestDigest(); 10479 } 10480 10481 private int installLocationPolicy(PackageInfoLite pkgLite) { 10482 String packageName = pkgLite.packageName; 10483 int installLocation = pkgLite.installLocation; 10484 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10485 // reader 10486 synchronized (mPackages) { 10487 PackageParser.Package pkg = mPackages.get(packageName); 10488 if (pkg != null) { 10489 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10490 // Check for downgrading. 10491 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10492 try { 10493 checkDowngrade(pkg, pkgLite); 10494 } catch (PackageManagerException e) { 10495 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10496 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10497 } 10498 } 10499 // Check for updated system application. 10500 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10501 if (onSd) { 10502 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10503 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10504 } 10505 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10506 } else { 10507 if (onSd) { 10508 // Install flag overrides everything. 10509 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10510 } 10511 // If current upgrade specifies particular preference 10512 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10513 // Application explicitly specified internal. 10514 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10515 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10516 // App explictly prefers external. Let policy decide 10517 } else { 10518 // Prefer previous location 10519 if (isExternal(pkg)) { 10520 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10521 } 10522 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10523 } 10524 } 10525 } else { 10526 // Invalid install. Return error code 10527 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10528 } 10529 } 10530 } 10531 // All the special cases have been taken care of. 10532 // Return result based on recommended install location. 10533 if (onSd) { 10534 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10535 } 10536 return pkgLite.recommendedInstallLocation; 10537 } 10538 10539 /* 10540 * Invoke remote method to get package information and install 10541 * location values. Override install location based on default 10542 * policy if needed and then create install arguments based 10543 * on the install location. 10544 */ 10545 public void handleStartCopy() throws RemoteException { 10546 int ret = PackageManager.INSTALL_SUCCEEDED; 10547 10548 // If we're already staged, we've firmly committed to an install location 10549 if (origin.staged) { 10550 if (origin.file != null) { 10551 installFlags |= PackageManager.INSTALL_INTERNAL; 10552 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10553 } else if (origin.cid != null) { 10554 installFlags |= PackageManager.INSTALL_EXTERNAL; 10555 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10556 } else { 10557 throw new IllegalStateException("Invalid stage location"); 10558 } 10559 } 10560 10561 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10562 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10563 PackageInfoLite pkgLite = null; 10564 10565 if (onInt && onSd) { 10566 // Check if both bits are set. 10567 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10568 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10569 } else { 10570 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10571 packageAbiOverride); 10572 10573 /* 10574 * If we have too little free space, try to free cache 10575 * before giving up. 10576 */ 10577 if (!origin.staged && pkgLite.recommendedInstallLocation 10578 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10579 // TODO: focus freeing disk space on the target device 10580 final StorageManager storage = StorageManager.from(mContext); 10581 final long lowThreshold = storage.getStorageLowBytes( 10582 Environment.getDataDirectory()); 10583 10584 final long sizeBytes = mContainerService.calculateInstalledSize( 10585 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10586 10587 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10588 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10589 installFlags, packageAbiOverride); 10590 } 10591 10592 /* 10593 * The cache free must have deleted the file we 10594 * downloaded to install. 10595 * 10596 * TODO: fix the "freeCache" call to not delete 10597 * the file we care about. 10598 */ 10599 if (pkgLite.recommendedInstallLocation 10600 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10601 pkgLite.recommendedInstallLocation 10602 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10603 } 10604 } 10605 } 10606 10607 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10608 int loc = pkgLite.recommendedInstallLocation; 10609 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10610 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10611 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10612 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10613 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10614 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10615 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10616 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10617 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10618 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10619 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10620 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10621 } else { 10622 // Override with defaults if needed. 10623 loc = installLocationPolicy(pkgLite); 10624 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10625 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10626 } else if (!onSd && !onInt) { 10627 // Override install location with flags 10628 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10629 // Set the flag to install on external media. 10630 installFlags |= PackageManager.INSTALL_EXTERNAL; 10631 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10632 } else { 10633 // Make sure the flag for installing on external 10634 // media is unset 10635 installFlags |= PackageManager.INSTALL_INTERNAL; 10636 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10637 } 10638 } 10639 } 10640 } 10641 10642 final InstallArgs args = createInstallArgs(this); 10643 mArgs = args; 10644 10645 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10646 // TODO: http://b/22976637 10647 // Apps installed for "all" users use the device owner to verify the app 10648 UserHandle verifierUser = getUser(); 10649 if (verifierUser == UserHandle.ALL) { 10650 verifierUser = UserHandle.SYSTEM; 10651 } 10652 10653 /* 10654 * Determine if we have any installed package verifiers. If we 10655 * do, then we'll defer to them to verify the packages. 10656 */ 10657 final int requiredUid = mRequiredVerifierPackage == null ? -1 10658 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10659 if (!origin.existing && requiredUid != -1 10660 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10661 final Intent verification = new Intent( 10662 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10663 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10664 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10665 PACKAGE_MIME_TYPE); 10666 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10667 10668 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10669 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10670 verifierUser.getIdentifier()); 10671 10672 if (DEBUG_VERIFY) { 10673 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10674 + verification.toString() + " with " + pkgLite.verifiers.length 10675 + " optional verifiers"); 10676 } 10677 10678 final int verificationId = mPendingVerificationToken++; 10679 10680 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10681 10682 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10683 installerPackageName); 10684 10685 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10686 installFlags); 10687 10688 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10689 pkgLite.packageName); 10690 10691 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10692 pkgLite.versionCode); 10693 10694 if (verificationParams != null) { 10695 if (verificationParams.getVerificationURI() != null) { 10696 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10697 verificationParams.getVerificationURI()); 10698 } 10699 if (verificationParams.getOriginatingURI() != null) { 10700 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10701 verificationParams.getOriginatingURI()); 10702 } 10703 if (verificationParams.getReferrer() != null) { 10704 verification.putExtra(Intent.EXTRA_REFERRER, 10705 verificationParams.getReferrer()); 10706 } 10707 if (verificationParams.getOriginatingUid() >= 0) { 10708 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10709 verificationParams.getOriginatingUid()); 10710 } 10711 if (verificationParams.getInstallerUid() >= 0) { 10712 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10713 verificationParams.getInstallerUid()); 10714 } 10715 } 10716 10717 final PackageVerificationState verificationState = new PackageVerificationState( 10718 requiredUid, args); 10719 10720 mPendingVerification.append(verificationId, verificationState); 10721 10722 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10723 receivers, verificationState); 10724 10725 /* 10726 * If any sufficient verifiers were listed in the package 10727 * manifest, attempt to ask them. 10728 */ 10729 if (sufficientVerifiers != null) { 10730 final int N = sufficientVerifiers.size(); 10731 if (N == 0) { 10732 Slog.i(TAG, "Additional verifiers required, but none installed."); 10733 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10734 } else { 10735 for (int i = 0; i < N; i++) { 10736 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10737 10738 final Intent sufficientIntent = new Intent(verification); 10739 sufficientIntent.setComponent(verifierComponent); 10740 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10741 } 10742 } 10743 } 10744 10745 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10746 mRequiredVerifierPackage, receivers); 10747 if (ret == PackageManager.INSTALL_SUCCEEDED 10748 && mRequiredVerifierPackage != null) { 10749 Trace.asyncTraceBegin( 10750 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10751 /* 10752 * Send the intent to the required verification agent, 10753 * but only start the verification timeout after the 10754 * target BroadcastReceivers have run. 10755 */ 10756 verification.setComponent(requiredVerifierComponent); 10757 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10758 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10759 new BroadcastReceiver() { 10760 @Override 10761 public void onReceive(Context context, Intent intent) { 10762 final Message msg = mHandler 10763 .obtainMessage(CHECK_PENDING_VERIFICATION); 10764 msg.arg1 = verificationId; 10765 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10766 } 10767 }, null, 0, null, null); 10768 10769 /* 10770 * We don't want the copy to proceed until verification 10771 * succeeds, so null out this field. 10772 */ 10773 mArgs = null; 10774 } 10775 } else { 10776 /* 10777 * No package verification is enabled, so immediately start 10778 * the remote call to initiate copy using temporary file. 10779 */ 10780 ret = args.copyApk(mContainerService, true); 10781 } 10782 } 10783 10784 mRet = ret; 10785 } 10786 10787 @Override 10788 void handleReturnCode() { 10789 // If mArgs is null, then MCS couldn't be reached. When it 10790 // reconnects, it will try again to install. At that point, this 10791 // will succeed. 10792 if (mArgs != null) { 10793 processPendingInstall(mArgs, mRet); 10794 } 10795 } 10796 10797 @Override 10798 void handleServiceError() { 10799 mArgs = createInstallArgs(this); 10800 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10801 } 10802 10803 public boolean isForwardLocked() { 10804 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10805 } 10806 } 10807 10808 /** 10809 * Used during creation of InstallArgs 10810 * 10811 * @param installFlags package installation flags 10812 * @return true if should be installed on external storage 10813 */ 10814 private static boolean installOnExternalAsec(int installFlags) { 10815 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10816 return false; 10817 } 10818 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10819 return true; 10820 } 10821 return false; 10822 } 10823 10824 /** 10825 * Used during creation of InstallArgs 10826 * 10827 * @param installFlags package installation flags 10828 * @return true if should be installed as forward locked 10829 */ 10830 private static boolean installForwardLocked(int installFlags) { 10831 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10832 } 10833 10834 private InstallArgs createInstallArgs(InstallParams params) { 10835 if (params.move != null) { 10836 return new MoveInstallArgs(params); 10837 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10838 return new AsecInstallArgs(params); 10839 } else { 10840 return new FileInstallArgs(params); 10841 } 10842 } 10843 10844 /** 10845 * Create args that describe an existing installed package. Typically used 10846 * when cleaning up old installs, or used as a move source. 10847 */ 10848 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10849 String resourcePath, String[] instructionSets) { 10850 final boolean isInAsec; 10851 if (installOnExternalAsec(installFlags)) { 10852 /* Apps on SD card are always in ASEC containers. */ 10853 isInAsec = true; 10854 } else if (installForwardLocked(installFlags) 10855 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10856 /* 10857 * Forward-locked apps are only in ASEC containers if they're the 10858 * new style 10859 */ 10860 isInAsec = true; 10861 } else { 10862 isInAsec = false; 10863 } 10864 10865 if (isInAsec) { 10866 return new AsecInstallArgs(codePath, instructionSets, 10867 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10868 } else { 10869 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10870 } 10871 } 10872 10873 static abstract class InstallArgs { 10874 /** @see InstallParams#origin */ 10875 final OriginInfo origin; 10876 /** @see InstallParams#move */ 10877 final MoveInfo move; 10878 10879 final IPackageInstallObserver2 observer; 10880 // Always refers to PackageManager flags only 10881 final int installFlags; 10882 final String installerPackageName; 10883 final String volumeUuid; 10884 final ManifestDigest manifestDigest; 10885 final UserHandle user; 10886 final String abiOverride; 10887 final String[] installGrantPermissions; 10888 /** If non-null, drop an async trace when the install completes */ 10889 final String traceMethod; 10890 final int traceCookie; 10891 10892 // The list of instruction sets supported by this app. This is currently 10893 // only used during the rmdex() phase to clean up resources. We can get rid of this 10894 // if we move dex files under the common app path. 10895 /* nullable */ String[] instructionSets; 10896 10897 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10898 int installFlags, String installerPackageName, String volumeUuid, 10899 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10900 String abiOverride, String[] installGrantPermissions, 10901 String traceMethod, int traceCookie) { 10902 this.origin = origin; 10903 this.move = move; 10904 this.installFlags = installFlags; 10905 this.observer = observer; 10906 this.installerPackageName = installerPackageName; 10907 this.volumeUuid = volumeUuid; 10908 this.manifestDigest = manifestDigest; 10909 this.user = user; 10910 this.instructionSets = instructionSets; 10911 this.abiOverride = abiOverride; 10912 this.installGrantPermissions = installGrantPermissions; 10913 this.traceMethod = traceMethod; 10914 this.traceCookie = traceCookie; 10915 } 10916 10917 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10918 abstract int doPreInstall(int status); 10919 10920 /** 10921 * Rename package into final resting place. All paths on the given 10922 * scanned package should be updated to reflect the rename. 10923 */ 10924 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10925 abstract int doPostInstall(int status, int uid); 10926 10927 /** @see PackageSettingBase#codePathString */ 10928 abstract String getCodePath(); 10929 /** @see PackageSettingBase#resourcePathString */ 10930 abstract String getResourcePath(); 10931 10932 // Need installer lock especially for dex file removal. 10933 abstract void cleanUpResourcesLI(); 10934 abstract boolean doPostDeleteLI(boolean delete); 10935 10936 /** 10937 * Called before the source arguments are copied. This is used mostly 10938 * for MoveParams when it needs to read the source file to put it in the 10939 * destination. 10940 */ 10941 int doPreCopy() { 10942 return PackageManager.INSTALL_SUCCEEDED; 10943 } 10944 10945 /** 10946 * Called after the source arguments are copied. This is used mostly for 10947 * MoveParams when it needs to read the source file to put it in the 10948 * destination. 10949 * 10950 * @return 10951 */ 10952 int doPostCopy(int uid) { 10953 return PackageManager.INSTALL_SUCCEEDED; 10954 } 10955 10956 protected boolean isFwdLocked() { 10957 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10958 } 10959 10960 protected boolean isExternalAsec() { 10961 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10962 } 10963 10964 UserHandle getUser() { 10965 return user; 10966 } 10967 } 10968 10969 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10970 if (!allCodePaths.isEmpty()) { 10971 if (instructionSets == null) { 10972 throw new IllegalStateException("instructionSet == null"); 10973 } 10974 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10975 for (String codePath : allCodePaths) { 10976 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10977 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10978 if (retCode < 0) { 10979 Slog.w(TAG, "Couldn't remove dex file for package: " 10980 + " at location " + codePath + ", retcode=" + retCode); 10981 // we don't consider this to be a failure of the core package deletion 10982 } 10983 } 10984 } 10985 } 10986 } 10987 10988 /** 10989 * Logic to handle installation of non-ASEC applications, including copying 10990 * and renaming logic. 10991 */ 10992 class FileInstallArgs extends InstallArgs { 10993 private File codeFile; 10994 private File resourceFile; 10995 10996 // Example topology: 10997 // /data/app/com.example/base.apk 10998 // /data/app/com.example/split_foo.apk 10999 // /data/app/com.example/lib/arm/libfoo.so 11000 // /data/app/com.example/lib/arm64/libfoo.so 11001 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11002 11003 /** New install */ 11004 FileInstallArgs(InstallParams params) { 11005 super(params.origin, params.move, params.observer, params.installFlags, 11006 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11007 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11008 params.grantedRuntimePermissions, 11009 params.traceMethod, params.traceCookie); 11010 if (isFwdLocked()) { 11011 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11012 } 11013 } 11014 11015 /** Existing install */ 11016 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11017 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11018 null, null, null, 0); 11019 this.codeFile = (codePath != null) ? new File(codePath) : null; 11020 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11021 } 11022 11023 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11024 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11025 try { 11026 return doCopyApk(imcs, temp); 11027 } finally { 11028 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11029 } 11030 } 11031 11032 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11033 if (origin.staged) { 11034 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11035 codeFile = origin.file; 11036 resourceFile = origin.file; 11037 return PackageManager.INSTALL_SUCCEEDED; 11038 } 11039 11040 try { 11041 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11042 codeFile = tempDir; 11043 resourceFile = tempDir; 11044 } catch (IOException e) { 11045 Slog.w(TAG, "Failed to create copy file: " + e); 11046 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11047 } 11048 11049 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11050 @Override 11051 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11052 if (!FileUtils.isValidExtFilename(name)) { 11053 throw new IllegalArgumentException("Invalid filename: " + name); 11054 } 11055 try { 11056 final File file = new File(codeFile, name); 11057 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11058 O_RDWR | O_CREAT, 0644); 11059 Os.chmod(file.getAbsolutePath(), 0644); 11060 return new ParcelFileDescriptor(fd); 11061 } catch (ErrnoException e) { 11062 throw new RemoteException("Failed to open: " + e.getMessage()); 11063 } 11064 } 11065 }; 11066 11067 int ret = PackageManager.INSTALL_SUCCEEDED; 11068 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11069 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11070 Slog.e(TAG, "Failed to copy package"); 11071 return ret; 11072 } 11073 11074 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11075 NativeLibraryHelper.Handle handle = null; 11076 try { 11077 handle = NativeLibraryHelper.Handle.create(codeFile); 11078 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11079 abiOverride); 11080 } catch (IOException e) { 11081 Slog.e(TAG, "Copying native libraries failed", e); 11082 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11083 } finally { 11084 IoUtils.closeQuietly(handle); 11085 } 11086 11087 return ret; 11088 } 11089 11090 int doPreInstall(int status) { 11091 if (status != PackageManager.INSTALL_SUCCEEDED) { 11092 cleanUp(); 11093 } 11094 return status; 11095 } 11096 11097 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11098 if (status != PackageManager.INSTALL_SUCCEEDED) { 11099 cleanUp(); 11100 return false; 11101 } 11102 11103 final File targetDir = codeFile.getParentFile(); 11104 final File beforeCodeFile = codeFile; 11105 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11106 11107 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11108 try { 11109 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11110 } catch (ErrnoException e) { 11111 Slog.w(TAG, "Failed to rename", e); 11112 return false; 11113 } 11114 11115 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11116 Slog.w(TAG, "Failed to restorecon"); 11117 return false; 11118 } 11119 11120 // Reflect the rename internally 11121 codeFile = afterCodeFile; 11122 resourceFile = afterCodeFile; 11123 11124 // Reflect the rename in scanned details 11125 pkg.codePath = afterCodeFile.getAbsolutePath(); 11126 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11127 pkg.baseCodePath); 11128 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11129 pkg.splitCodePaths); 11130 11131 // Reflect the rename in app info 11132 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11133 pkg.applicationInfo.setCodePath(pkg.codePath); 11134 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11135 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11136 pkg.applicationInfo.setResourcePath(pkg.codePath); 11137 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11138 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11139 11140 return true; 11141 } 11142 11143 int doPostInstall(int status, int uid) { 11144 if (status != PackageManager.INSTALL_SUCCEEDED) { 11145 cleanUp(); 11146 } 11147 return status; 11148 } 11149 11150 @Override 11151 String getCodePath() { 11152 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11153 } 11154 11155 @Override 11156 String getResourcePath() { 11157 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11158 } 11159 11160 private boolean cleanUp() { 11161 if (codeFile == null || !codeFile.exists()) { 11162 return false; 11163 } 11164 11165 if (codeFile.isDirectory()) { 11166 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11167 } else { 11168 codeFile.delete(); 11169 } 11170 11171 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11172 resourceFile.delete(); 11173 } 11174 11175 return true; 11176 } 11177 11178 void cleanUpResourcesLI() { 11179 // Try enumerating all code paths before deleting 11180 List<String> allCodePaths = Collections.EMPTY_LIST; 11181 if (codeFile != null && codeFile.exists()) { 11182 try { 11183 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11184 allCodePaths = pkg.getAllCodePaths(); 11185 } catch (PackageParserException e) { 11186 // Ignored; we tried our best 11187 } 11188 } 11189 11190 cleanUp(); 11191 removeDexFiles(allCodePaths, instructionSets); 11192 } 11193 11194 boolean doPostDeleteLI(boolean delete) { 11195 // XXX err, shouldn't we respect the delete flag? 11196 cleanUpResourcesLI(); 11197 return true; 11198 } 11199 } 11200 11201 private boolean isAsecExternal(String cid) { 11202 final String asecPath = PackageHelper.getSdFilesystem(cid); 11203 return !asecPath.startsWith(mAsecInternalPath); 11204 } 11205 11206 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11207 PackageManagerException { 11208 if (copyRet < 0) { 11209 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11210 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11211 throw new PackageManagerException(copyRet, message); 11212 } 11213 } 11214 } 11215 11216 /** 11217 * Extract the MountService "container ID" from the full code path of an 11218 * .apk. 11219 */ 11220 static String cidFromCodePath(String fullCodePath) { 11221 int eidx = fullCodePath.lastIndexOf("/"); 11222 String subStr1 = fullCodePath.substring(0, eidx); 11223 int sidx = subStr1.lastIndexOf("/"); 11224 return subStr1.substring(sidx+1, eidx); 11225 } 11226 11227 /** 11228 * Logic to handle installation of ASEC applications, including copying and 11229 * renaming logic. 11230 */ 11231 class AsecInstallArgs extends InstallArgs { 11232 static final String RES_FILE_NAME = "pkg.apk"; 11233 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11234 11235 String cid; 11236 String packagePath; 11237 String resourcePath; 11238 11239 /** New install */ 11240 AsecInstallArgs(InstallParams params) { 11241 super(params.origin, params.move, params.observer, params.installFlags, 11242 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11243 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11244 params.grantedRuntimePermissions, 11245 params.traceMethod, params.traceCookie); 11246 } 11247 11248 /** Existing install */ 11249 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11250 boolean isExternal, boolean isForwardLocked) { 11251 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11252 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11253 instructionSets, null, null, null, 0); 11254 // Hackily pretend we're still looking at a full code path 11255 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11256 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11257 } 11258 11259 // Extract cid from fullCodePath 11260 int eidx = fullCodePath.lastIndexOf("/"); 11261 String subStr1 = fullCodePath.substring(0, eidx); 11262 int sidx = subStr1.lastIndexOf("/"); 11263 cid = subStr1.substring(sidx+1, eidx); 11264 setMountPath(subStr1); 11265 } 11266 11267 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11268 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11269 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11270 instructionSets, null, null, null, 0); 11271 this.cid = cid; 11272 setMountPath(PackageHelper.getSdDir(cid)); 11273 } 11274 11275 void createCopyFile() { 11276 cid = mInstallerService.allocateExternalStageCidLegacy(); 11277 } 11278 11279 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11280 if (origin.staged) { 11281 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11282 cid = origin.cid; 11283 setMountPath(PackageHelper.getSdDir(cid)); 11284 return PackageManager.INSTALL_SUCCEEDED; 11285 } 11286 11287 if (temp) { 11288 createCopyFile(); 11289 } else { 11290 /* 11291 * Pre-emptively destroy the container since it's destroyed if 11292 * copying fails due to it existing anyway. 11293 */ 11294 PackageHelper.destroySdDir(cid); 11295 } 11296 11297 final String newMountPath = imcs.copyPackageToContainer( 11298 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11299 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11300 11301 if (newMountPath != null) { 11302 setMountPath(newMountPath); 11303 return PackageManager.INSTALL_SUCCEEDED; 11304 } else { 11305 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11306 } 11307 } 11308 11309 @Override 11310 String getCodePath() { 11311 return packagePath; 11312 } 11313 11314 @Override 11315 String getResourcePath() { 11316 return resourcePath; 11317 } 11318 11319 int doPreInstall(int status) { 11320 if (status != PackageManager.INSTALL_SUCCEEDED) { 11321 // Destroy container 11322 PackageHelper.destroySdDir(cid); 11323 } else { 11324 boolean mounted = PackageHelper.isContainerMounted(cid); 11325 if (!mounted) { 11326 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11327 Process.SYSTEM_UID); 11328 if (newMountPath != null) { 11329 setMountPath(newMountPath); 11330 } else { 11331 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11332 } 11333 } 11334 } 11335 return status; 11336 } 11337 11338 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11339 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11340 String newMountPath = null; 11341 if (PackageHelper.isContainerMounted(cid)) { 11342 // Unmount the container 11343 if (!PackageHelper.unMountSdDir(cid)) { 11344 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11345 return false; 11346 } 11347 } 11348 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11349 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11350 " which might be stale. Will try to clean up."); 11351 // Clean up the stale container and proceed to recreate. 11352 if (!PackageHelper.destroySdDir(newCacheId)) { 11353 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11354 return false; 11355 } 11356 // Successfully cleaned up stale container. Try to rename again. 11357 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11358 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11359 + " inspite of cleaning it up."); 11360 return false; 11361 } 11362 } 11363 if (!PackageHelper.isContainerMounted(newCacheId)) { 11364 Slog.w(TAG, "Mounting container " + newCacheId); 11365 newMountPath = PackageHelper.mountSdDir(newCacheId, 11366 getEncryptKey(), Process.SYSTEM_UID); 11367 } else { 11368 newMountPath = PackageHelper.getSdDir(newCacheId); 11369 } 11370 if (newMountPath == null) { 11371 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11372 return false; 11373 } 11374 Log.i(TAG, "Succesfully renamed " + cid + 11375 " to " + newCacheId + 11376 " at new path: " + newMountPath); 11377 cid = newCacheId; 11378 11379 final File beforeCodeFile = new File(packagePath); 11380 setMountPath(newMountPath); 11381 final File afterCodeFile = new File(packagePath); 11382 11383 // Reflect the rename in scanned details 11384 pkg.codePath = afterCodeFile.getAbsolutePath(); 11385 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11386 pkg.baseCodePath); 11387 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11388 pkg.splitCodePaths); 11389 11390 // Reflect the rename in app info 11391 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11392 pkg.applicationInfo.setCodePath(pkg.codePath); 11393 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11394 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11395 pkg.applicationInfo.setResourcePath(pkg.codePath); 11396 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11397 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11398 11399 return true; 11400 } 11401 11402 private void setMountPath(String mountPath) { 11403 final File mountFile = new File(mountPath); 11404 11405 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11406 if (monolithicFile.exists()) { 11407 packagePath = monolithicFile.getAbsolutePath(); 11408 if (isFwdLocked()) { 11409 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11410 } else { 11411 resourcePath = packagePath; 11412 } 11413 } else { 11414 packagePath = mountFile.getAbsolutePath(); 11415 resourcePath = packagePath; 11416 } 11417 } 11418 11419 int doPostInstall(int status, int uid) { 11420 if (status != PackageManager.INSTALL_SUCCEEDED) { 11421 cleanUp(); 11422 } else { 11423 final int groupOwner; 11424 final String protectedFile; 11425 if (isFwdLocked()) { 11426 groupOwner = UserHandle.getSharedAppGid(uid); 11427 protectedFile = RES_FILE_NAME; 11428 } else { 11429 groupOwner = -1; 11430 protectedFile = null; 11431 } 11432 11433 if (uid < Process.FIRST_APPLICATION_UID 11434 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11435 Slog.e(TAG, "Failed to finalize " + cid); 11436 PackageHelper.destroySdDir(cid); 11437 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11438 } 11439 11440 boolean mounted = PackageHelper.isContainerMounted(cid); 11441 if (!mounted) { 11442 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11443 } 11444 } 11445 return status; 11446 } 11447 11448 private void cleanUp() { 11449 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11450 11451 // Destroy secure container 11452 PackageHelper.destroySdDir(cid); 11453 } 11454 11455 private List<String> getAllCodePaths() { 11456 final File codeFile = new File(getCodePath()); 11457 if (codeFile != null && codeFile.exists()) { 11458 try { 11459 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11460 return pkg.getAllCodePaths(); 11461 } catch (PackageParserException e) { 11462 // Ignored; we tried our best 11463 } 11464 } 11465 return Collections.EMPTY_LIST; 11466 } 11467 11468 void cleanUpResourcesLI() { 11469 // Enumerate all code paths before deleting 11470 cleanUpResourcesLI(getAllCodePaths()); 11471 } 11472 11473 private void cleanUpResourcesLI(List<String> allCodePaths) { 11474 cleanUp(); 11475 removeDexFiles(allCodePaths, instructionSets); 11476 } 11477 11478 String getPackageName() { 11479 return getAsecPackageName(cid); 11480 } 11481 11482 boolean doPostDeleteLI(boolean delete) { 11483 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11484 final List<String> allCodePaths = getAllCodePaths(); 11485 boolean mounted = PackageHelper.isContainerMounted(cid); 11486 if (mounted) { 11487 // Unmount first 11488 if (PackageHelper.unMountSdDir(cid)) { 11489 mounted = false; 11490 } 11491 } 11492 if (!mounted && delete) { 11493 cleanUpResourcesLI(allCodePaths); 11494 } 11495 return !mounted; 11496 } 11497 11498 @Override 11499 int doPreCopy() { 11500 if (isFwdLocked()) { 11501 if (!PackageHelper.fixSdPermissions(cid, 11502 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11503 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11504 } 11505 } 11506 11507 return PackageManager.INSTALL_SUCCEEDED; 11508 } 11509 11510 @Override 11511 int doPostCopy(int uid) { 11512 if (isFwdLocked()) { 11513 if (uid < Process.FIRST_APPLICATION_UID 11514 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11515 RES_FILE_NAME)) { 11516 Slog.e(TAG, "Failed to finalize " + cid); 11517 PackageHelper.destroySdDir(cid); 11518 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11519 } 11520 } 11521 11522 return PackageManager.INSTALL_SUCCEEDED; 11523 } 11524 } 11525 11526 /** 11527 * Logic to handle movement of existing installed applications. 11528 */ 11529 class MoveInstallArgs extends InstallArgs { 11530 private File codeFile; 11531 private File resourceFile; 11532 11533 /** New install */ 11534 MoveInstallArgs(InstallParams params) { 11535 super(params.origin, params.move, params.observer, params.installFlags, 11536 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11537 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11538 params.grantedRuntimePermissions, 11539 params.traceMethod, params.traceCookie); 11540 } 11541 11542 int copyApk(IMediaContainerService imcs, boolean temp) { 11543 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11544 + move.fromUuid + " to " + move.toUuid); 11545 synchronized (mInstaller) { 11546 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11547 move.dataAppName, move.appId, move.seinfo) != 0) { 11548 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11549 } 11550 } 11551 11552 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11553 resourceFile = codeFile; 11554 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11555 11556 return PackageManager.INSTALL_SUCCEEDED; 11557 } 11558 11559 int doPreInstall(int status) { 11560 if (status != PackageManager.INSTALL_SUCCEEDED) { 11561 cleanUp(move.toUuid); 11562 } 11563 return status; 11564 } 11565 11566 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11567 if (status != PackageManager.INSTALL_SUCCEEDED) { 11568 cleanUp(move.toUuid); 11569 return false; 11570 } 11571 11572 // Reflect the move in app info 11573 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11574 pkg.applicationInfo.setCodePath(pkg.codePath); 11575 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11576 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11577 pkg.applicationInfo.setResourcePath(pkg.codePath); 11578 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11579 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11580 11581 return true; 11582 } 11583 11584 int doPostInstall(int status, int uid) { 11585 if (status == PackageManager.INSTALL_SUCCEEDED) { 11586 cleanUp(move.fromUuid); 11587 } else { 11588 cleanUp(move.toUuid); 11589 } 11590 return status; 11591 } 11592 11593 @Override 11594 String getCodePath() { 11595 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11596 } 11597 11598 @Override 11599 String getResourcePath() { 11600 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11601 } 11602 11603 private boolean cleanUp(String volumeUuid) { 11604 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11605 move.dataAppName); 11606 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11607 synchronized (mInstallLock) { 11608 // Clean up both app data and code 11609 removeDataDirsLI(volumeUuid, move.packageName); 11610 if (codeFile.isDirectory()) { 11611 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11612 } else { 11613 codeFile.delete(); 11614 } 11615 } 11616 return true; 11617 } 11618 11619 void cleanUpResourcesLI() { 11620 throw new UnsupportedOperationException(); 11621 } 11622 11623 boolean doPostDeleteLI(boolean delete) { 11624 throw new UnsupportedOperationException(); 11625 } 11626 } 11627 11628 static String getAsecPackageName(String packageCid) { 11629 int idx = packageCid.lastIndexOf("-"); 11630 if (idx == -1) { 11631 return packageCid; 11632 } 11633 return packageCid.substring(0, idx); 11634 } 11635 11636 // Utility method used to create code paths based on package name and available index. 11637 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11638 String idxStr = ""; 11639 int idx = 1; 11640 // Fall back to default value of idx=1 if prefix is not 11641 // part of oldCodePath 11642 if (oldCodePath != null) { 11643 String subStr = oldCodePath; 11644 // Drop the suffix right away 11645 if (suffix != null && subStr.endsWith(suffix)) { 11646 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11647 } 11648 // If oldCodePath already contains prefix find out the 11649 // ending index to either increment or decrement. 11650 int sidx = subStr.lastIndexOf(prefix); 11651 if (sidx != -1) { 11652 subStr = subStr.substring(sidx + prefix.length()); 11653 if (subStr != null) { 11654 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11655 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11656 } 11657 try { 11658 idx = Integer.parseInt(subStr); 11659 if (idx <= 1) { 11660 idx++; 11661 } else { 11662 idx--; 11663 } 11664 } catch(NumberFormatException e) { 11665 } 11666 } 11667 } 11668 } 11669 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11670 return prefix + idxStr; 11671 } 11672 11673 private File getNextCodePath(File targetDir, String packageName) { 11674 int suffix = 1; 11675 File result; 11676 do { 11677 result = new File(targetDir, packageName + "-" + suffix); 11678 suffix++; 11679 } while (result.exists()); 11680 return result; 11681 } 11682 11683 // Utility method that returns the relative package path with respect 11684 // to the installation directory. Like say for /data/data/com.test-1.apk 11685 // string com.test-1 is returned. 11686 static String deriveCodePathName(String codePath) { 11687 if (codePath == null) { 11688 return null; 11689 } 11690 final File codeFile = new File(codePath); 11691 final String name = codeFile.getName(); 11692 if (codeFile.isDirectory()) { 11693 return name; 11694 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11695 final int lastDot = name.lastIndexOf('.'); 11696 return name.substring(0, lastDot); 11697 } else { 11698 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11699 return null; 11700 } 11701 } 11702 11703 class PackageInstalledInfo { 11704 String name; 11705 int uid; 11706 // The set of users that originally had this package installed. 11707 int[] origUsers; 11708 // The set of users that now have this package installed. 11709 int[] newUsers; 11710 PackageParser.Package pkg; 11711 int returnCode; 11712 String returnMsg; 11713 PackageRemovedInfo removedInfo; 11714 11715 public void setError(int code, String msg) { 11716 returnCode = code; 11717 returnMsg = msg; 11718 Slog.w(TAG, msg); 11719 } 11720 11721 public void setError(String msg, PackageParserException e) { 11722 returnCode = e.error; 11723 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11724 Slog.w(TAG, msg, e); 11725 } 11726 11727 public void setError(String msg, PackageManagerException e) { 11728 returnCode = e.error; 11729 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11730 Slog.w(TAG, msg, e); 11731 } 11732 11733 // In some error cases we want to convey more info back to the observer 11734 String origPackage; 11735 String origPermission; 11736 } 11737 11738 /* 11739 * Install a non-existing package. 11740 */ 11741 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11742 UserHandle user, String installerPackageName, String volumeUuid, 11743 PackageInstalledInfo res) { 11744 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11745 11746 // Remember this for later, in case we need to rollback this install 11747 String pkgName = pkg.packageName; 11748 11749 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11750 // TODO: b/23350563 11751 final boolean dataDirExists = Environment 11752 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11753 11754 synchronized(mPackages) { 11755 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11756 // A package with the same name is already installed, though 11757 // it has been renamed to an older name. The package we 11758 // are trying to install should be installed as an update to 11759 // the existing one, but that has not been requested, so bail. 11760 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11761 + " without first uninstalling package running as " 11762 + mSettings.mRenamedPackages.get(pkgName)); 11763 return; 11764 } 11765 if (mPackages.containsKey(pkgName)) { 11766 // Don't allow installation over an existing package with the same name. 11767 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11768 + " without first uninstalling."); 11769 return; 11770 } 11771 } 11772 11773 try { 11774 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11775 System.currentTimeMillis(), user); 11776 11777 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11778 // delete the partially installed application. the data directory will have to be 11779 // restored if it was already existing 11780 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11781 // remove package from internal structures. Note that we want deletePackageX to 11782 // delete the package data and cache directories that it created in 11783 // scanPackageLocked, unless those directories existed before we even tried to 11784 // install. 11785 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11786 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11787 res.removedInfo, true); 11788 } 11789 11790 } catch (PackageManagerException e) { 11791 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11792 } 11793 11794 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11795 } 11796 11797 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11798 // Can't rotate keys during boot or if sharedUser. 11799 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11800 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11801 return false; 11802 } 11803 // app is using upgradeKeySets; make sure all are valid 11804 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11805 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11806 for (int i = 0; i < upgradeKeySets.length; i++) { 11807 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11808 Slog.wtf(TAG, "Package " 11809 + (oldPs.name != null ? oldPs.name : "<null>") 11810 + " contains upgrade-key-set reference to unknown key-set: " 11811 + upgradeKeySets[i] 11812 + " reverting to signatures check."); 11813 return false; 11814 } 11815 } 11816 return true; 11817 } 11818 11819 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11820 // Upgrade keysets are being used. Determine if new package has a superset of the 11821 // required keys. 11822 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11823 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11824 for (int i = 0; i < upgradeKeySets.length; i++) { 11825 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11826 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11827 return true; 11828 } 11829 } 11830 return false; 11831 } 11832 11833 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11834 UserHandle user, String installerPackageName, String volumeUuid, 11835 PackageInstalledInfo res) { 11836 final PackageParser.Package oldPackage; 11837 final String pkgName = pkg.packageName; 11838 final int[] allUsers; 11839 final boolean[] perUserInstalled; 11840 11841 // First find the old package info and check signatures 11842 synchronized(mPackages) { 11843 oldPackage = mPackages.get(pkgName); 11844 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11845 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11846 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11847 if(!checkUpgradeKeySetLP(ps, pkg)) { 11848 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11849 "New package not signed by keys specified by upgrade-keysets: " 11850 + pkgName); 11851 return; 11852 } 11853 } else { 11854 // default to original signature matching 11855 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11856 != PackageManager.SIGNATURE_MATCH) { 11857 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11858 "New package has a different signature: " + pkgName); 11859 return; 11860 } 11861 } 11862 11863 // In case of rollback, remember per-user/profile install state 11864 allUsers = sUserManager.getUserIds(); 11865 perUserInstalled = new boolean[allUsers.length]; 11866 for (int i = 0; i < allUsers.length; i++) { 11867 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11868 } 11869 } 11870 11871 boolean sysPkg = (isSystemApp(oldPackage)); 11872 if (sysPkg) { 11873 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11874 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11875 } else { 11876 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11877 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11878 } 11879 } 11880 11881 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11882 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11883 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11884 String volumeUuid, PackageInstalledInfo res) { 11885 String pkgName = deletedPackage.packageName; 11886 boolean deletedPkg = true; 11887 boolean updatedSettings = false; 11888 11889 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11890 + deletedPackage); 11891 long origUpdateTime; 11892 if (pkg.mExtras != null) { 11893 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11894 } else { 11895 origUpdateTime = 0; 11896 } 11897 11898 // First delete the existing package while retaining the data directory 11899 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11900 res.removedInfo, true)) { 11901 // If the existing package wasn't successfully deleted 11902 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11903 deletedPkg = false; 11904 } else { 11905 // Successfully deleted the old package; proceed with replace. 11906 11907 // If deleted package lived in a container, give users a chance to 11908 // relinquish resources before killing. 11909 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11910 if (DEBUG_INSTALL) { 11911 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11912 } 11913 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11914 final ArrayList<String> pkgList = new ArrayList<String>(1); 11915 pkgList.add(deletedPackage.applicationInfo.packageName); 11916 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11917 } 11918 11919 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11920 try { 11921 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 11922 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11923 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11924 perUserInstalled, res, user); 11925 updatedSettings = true; 11926 } catch (PackageManagerException e) { 11927 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11928 } 11929 } 11930 11931 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11932 // remove package from internal structures. Note that we want deletePackageX to 11933 // delete the package data and cache directories that it created in 11934 // scanPackageLocked, unless those directories existed before we even tried to 11935 // install. 11936 if(updatedSettings) { 11937 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11938 deletePackageLI( 11939 pkgName, null, true, allUsers, perUserInstalled, 11940 PackageManager.DELETE_KEEP_DATA, 11941 res.removedInfo, true); 11942 } 11943 // Since we failed to install the new package we need to restore the old 11944 // package that we deleted. 11945 if (deletedPkg) { 11946 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11947 File restoreFile = new File(deletedPackage.codePath); 11948 // Parse old package 11949 boolean oldExternal = isExternal(deletedPackage); 11950 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11951 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11952 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11953 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11954 try { 11955 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 11956 null); 11957 } catch (PackageManagerException e) { 11958 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11959 + e.getMessage()); 11960 return; 11961 } 11962 // Restore of old package succeeded. Update permissions. 11963 // writer 11964 synchronized (mPackages) { 11965 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11966 UPDATE_PERMISSIONS_ALL); 11967 // can downgrade to reader 11968 mSettings.writeLPr(); 11969 } 11970 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11971 } 11972 } 11973 } 11974 11975 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11976 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11977 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11978 String volumeUuid, PackageInstalledInfo res) { 11979 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11980 + ", old=" + deletedPackage); 11981 boolean disabledSystem = false; 11982 boolean updatedSettings = false; 11983 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11984 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11985 != 0) { 11986 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11987 } 11988 String packageName = deletedPackage.packageName; 11989 if (packageName == null) { 11990 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11991 "Attempt to delete null packageName."); 11992 return; 11993 } 11994 PackageParser.Package oldPkg; 11995 PackageSetting oldPkgSetting; 11996 // reader 11997 synchronized (mPackages) { 11998 oldPkg = mPackages.get(packageName); 11999 oldPkgSetting = mSettings.mPackages.get(packageName); 12000 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12001 (oldPkgSetting == null)) { 12002 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12003 "Couldn't find package:" + packageName + " information"); 12004 return; 12005 } 12006 } 12007 12008 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12009 12010 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12011 res.removedInfo.removedPackage = packageName; 12012 // Remove existing system package 12013 removePackageLI(oldPkgSetting, true); 12014 // writer 12015 synchronized (mPackages) { 12016 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12017 if (!disabledSystem && deletedPackage != null) { 12018 // We didn't need to disable the .apk as a current system package, 12019 // which means we are replacing another update that is already 12020 // installed. We need to make sure to delete the older one's .apk. 12021 res.removedInfo.args = createInstallArgsForExisting(0, 12022 deletedPackage.applicationInfo.getCodePath(), 12023 deletedPackage.applicationInfo.getResourcePath(), 12024 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12025 } else { 12026 res.removedInfo.args = null; 12027 } 12028 } 12029 12030 // Successfully disabled the old package. Now proceed with re-installation 12031 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12032 12033 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12034 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12035 12036 PackageParser.Package newPackage = null; 12037 try { 12038 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12039 if (newPackage.mExtras != null) { 12040 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12041 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12042 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12043 12044 // is the update attempting to change shared user? that isn't going to work... 12045 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12046 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12047 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12048 + " to " + newPkgSetting.sharedUser); 12049 updatedSettings = true; 12050 } 12051 } 12052 12053 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12054 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12055 perUserInstalled, res, user); 12056 updatedSettings = true; 12057 } 12058 12059 } catch (PackageManagerException e) { 12060 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12061 } 12062 12063 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12064 // Re installation failed. Restore old information 12065 // Remove new pkg information 12066 if (newPackage != null) { 12067 removeInstalledPackageLI(newPackage, true); 12068 } 12069 // Add back the old system package 12070 try { 12071 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12072 } catch (PackageManagerException e) { 12073 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12074 } 12075 // Restore the old system information in Settings 12076 synchronized (mPackages) { 12077 if (disabledSystem) { 12078 mSettings.enableSystemPackageLPw(packageName); 12079 } 12080 if (updatedSettings) { 12081 mSettings.setInstallerPackageName(packageName, 12082 oldPkgSetting.installerPackageName); 12083 } 12084 mSettings.writeLPr(); 12085 } 12086 } 12087 } 12088 12089 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12090 // Collect all used permissions in the UID 12091 ArraySet<String> usedPermissions = new ArraySet<>(); 12092 final int packageCount = su.packages.size(); 12093 for (int i = 0; i < packageCount; i++) { 12094 PackageSetting ps = su.packages.valueAt(i); 12095 if (ps.pkg == null) { 12096 continue; 12097 } 12098 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12099 for (int j = 0; j < requestedPermCount; j++) { 12100 String permission = ps.pkg.requestedPermissions.get(j); 12101 BasePermission bp = mSettings.mPermissions.get(permission); 12102 if (bp != null) { 12103 usedPermissions.add(permission); 12104 } 12105 } 12106 } 12107 12108 PermissionsState permissionsState = su.getPermissionsState(); 12109 // Prune install permissions 12110 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12111 final int installPermCount = installPermStates.size(); 12112 for (int i = installPermCount - 1; i >= 0; i--) { 12113 PermissionState permissionState = installPermStates.get(i); 12114 if (!usedPermissions.contains(permissionState.getName())) { 12115 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12116 if (bp != null) { 12117 permissionsState.revokeInstallPermission(bp); 12118 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12119 PackageManager.MASK_PERMISSION_FLAGS, 0); 12120 } 12121 } 12122 } 12123 12124 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12125 12126 // Prune runtime permissions 12127 for (int userId : allUserIds) { 12128 List<PermissionState> runtimePermStates = permissionsState 12129 .getRuntimePermissionStates(userId); 12130 final int runtimePermCount = runtimePermStates.size(); 12131 for (int i = runtimePermCount - 1; i >= 0; i--) { 12132 PermissionState permissionState = runtimePermStates.get(i); 12133 if (!usedPermissions.contains(permissionState.getName())) { 12134 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12135 if (bp != null) { 12136 permissionsState.revokeRuntimePermission(bp, userId); 12137 permissionsState.updatePermissionFlags(bp, userId, 12138 PackageManager.MASK_PERMISSION_FLAGS, 0); 12139 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12140 runtimePermissionChangedUserIds, userId); 12141 } 12142 } 12143 } 12144 } 12145 12146 return runtimePermissionChangedUserIds; 12147 } 12148 12149 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12150 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12151 UserHandle user) { 12152 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12153 12154 String pkgName = newPackage.packageName; 12155 synchronized (mPackages) { 12156 //write settings. the installStatus will be incomplete at this stage. 12157 //note that the new package setting would have already been 12158 //added to mPackages. It hasn't been persisted yet. 12159 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12160 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12161 mSettings.writeLPr(); 12162 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12163 } 12164 12165 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12166 synchronized (mPackages) { 12167 updatePermissionsLPw(newPackage.packageName, newPackage, 12168 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12169 ? UPDATE_PERMISSIONS_ALL : 0)); 12170 // For system-bundled packages, we assume that installing an upgraded version 12171 // of the package implies that the user actually wants to run that new code, 12172 // so we enable the package. 12173 PackageSetting ps = mSettings.mPackages.get(pkgName); 12174 if (ps != null) { 12175 if (isSystemApp(newPackage)) { 12176 // NB: implicit assumption that system package upgrades apply to all users 12177 if (DEBUG_INSTALL) { 12178 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12179 } 12180 if (res.origUsers != null) { 12181 for (int userHandle : res.origUsers) { 12182 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12183 userHandle, installerPackageName); 12184 } 12185 } 12186 // Also convey the prior install/uninstall state 12187 if (allUsers != null && perUserInstalled != null) { 12188 for (int i = 0; i < allUsers.length; i++) { 12189 if (DEBUG_INSTALL) { 12190 Slog.d(TAG, " user " + allUsers[i] 12191 + " => " + perUserInstalled[i]); 12192 } 12193 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12194 } 12195 // these install state changes will be persisted in the 12196 // upcoming call to mSettings.writeLPr(). 12197 } 12198 } 12199 // It's implied that when a user requests installation, they want the app to be 12200 // installed and enabled. 12201 int userId = user.getIdentifier(); 12202 if (userId != UserHandle.USER_ALL) { 12203 ps.setInstalled(true, userId); 12204 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12205 } 12206 } 12207 res.name = pkgName; 12208 res.uid = newPackage.applicationInfo.uid; 12209 res.pkg = newPackage; 12210 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12211 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12212 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12213 //to update install status 12214 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12215 mSettings.writeLPr(); 12216 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12217 } 12218 12219 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12220 } 12221 12222 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12223 try { 12224 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12225 installPackageLI(args, res); 12226 } finally { 12227 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12228 } 12229 } 12230 12231 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12232 final int installFlags = args.installFlags; 12233 final String installerPackageName = args.installerPackageName; 12234 final String volumeUuid = args.volumeUuid; 12235 final File tmpPackageFile = new File(args.getCodePath()); 12236 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12237 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12238 || (args.volumeUuid != null)); 12239 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12240 boolean replace = false; 12241 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12242 if (args.move != null) { 12243 // moving a complete application; perfom an initial scan on the new install location 12244 scanFlags |= SCAN_INITIAL; 12245 } 12246 // Result object to be returned 12247 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12248 12249 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12250 12251 // Retrieve PackageSettings and parse package 12252 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12253 | PackageParser.PARSE_ENFORCE_CODE 12254 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12255 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12256 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12257 PackageParser pp = new PackageParser(); 12258 pp.setSeparateProcesses(mSeparateProcesses); 12259 pp.setDisplayMetrics(mMetrics); 12260 12261 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12262 final PackageParser.Package pkg; 12263 try { 12264 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12265 } catch (PackageParserException e) { 12266 res.setError("Failed parse during installPackageLI", e); 12267 return; 12268 } finally { 12269 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12270 } 12271 12272 // Mark that we have an install time CPU ABI override. 12273 pkg.cpuAbiOverride = args.abiOverride; 12274 12275 String pkgName = res.name = pkg.packageName; 12276 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12277 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12278 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12279 return; 12280 } 12281 } 12282 12283 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12284 try { 12285 pp.collectCertificates(pkg, parseFlags); 12286 } catch (PackageParserException e) { 12287 res.setError("Failed collect during installPackageLI", e); 12288 return; 12289 } finally { 12290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12291 } 12292 12293 /* If the installer passed in a manifest digest, compare it now. */ 12294 if (args.manifestDigest != null) { 12295 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12296 try { 12297 pp.collectManifestDigest(pkg); 12298 } catch (PackageParserException e) { 12299 res.setError("Failed collect during installPackageLI", e); 12300 return; 12301 } finally { 12302 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12303 } 12304 12305 if (DEBUG_INSTALL) { 12306 final String parsedManifest = pkg.manifestDigest == null ? "null" 12307 : pkg.manifestDigest.toString(); 12308 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12309 + parsedManifest); 12310 } 12311 12312 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12313 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12314 return; 12315 } 12316 } else if (DEBUG_INSTALL) { 12317 final String parsedManifest = pkg.manifestDigest == null 12318 ? "null" : pkg.manifestDigest.toString(); 12319 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12320 } 12321 12322 // Get rid of all references to package scan path via parser. 12323 pp = null; 12324 String oldCodePath = null; 12325 boolean systemApp = false; 12326 synchronized (mPackages) { 12327 // Check if installing already existing package 12328 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12329 String oldName = mSettings.mRenamedPackages.get(pkgName); 12330 if (pkg.mOriginalPackages != null 12331 && pkg.mOriginalPackages.contains(oldName) 12332 && mPackages.containsKey(oldName)) { 12333 // This package is derived from an original package, 12334 // and this device has been updating from that original 12335 // name. We must continue using the original name, so 12336 // rename the new package here. 12337 pkg.setPackageName(oldName); 12338 pkgName = pkg.packageName; 12339 replace = true; 12340 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12341 + oldName + " pkgName=" + pkgName); 12342 } else if (mPackages.containsKey(pkgName)) { 12343 // This package, under its official name, already exists 12344 // on the device; we should replace it. 12345 replace = true; 12346 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12347 } 12348 12349 // Prevent apps opting out from runtime permissions 12350 if (replace) { 12351 PackageParser.Package oldPackage = mPackages.get(pkgName); 12352 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12353 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12354 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12355 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12356 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12357 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12358 + " doesn't support runtime permissions but the old" 12359 + " target SDK " + oldTargetSdk + " does."); 12360 return; 12361 } 12362 } 12363 } 12364 12365 PackageSetting ps = mSettings.mPackages.get(pkgName); 12366 if (ps != null) { 12367 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12368 12369 // Quick sanity check that we're signed correctly if updating; 12370 // we'll check this again later when scanning, but we want to 12371 // bail early here before tripping over redefined permissions. 12372 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12373 if (!checkUpgradeKeySetLP(ps, pkg)) { 12374 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12375 + pkg.packageName + " upgrade keys do not match the " 12376 + "previously installed version"); 12377 return; 12378 } 12379 } else { 12380 try { 12381 verifySignaturesLP(ps, pkg); 12382 } catch (PackageManagerException e) { 12383 res.setError(e.error, e.getMessage()); 12384 return; 12385 } 12386 } 12387 12388 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12389 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12390 systemApp = (ps.pkg.applicationInfo.flags & 12391 ApplicationInfo.FLAG_SYSTEM) != 0; 12392 } 12393 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12394 } 12395 12396 // Check whether the newly-scanned package wants to define an already-defined perm 12397 int N = pkg.permissions.size(); 12398 for (int i = N-1; i >= 0; i--) { 12399 PackageParser.Permission perm = pkg.permissions.get(i); 12400 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12401 if (bp != null) { 12402 // If the defining package is signed with our cert, it's okay. This 12403 // also includes the "updating the same package" case, of course. 12404 // "updating same package" could also involve key-rotation. 12405 final boolean sigsOk; 12406 if (bp.sourcePackage.equals(pkg.packageName) 12407 && (bp.packageSetting instanceof PackageSetting) 12408 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12409 scanFlags))) { 12410 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12411 } else { 12412 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12413 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12414 } 12415 if (!sigsOk) { 12416 // If the owning package is the system itself, we log but allow 12417 // install to proceed; we fail the install on all other permission 12418 // redefinitions. 12419 if (!bp.sourcePackage.equals("android")) { 12420 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12421 + pkg.packageName + " attempting to redeclare permission " 12422 + perm.info.name + " already owned by " + bp.sourcePackage); 12423 res.origPermission = perm.info.name; 12424 res.origPackage = bp.sourcePackage; 12425 return; 12426 } else { 12427 Slog.w(TAG, "Package " + pkg.packageName 12428 + " attempting to redeclare system permission " 12429 + perm.info.name + "; ignoring new declaration"); 12430 pkg.permissions.remove(i); 12431 } 12432 } 12433 } 12434 } 12435 12436 } 12437 12438 if (systemApp && onExternal) { 12439 // Disable updates to system apps on sdcard 12440 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12441 "Cannot install updates to system apps on sdcard"); 12442 return; 12443 } 12444 12445 if (args.move != null) { 12446 // We did an in-place move, so dex is ready to roll 12447 scanFlags |= SCAN_NO_DEX; 12448 scanFlags |= SCAN_MOVE; 12449 12450 synchronized (mPackages) { 12451 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12452 if (ps == null) { 12453 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12454 "Missing settings for moved package " + pkgName); 12455 } 12456 12457 // We moved the entire application as-is, so bring over the 12458 // previously derived ABI information. 12459 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12460 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12461 } 12462 12463 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12464 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12465 scanFlags |= SCAN_NO_DEX; 12466 12467 try { 12468 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12469 true /* extract libs */); 12470 } catch (PackageManagerException pme) { 12471 Slog.e(TAG, "Error deriving application ABI", pme); 12472 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12473 return; 12474 } 12475 } 12476 12477 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12478 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12479 return; 12480 } 12481 12482 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12483 12484 if (replace) { 12485 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12486 installerPackageName, volumeUuid, res); 12487 } else { 12488 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12489 args.user, installerPackageName, volumeUuid, res); 12490 } 12491 synchronized (mPackages) { 12492 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12493 if (ps != null) { 12494 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12495 } 12496 } 12497 } 12498 12499 private void startIntentFilterVerifications(int userId, boolean replacing, 12500 PackageParser.Package pkg) { 12501 if (mIntentFilterVerifierComponent == null) { 12502 Slog.w(TAG, "No IntentFilter verification will not be done as " 12503 + "there is no IntentFilterVerifier available!"); 12504 return; 12505 } 12506 12507 final int verifierUid = getPackageUid( 12508 mIntentFilterVerifierComponent.getPackageName(), 12509 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12510 12511 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12512 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12513 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12514 mHandler.sendMessage(msg); 12515 } 12516 12517 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12518 PackageParser.Package pkg) { 12519 int size = pkg.activities.size(); 12520 if (size == 0) { 12521 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12522 "No activity, so no need to verify any IntentFilter!"); 12523 return; 12524 } 12525 12526 final boolean hasDomainURLs = hasDomainURLs(pkg); 12527 if (!hasDomainURLs) { 12528 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12529 "No domain URLs, so no need to verify any IntentFilter!"); 12530 return; 12531 } 12532 12533 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12534 + " if any IntentFilter from the " + size 12535 + " Activities needs verification ..."); 12536 12537 int count = 0; 12538 final String packageName = pkg.packageName; 12539 12540 synchronized (mPackages) { 12541 // If this is a new install and we see that we've already run verification for this 12542 // package, we have nothing to do: it means the state was restored from backup. 12543 if (!replacing) { 12544 IntentFilterVerificationInfo ivi = 12545 mSettings.getIntentFilterVerificationLPr(packageName); 12546 if (ivi != null) { 12547 if (DEBUG_DOMAIN_VERIFICATION) { 12548 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12549 + ivi.getStatusString()); 12550 } 12551 return; 12552 } 12553 } 12554 12555 // If any filters need to be verified, then all need to be. 12556 boolean needToVerify = false; 12557 for (PackageParser.Activity a : pkg.activities) { 12558 for (ActivityIntentInfo filter : a.intents) { 12559 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12560 if (DEBUG_DOMAIN_VERIFICATION) { 12561 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12562 } 12563 needToVerify = true; 12564 break; 12565 } 12566 } 12567 } 12568 12569 if (needToVerify) { 12570 final int verificationId = mIntentFilterVerificationToken++; 12571 for (PackageParser.Activity a : pkg.activities) { 12572 for (ActivityIntentInfo filter : a.intents) { 12573 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12574 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12575 "Verification needed for IntentFilter:" + filter.toString()); 12576 mIntentFilterVerifier.addOneIntentFilterVerification( 12577 verifierUid, userId, verificationId, filter, packageName); 12578 count++; 12579 } 12580 } 12581 } 12582 } 12583 } 12584 12585 if (count > 0) { 12586 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12587 + " IntentFilter verification" + (count > 1 ? "s" : "") 12588 + " for userId:" + userId); 12589 mIntentFilterVerifier.startVerifications(userId); 12590 } else { 12591 if (DEBUG_DOMAIN_VERIFICATION) { 12592 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12593 } 12594 } 12595 } 12596 12597 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12598 final ComponentName cn = filter.activity.getComponentName(); 12599 final String packageName = cn.getPackageName(); 12600 12601 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12602 packageName); 12603 if (ivi == null) { 12604 return true; 12605 } 12606 int status = ivi.getStatus(); 12607 switch (status) { 12608 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12609 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12610 return true; 12611 12612 default: 12613 // Nothing to do 12614 return false; 12615 } 12616 } 12617 12618 private static boolean isMultiArch(PackageSetting ps) { 12619 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12620 } 12621 12622 private static boolean isMultiArch(ApplicationInfo info) { 12623 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12624 } 12625 12626 private static boolean isExternal(PackageParser.Package pkg) { 12627 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12628 } 12629 12630 private static boolean isExternal(PackageSetting ps) { 12631 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12632 } 12633 12634 private static boolean isExternal(ApplicationInfo info) { 12635 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12636 } 12637 12638 private static boolean isSystemApp(PackageParser.Package pkg) { 12639 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12640 } 12641 12642 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12643 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12644 } 12645 12646 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12647 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12648 } 12649 12650 private static boolean isSystemApp(PackageSetting ps) { 12651 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12652 } 12653 12654 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12655 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12656 } 12657 12658 private int packageFlagsToInstallFlags(PackageSetting ps) { 12659 int installFlags = 0; 12660 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12661 // This existing package was an external ASEC install when we have 12662 // the external flag without a UUID 12663 installFlags |= PackageManager.INSTALL_EXTERNAL; 12664 } 12665 if (ps.isForwardLocked()) { 12666 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12667 } 12668 return installFlags; 12669 } 12670 12671 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12672 if (isExternal(pkg)) { 12673 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12674 return StorageManager.UUID_PRIMARY_PHYSICAL; 12675 } else { 12676 return pkg.volumeUuid; 12677 } 12678 } else { 12679 return StorageManager.UUID_PRIVATE_INTERNAL; 12680 } 12681 } 12682 12683 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12684 if (isExternal(pkg)) { 12685 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12686 return mSettings.getExternalVersion(); 12687 } else { 12688 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12689 } 12690 } else { 12691 return mSettings.getInternalVersion(); 12692 } 12693 } 12694 12695 private void deleteTempPackageFiles() { 12696 final FilenameFilter filter = new FilenameFilter() { 12697 public boolean accept(File dir, String name) { 12698 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12699 } 12700 }; 12701 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12702 file.delete(); 12703 } 12704 } 12705 12706 @Override 12707 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12708 int flags) { 12709 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12710 flags); 12711 } 12712 12713 @Override 12714 public void deletePackage(final String packageName, 12715 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12716 mContext.enforceCallingOrSelfPermission( 12717 android.Manifest.permission.DELETE_PACKAGES, null); 12718 Preconditions.checkNotNull(packageName); 12719 Preconditions.checkNotNull(observer); 12720 final int uid = Binder.getCallingUid(); 12721 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12722 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12723 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12724 mContext.enforceCallingPermission( 12725 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12726 "deletePackage for user " + userId); 12727 } 12728 12729 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12730 try { 12731 observer.onPackageDeleted(packageName, 12732 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12733 } catch (RemoteException re) { 12734 } 12735 return; 12736 } 12737 12738 for (int currentUserId : users) { 12739 if (getBlockUninstallForUser(packageName, currentUserId)) { 12740 try { 12741 observer.onPackageDeleted(packageName, 12742 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 12743 } catch (RemoteException re) { 12744 } 12745 return; 12746 } 12747 } 12748 12749 if (DEBUG_REMOVE) { 12750 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12751 } 12752 // Queue up an async operation since the package deletion may take a little while. 12753 mHandler.post(new Runnable() { 12754 public void run() { 12755 mHandler.removeCallbacks(this); 12756 final int returnCode = deletePackageX(packageName, userId, flags); 12757 try { 12758 observer.onPackageDeleted(packageName, returnCode, null); 12759 } catch (RemoteException e) { 12760 Log.i(TAG, "Observer no longer exists."); 12761 } //end catch 12762 } //end run 12763 }); 12764 } 12765 12766 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12767 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12768 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12769 try { 12770 if (dpm != null) { 12771 // Does the package contains the device owner? 12772 if (dpm.isDeviceOwnerPackage(packageName)) { 12773 return true; 12774 } 12775 // Does it contain a device admin for any user? 12776 int[] users; 12777 if (userId == UserHandle.USER_ALL) { 12778 users = sUserManager.getUserIds(); 12779 } else { 12780 users = new int[]{userId}; 12781 } 12782 for (int i = 0; i < users.length; ++i) { 12783 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12784 return true; 12785 } 12786 } 12787 } 12788 } catch (RemoteException e) { 12789 } 12790 return false; 12791 } 12792 12793 /** 12794 * This method is an internal method that could be get invoked either 12795 * to delete an installed package or to clean up a failed installation. 12796 * After deleting an installed package, a broadcast is sent to notify any 12797 * listeners that the package has been installed. For cleaning up a failed 12798 * installation, the broadcast is not necessary since the package's 12799 * installation wouldn't have sent the initial broadcast either 12800 * The key steps in deleting a package are 12801 * deleting the package information in internal structures like mPackages, 12802 * deleting the packages base directories through installd 12803 * updating mSettings to reflect current status 12804 * persisting settings for later use 12805 * sending a broadcast if necessary 12806 */ 12807 private int deletePackageX(String packageName, int userId, int flags) { 12808 final PackageRemovedInfo info = new PackageRemovedInfo(); 12809 final boolean res; 12810 12811 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12812 ? UserHandle.ALL : new UserHandle(userId); 12813 12814 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12815 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12816 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12817 } 12818 12819 boolean removedForAllUsers = false; 12820 boolean systemUpdate = false; 12821 12822 // for the uninstall-updates case and restricted profiles, remember the per- 12823 // userhandle installed state 12824 int[] allUsers; 12825 boolean[] perUserInstalled; 12826 synchronized (mPackages) { 12827 PackageSetting ps = mSettings.mPackages.get(packageName); 12828 allUsers = sUserManager.getUserIds(); 12829 perUserInstalled = new boolean[allUsers.length]; 12830 for (int i = 0; i < allUsers.length; i++) { 12831 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12832 } 12833 } 12834 12835 synchronized (mInstallLock) { 12836 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12837 res = deletePackageLI(packageName, removeForUser, 12838 true, allUsers, perUserInstalled, 12839 flags | REMOVE_CHATTY, info, true); 12840 systemUpdate = info.isRemovedPackageSystemUpdate; 12841 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12842 removedForAllUsers = true; 12843 } 12844 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12845 + " removedForAllUsers=" + removedForAllUsers); 12846 } 12847 12848 if (res) { 12849 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12850 12851 // If the removed package was a system update, the old system package 12852 // was re-enabled; we need to broadcast this information 12853 if (systemUpdate) { 12854 Bundle extras = new Bundle(1); 12855 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12856 ? info.removedAppId : info.uid); 12857 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12858 12859 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12860 extras, null, null, null); 12861 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12862 extras, null, null, null); 12863 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12864 null, packageName, null, null); 12865 } 12866 } 12867 // Force a gc here. 12868 Runtime.getRuntime().gc(); 12869 // Delete the resources here after sending the broadcast to let 12870 // other processes clean up before deleting resources. 12871 if (info.args != null) { 12872 synchronized (mInstallLock) { 12873 info.args.doPostDeleteLI(true); 12874 } 12875 } 12876 12877 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12878 } 12879 12880 class PackageRemovedInfo { 12881 String removedPackage; 12882 int uid = -1; 12883 int removedAppId = -1; 12884 int[] removedUsers = null; 12885 boolean isRemovedPackageSystemUpdate = false; 12886 // Clean up resources deleted packages. 12887 InstallArgs args = null; 12888 12889 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12890 Bundle extras = new Bundle(1); 12891 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12892 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12893 if (replacing) { 12894 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12895 } 12896 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12897 if (removedPackage != null) { 12898 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12899 extras, null, null, removedUsers); 12900 if (fullRemove && !replacing) { 12901 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12902 extras, null, null, removedUsers); 12903 } 12904 } 12905 if (removedAppId >= 0) { 12906 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12907 removedUsers); 12908 } 12909 } 12910 } 12911 12912 /* 12913 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12914 * flag is not set, the data directory is removed as well. 12915 * make sure this flag is set for partially installed apps. If not its meaningless to 12916 * delete a partially installed application. 12917 */ 12918 private void removePackageDataLI(PackageSetting ps, 12919 int[] allUserHandles, boolean[] perUserInstalled, 12920 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12921 String packageName = ps.name; 12922 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12923 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12924 // Retrieve object to delete permissions for shared user later on 12925 final PackageSetting deletedPs; 12926 // reader 12927 synchronized (mPackages) { 12928 deletedPs = mSettings.mPackages.get(packageName); 12929 if (outInfo != null) { 12930 outInfo.removedPackage = packageName; 12931 outInfo.removedUsers = deletedPs != null 12932 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12933 : null; 12934 } 12935 } 12936 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12937 removeDataDirsLI(ps.volumeUuid, packageName); 12938 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12939 } 12940 // writer 12941 synchronized (mPackages) { 12942 if (deletedPs != null) { 12943 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12944 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12945 clearDefaultBrowserIfNeeded(packageName); 12946 if (outInfo != null) { 12947 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12948 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12949 } 12950 updatePermissionsLPw(deletedPs.name, null, 0); 12951 if (deletedPs.sharedUser != null) { 12952 // Remove permissions associated with package. Since runtime 12953 // permissions are per user we have to kill the removed package 12954 // or packages running under the shared user of the removed 12955 // package if revoking the permissions requested only by the removed 12956 // package is successful and this causes a change in gids. 12957 for (int userId : UserManagerService.getInstance().getUserIds()) { 12958 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12959 userId); 12960 if (userIdToKill == UserHandle.USER_ALL 12961 || userIdToKill >= UserHandle.USER_SYSTEM) { 12962 // If gids changed for this user, kill all affected packages. 12963 mHandler.post(new Runnable() { 12964 @Override 12965 public void run() { 12966 // This has to happen with no lock held. 12967 killApplication(deletedPs.name, deletedPs.appId, 12968 KILL_APP_REASON_GIDS_CHANGED); 12969 } 12970 }); 12971 break; 12972 } 12973 } 12974 } 12975 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12976 } 12977 // make sure to preserve per-user disabled state if this removal was just 12978 // a downgrade of a system app to the factory package 12979 if (allUserHandles != null && perUserInstalled != null) { 12980 if (DEBUG_REMOVE) { 12981 Slog.d(TAG, "Propagating install state across downgrade"); 12982 } 12983 for (int i = 0; i < allUserHandles.length; i++) { 12984 if (DEBUG_REMOVE) { 12985 Slog.d(TAG, " user " + allUserHandles[i] 12986 + " => " + perUserInstalled[i]); 12987 } 12988 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12989 } 12990 } 12991 } 12992 // can downgrade to reader 12993 if (writeSettings) { 12994 // Save settings now 12995 mSettings.writeLPr(); 12996 } 12997 } 12998 if (outInfo != null) { 12999 // A user ID was deleted here. Go through all users and remove it 13000 // from KeyStore. 13001 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13002 } 13003 } 13004 13005 static boolean locationIsPrivileged(File path) { 13006 try { 13007 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13008 .getCanonicalPath(); 13009 return path.getCanonicalPath().startsWith(privilegedAppDir); 13010 } catch (IOException e) { 13011 Slog.e(TAG, "Unable to access code path " + path); 13012 } 13013 return false; 13014 } 13015 13016 /* 13017 * Tries to delete system package. 13018 */ 13019 private boolean deleteSystemPackageLI(PackageSetting newPs, 13020 int[] allUserHandles, boolean[] perUserInstalled, 13021 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13022 final boolean applyUserRestrictions 13023 = (allUserHandles != null) && (perUserInstalled != null); 13024 PackageSetting disabledPs = null; 13025 // Confirm if the system package has been updated 13026 // An updated system app can be deleted. This will also have to restore 13027 // the system pkg from system partition 13028 // reader 13029 synchronized (mPackages) { 13030 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13031 } 13032 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13033 + " disabledPs=" + disabledPs); 13034 if (disabledPs == null) { 13035 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13036 return false; 13037 } else if (DEBUG_REMOVE) { 13038 Slog.d(TAG, "Deleting system pkg from data partition"); 13039 } 13040 if (DEBUG_REMOVE) { 13041 if (applyUserRestrictions) { 13042 Slog.d(TAG, "Remembering install states:"); 13043 for (int i = 0; i < allUserHandles.length; i++) { 13044 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13045 } 13046 } 13047 } 13048 // Delete the updated package 13049 outInfo.isRemovedPackageSystemUpdate = true; 13050 if (disabledPs.versionCode < newPs.versionCode) { 13051 // Delete data for downgrades 13052 flags &= ~PackageManager.DELETE_KEEP_DATA; 13053 } else { 13054 // Preserve data by setting flag 13055 flags |= PackageManager.DELETE_KEEP_DATA; 13056 } 13057 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13058 allUserHandles, perUserInstalled, outInfo, writeSettings); 13059 if (!ret) { 13060 return false; 13061 } 13062 // writer 13063 synchronized (mPackages) { 13064 // Reinstate the old system package 13065 mSettings.enableSystemPackageLPw(newPs.name); 13066 // Remove any native libraries from the upgraded package. 13067 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13068 } 13069 // Install the system package 13070 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13071 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13072 if (locationIsPrivileged(disabledPs.codePath)) { 13073 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13074 } 13075 13076 final PackageParser.Package newPkg; 13077 try { 13078 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13079 } catch (PackageManagerException e) { 13080 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13081 return false; 13082 } 13083 13084 // writer 13085 synchronized (mPackages) { 13086 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13087 13088 // Propagate the permissions state as we do not want to drop on the floor 13089 // runtime permissions. The update permissions method below will take 13090 // care of removing obsolete permissions and grant install permissions. 13091 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13092 updatePermissionsLPw(newPkg.packageName, newPkg, 13093 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13094 13095 if (applyUserRestrictions) { 13096 if (DEBUG_REMOVE) { 13097 Slog.d(TAG, "Propagating install state across reinstall"); 13098 } 13099 for (int i = 0; i < allUserHandles.length; i++) { 13100 if (DEBUG_REMOVE) { 13101 Slog.d(TAG, " user " + allUserHandles[i] 13102 + " => " + perUserInstalled[i]); 13103 } 13104 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13105 13106 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13107 } 13108 // Regardless of writeSettings we need to ensure that this restriction 13109 // state propagation is persisted 13110 mSettings.writeAllUsersPackageRestrictionsLPr(); 13111 } 13112 // can downgrade to reader here 13113 if (writeSettings) { 13114 mSettings.writeLPr(); 13115 } 13116 } 13117 return true; 13118 } 13119 13120 private boolean deleteInstalledPackageLI(PackageSetting ps, 13121 boolean deleteCodeAndResources, int flags, 13122 int[] allUserHandles, boolean[] perUserInstalled, 13123 PackageRemovedInfo outInfo, boolean writeSettings) { 13124 if (outInfo != null) { 13125 outInfo.uid = ps.appId; 13126 } 13127 13128 // Delete package data from internal structures and also remove data if flag is set 13129 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13130 13131 // Delete application code and resources 13132 if (deleteCodeAndResources && (outInfo != null)) { 13133 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13134 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13135 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13136 } 13137 return true; 13138 } 13139 13140 @Override 13141 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13142 int userId) { 13143 mContext.enforceCallingOrSelfPermission( 13144 android.Manifest.permission.DELETE_PACKAGES, null); 13145 synchronized (mPackages) { 13146 PackageSetting ps = mSettings.mPackages.get(packageName); 13147 if (ps == null) { 13148 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13149 return false; 13150 } 13151 if (!ps.getInstalled(userId)) { 13152 // Can't block uninstall for an app that is not installed or enabled. 13153 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13154 return false; 13155 } 13156 ps.setBlockUninstall(blockUninstall, userId); 13157 mSettings.writePackageRestrictionsLPr(userId); 13158 } 13159 return true; 13160 } 13161 13162 @Override 13163 public boolean getBlockUninstallForUser(String packageName, int userId) { 13164 synchronized (mPackages) { 13165 PackageSetting ps = mSettings.mPackages.get(packageName); 13166 if (ps == null) { 13167 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13168 return false; 13169 } 13170 return ps.getBlockUninstall(userId); 13171 } 13172 } 13173 13174 /* 13175 * This method handles package deletion in general 13176 */ 13177 private boolean deletePackageLI(String packageName, UserHandle user, 13178 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13179 int flags, PackageRemovedInfo outInfo, 13180 boolean writeSettings) { 13181 if (packageName == null) { 13182 Slog.w(TAG, "Attempt to delete null packageName."); 13183 return false; 13184 } 13185 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13186 PackageSetting ps; 13187 boolean dataOnly = false; 13188 int removeUser = -1; 13189 int appId = -1; 13190 synchronized (mPackages) { 13191 ps = mSettings.mPackages.get(packageName); 13192 if (ps == null) { 13193 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13194 return false; 13195 } 13196 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13197 && user.getIdentifier() != UserHandle.USER_ALL) { 13198 // The caller is asking that the package only be deleted for a single 13199 // user. To do this, we just mark its uninstalled state and delete 13200 // its data. If this is a system app, we only allow this to happen if 13201 // they have set the special DELETE_SYSTEM_APP which requests different 13202 // semantics than normal for uninstalling system apps. 13203 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13204 final int userId = user.getIdentifier(); 13205 ps.setUserState(userId, 13206 COMPONENT_ENABLED_STATE_DEFAULT, 13207 false, //installed 13208 true, //stopped 13209 true, //notLaunched 13210 false, //hidden 13211 null, null, null, 13212 false, // blockUninstall 13213 ps.readUserState(userId).domainVerificationStatus, 0); 13214 if (!isSystemApp(ps)) { 13215 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13216 // Other user still have this package installed, so all 13217 // we need to do is clear this user's data and save that 13218 // it is uninstalled. 13219 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13220 removeUser = user.getIdentifier(); 13221 appId = ps.appId; 13222 scheduleWritePackageRestrictionsLocked(removeUser); 13223 } else { 13224 // We need to set it back to 'installed' so the uninstall 13225 // broadcasts will be sent correctly. 13226 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13227 ps.setInstalled(true, user.getIdentifier()); 13228 } 13229 } else { 13230 // This is a system app, so we assume that the 13231 // other users still have this package installed, so all 13232 // we need to do is clear this user's data and save that 13233 // it is uninstalled. 13234 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13235 removeUser = user.getIdentifier(); 13236 appId = ps.appId; 13237 scheduleWritePackageRestrictionsLocked(removeUser); 13238 } 13239 } 13240 } 13241 13242 if (removeUser >= 0) { 13243 // From above, we determined that we are deleting this only 13244 // for a single user. Continue the work here. 13245 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13246 if (outInfo != null) { 13247 outInfo.removedPackage = packageName; 13248 outInfo.removedAppId = appId; 13249 outInfo.removedUsers = new int[] {removeUser}; 13250 } 13251 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13252 removeKeystoreDataIfNeeded(removeUser, appId); 13253 schedulePackageCleaning(packageName, removeUser, false); 13254 synchronized (mPackages) { 13255 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13256 scheduleWritePackageRestrictionsLocked(removeUser); 13257 } 13258 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13259 } 13260 return true; 13261 } 13262 13263 if (dataOnly) { 13264 // Delete application data first 13265 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13266 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13267 return true; 13268 } 13269 13270 boolean ret = false; 13271 if (isSystemApp(ps)) { 13272 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13273 // When an updated system application is deleted we delete the existing resources as well and 13274 // fall back to existing code in system partition 13275 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13276 flags, outInfo, writeSettings); 13277 } else { 13278 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13279 // Kill application pre-emptively especially for apps on sd. 13280 killApplication(packageName, ps.appId, "uninstall pkg"); 13281 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13282 allUserHandles, perUserInstalled, 13283 outInfo, writeSettings); 13284 } 13285 13286 return ret; 13287 } 13288 13289 private final class ClearStorageConnection implements ServiceConnection { 13290 IMediaContainerService mContainerService; 13291 13292 @Override 13293 public void onServiceConnected(ComponentName name, IBinder service) { 13294 synchronized (this) { 13295 mContainerService = IMediaContainerService.Stub.asInterface(service); 13296 notifyAll(); 13297 } 13298 } 13299 13300 @Override 13301 public void onServiceDisconnected(ComponentName name) { 13302 } 13303 } 13304 13305 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13306 final boolean mounted; 13307 if (Environment.isExternalStorageEmulated()) { 13308 mounted = true; 13309 } else { 13310 final String status = Environment.getExternalStorageState(); 13311 13312 mounted = status.equals(Environment.MEDIA_MOUNTED) 13313 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13314 } 13315 13316 if (!mounted) { 13317 return; 13318 } 13319 13320 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13321 int[] users; 13322 if (userId == UserHandle.USER_ALL) { 13323 users = sUserManager.getUserIds(); 13324 } else { 13325 users = new int[] { userId }; 13326 } 13327 final ClearStorageConnection conn = new ClearStorageConnection(); 13328 if (mContext.bindServiceAsUser( 13329 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13330 try { 13331 for (int curUser : users) { 13332 long timeout = SystemClock.uptimeMillis() + 5000; 13333 synchronized (conn) { 13334 long now = SystemClock.uptimeMillis(); 13335 while (conn.mContainerService == null && now < timeout) { 13336 try { 13337 conn.wait(timeout - now); 13338 } catch (InterruptedException e) { 13339 } 13340 } 13341 } 13342 if (conn.mContainerService == null) { 13343 return; 13344 } 13345 13346 final UserEnvironment userEnv = new UserEnvironment(curUser); 13347 clearDirectory(conn.mContainerService, 13348 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13349 if (allData) { 13350 clearDirectory(conn.mContainerService, 13351 userEnv.buildExternalStorageAppDataDirs(packageName)); 13352 clearDirectory(conn.mContainerService, 13353 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13354 } 13355 } 13356 } finally { 13357 mContext.unbindService(conn); 13358 } 13359 } 13360 } 13361 13362 @Override 13363 public void clearApplicationUserData(final String packageName, 13364 final IPackageDataObserver observer, final int userId) { 13365 mContext.enforceCallingOrSelfPermission( 13366 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13367 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13368 // Queue up an async operation since the package deletion may take a little while. 13369 mHandler.post(new Runnable() { 13370 public void run() { 13371 mHandler.removeCallbacks(this); 13372 final boolean succeeded; 13373 synchronized (mInstallLock) { 13374 succeeded = clearApplicationUserDataLI(packageName, userId); 13375 } 13376 clearExternalStorageDataSync(packageName, userId, true); 13377 if (succeeded) { 13378 // invoke DeviceStorageMonitor's update method to clear any notifications 13379 DeviceStorageMonitorInternal 13380 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13381 if (dsm != null) { 13382 dsm.checkMemory(); 13383 } 13384 } 13385 if(observer != null) { 13386 try { 13387 observer.onRemoveCompleted(packageName, succeeded); 13388 } catch (RemoteException e) { 13389 Log.i(TAG, "Observer no longer exists."); 13390 } 13391 } //end if observer 13392 } //end run 13393 }); 13394 } 13395 13396 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13397 if (packageName == null) { 13398 Slog.w(TAG, "Attempt to delete null packageName."); 13399 return false; 13400 } 13401 13402 // Try finding details about the requested package 13403 PackageParser.Package pkg; 13404 synchronized (mPackages) { 13405 pkg = mPackages.get(packageName); 13406 if (pkg == null) { 13407 final PackageSetting ps = mSettings.mPackages.get(packageName); 13408 if (ps != null) { 13409 pkg = ps.pkg; 13410 } 13411 } 13412 13413 if (pkg == null) { 13414 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13415 return false; 13416 } 13417 13418 PackageSetting ps = (PackageSetting) pkg.mExtras; 13419 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13420 } 13421 13422 // Always delete data directories for package, even if we found no other 13423 // record of app. This helps users recover from UID mismatches without 13424 // resorting to a full data wipe. 13425 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13426 if (retCode < 0) { 13427 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13428 return false; 13429 } 13430 13431 final int appId = pkg.applicationInfo.uid; 13432 removeKeystoreDataIfNeeded(userId, appId); 13433 13434 // Create a native library symlink only if we have native libraries 13435 // and if the native libraries are 32 bit libraries. We do not provide 13436 // this symlink for 64 bit libraries. 13437 if (pkg.applicationInfo.primaryCpuAbi != null && 13438 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13439 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13440 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13441 nativeLibPath, userId) < 0) { 13442 Slog.w(TAG, "Failed linking native library dir"); 13443 return false; 13444 } 13445 } 13446 13447 return true; 13448 } 13449 13450 /** 13451 * Reverts user permission state changes (permissions and flags) in 13452 * all packages for a given user. 13453 * 13454 * @param userId The device user for which to do a reset. 13455 */ 13456 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13457 final int packageCount = mPackages.size(); 13458 for (int i = 0; i < packageCount; i++) { 13459 PackageParser.Package pkg = mPackages.valueAt(i); 13460 PackageSetting ps = (PackageSetting) pkg.mExtras; 13461 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13462 } 13463 } 13464 13465 /** 13466 * Reverts user permission state changes (permissions and flags). 13467 * 13468 * @param ps The package for which to reset. 13469 * @param userId The device user for which to do a reset. 13470 */ 13471 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13472 final PackageSetting ps, final int userId) { 13473 if (ps.pkg == null) { 13474 return; 13475 } 13476 13477 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13478 | FLAG_PERMISSION_USER_FIXED 13479 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13480 13481 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13482 | FLAG_PERMISSION_POLICY_FIXED; 13483 13484 boolean writeInstallPermissions = false; 13485 boolean writeRuntimePermissions = false; 13486 13487 final int permissionCount = ps.pkg.requestedPermissions.size(); 13488 for (int i = 0; i < permissionCount; i++) { 13489 String permission = ps.pkg.requestedPermissions.get(i); 13490 13491 BasePermission bp = mSettings.mPermissions.get(permission); 13492 if (bp == null) { 13493 continue; 13494 } 13495 13496 // If shared user we just reset the state to which only this app contributed. 13497 if (ps.sharedUser != null) { 13498 boolean used = false; 13499 final int packageCount = ps.sharedUser.packages.size(); 13500 for (int j = 0; j < packageCount; j++) { 13501 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13502 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13503 && pkg.pkg.requestedPermissions.contains(permission)) { 13504 used = true; 13505 break; 13506 } 13507 } 13508 if (used) { 13509 continue; 13510 } 13511 } 13512 13513 PermissionsState permissionsState = ps.getPermissionsState(); 13514 13515 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13516 13517 // Always clear the user settable flags. 13518 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13519 bp.name) != null; 13520 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13521 if (hasInstallState) { 13522 writeInstallPermissions = true; 13523 } else { 13524 writeRuntimePermissions = true; 13525 } 13526 } 13527 13528 // Below is only runtime permission handling. 13529 if (!bp.isRuntime()) { 13530 continue; 13531 } 13532 13533 // Never clobber system or policy. 13534 if ((oldFlags & policyOrSystemFlags) != 0) { 13535 continue; 13536 } 13537 13538 // If this permission was granted by default, make sure it is. 13539 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13540 if (permissionsState.grantRuntimePermission(bp, userId) 13541 != PERMISSION_OPERATION_FAILURE) { 13542 writeRuntimePermissions = true; 13543 } 13544 } else { 13545 // Otherwise, reset the permission. 13546 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13547 switch (revokeResult) { 13548 case PERMISSION_OPERATION_SUCCESS: { 13549 writeRuntimePermissions = true; 13550 } break; 13551 13552 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13553 writeRuntimePermissions = true; 13554 final int appId = ps.appId; 13555 mHandler.post(new Runnable() { 13556 @Override 13557 public void run() { 13558 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13559 } 13560 }); 13561 } break; 13562 } 13563 } 13564 } 13565 13566 // Synchronously write as we are taking permissions away. 13567 if (writeRuntimePermissions) { 13568 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13569 } 13570 13571 // Synchronously write as we are taking permissions away. 13572 if (writeInstallPermissions) { 13573 mSettings.writeLPr(); 13574 } 13575 } 13576 13577 /** 13578 * Remove entries from the keystore daemon. Will only remove it if the 13579 * {@code appId} is valid. 13580 */ 13581 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13582 if (appId < 0) { 13583 return; 13584 } 13585 13586 final KeyStore keyStore = KeyStore.getInstance(); 13587 if (keyStore != null) { 13588 if (userId == UserHandle.USER_ALL) { 13589 for (final int individual : sUserManager.getUserIds()) { 13590 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13591 } 13592 } else { 13593 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13594 } 13595 } else { 13596 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13597 } 13598 } 13599 13600 @Override 13601 public void deleteApplicationCacheFiles(final String packageName, 13602 final IPackageDataObserver observer) { 13603 mContext.enforceCallingOrSelfPermission( 13604 android.Manifest.permission.DELETE_CACHE_FILES, null); 13605 // Queue up an async operation since the package deletion may take a little while. 13606 final int userId = UserHandle.getCallingUserId(); 13607 mHandler.post(new Runnable() { 13608 public void run() { 13609 mHandler.removeCallbacks(this); 13610 final boolean succeded; 13611 synchronized (mInstallLock) { 13612 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13613 } 13614 clearExternalStorageDataSync(packageName, userId, false); 13615 if (observer != null) { 13616 try { 13617 observer.onRemoveCompleted(packageName, succeded); 13618 } catch (RemoteException e) { 13619 Log.i(TAG, "Observer no longer exists."); 13620 } 13621 } //end if observer 13622 } //end run 13623 }); 13624 } 13625 13626 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13627 if (packageName == null) { 13628 Slog.w(TAG, "Attempt to delete null packageName."); 13629 return false; 13630 } 13631 PackageParser.Package p; 13632 synchronized (mPackages) { 13633 p = mPackages.get(packageName); 13634 } 13635 if (p == null) { 13636 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13637 return false; 13638 } 13639 final ApplicationInfo applicationInfo = p.applicationInfo; 13640 if (applicationInfo == null) { 13641 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13642 return false; 13643 } 13644 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13645 if (retCode < 0) { 13646 Slog.w(TAG, "Couldn't remove cache files for package: " 13647 + packageName + " u" + userId); 13648 return false; 13649 } 13650 return true; 13651 } 13652 13653 @Override 13654 public void getPackageSizeInfo(final String packageName, int userHandle, 13655 final IPackageStatsObserver observer) { 13656 mContext.enforceCallingOrSelfPermission( 13657 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13658 if (packageName == null) { 13659 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13660 } 13661 13662 PackageStats stats = new PackageStats(packageName, userHandle); 13663 13664 /* 13665 * Queue up an async operation since the package measurement may take a 13666 * little while. 13667 */ 13668 Message msg = mHandler.obtainMessage(INIT_COPY); 13669 msg.obj = new MeasureParams(stats, observer); 13670 mHandler.sendMessage(msg); 13671 } 13672 13673 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13674 PackageStats pStats) { 13675 if (packageName == null) { 13676 Slog.w(TAG, "Attempt to get size of null packageName."); 13677 return false; 13678 } 13679 PackageParser.Package p; 13680 boolean dataOnly = false; 13681 String libDirRoot = null; 13682 String asecPath = null; 13683 PackageSetting ps = null; 13684 synchronized (mPackages) { 13685 p = mPackages.get(packageName); 13686 ps = mSettings.mPackages.get(packageName); 13687 if(p == null) { 13688 dataOnly = true; 13689 if((ps == null) || (ps.pkg == null)) { 13690 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13691 return false; 13692 } 13693 p = ps.pkg; 13694 } 13695 if (ps != null) { 13696 libDirRoot = ps.legacyNativeLibraryPathString; 13697 } 13698 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13699 final long token = Binder.clearCallingIdentity(); 13700 try { 13701 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13702 if (secureContainerId != null) { 13703 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13704 } 13705 } finally { 13706 Binder.restoreCallingIdentity(token); 13707 } 13708 } 13709 } 13710 String publicSrcDir = null; 13711 if(!dataOnly) { 13712 final ApplicationInfo applicationInfo = p.applicationInfo; 13713 if (applicationInfo == null) { 13714 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13715 return false; 13716 } 13717 if (p.isForwardLocked()) { 13718 publicSrcDir = applicationInfo.getBaseResourcePath(); 13719 } 13720 } 13721 // TODO: extend to measure size of split APKs 13722 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13723 // not just the first level. 13724 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13725 // just the primary. 13726 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13727 13728 String apkPath; 13729 File packageDir = new File(p.codePath); 13730 13731 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13732 apkPath = packageDir.getAbsolutePath(); 13733 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13734 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13735 libDirRoot = null; 13736 } 13737 } else { 13738 apkPath = p.baseCodePath; 13739 } 13740 13741 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13742 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13743 if (res < 0) { 13744 return false; 13745 } 13746 13747 // Fix-up for forward-locked applications in ASEC containers. 13748 if (!isExternal(p)) { 13749 pStats.codeSize += pStats.externalCodeSize; 13750 pStats.externalCodeSize = 0L; 13751 } 13752 13753 return true; 13754 } 13755 13756 13757 @Override 13758 public void addPackageToPreferred(String packageName) { 13759 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13760 } 13761 13762 @Override 13763 public void removePackageFromPreferred(String packageName) { 13764 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13765 } 13766 13767 @Override 13768 public List<PackageInfo> getPreferredPackages(int flags) { 13769 return new ArrayList<PackageInfo>(); 13770 } 13771 13772 private int getUidTargetSdkVersionLockedLPr(int uid) { 13773 Object obj = mSettings.getUserIdLPr(uid); 13774 if (obj instanceof SharedUserSetting) { 13775 final SharedUserSetting sus = (SharedUserSetting) obj; 13776 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13777 final Iterator<PackageSetting> it = sus.packages.iterator(); 13778 while (it.hasNext()) { 13779 final PackageSetting ps = it.next(); 13780 if (ps.pkg != null) { 13781 int v = ps.pkg.applicationInfo.targetSdkVersion; 13782 if (v < vers) vers = v; 13783 } 13784 } 13785 return vers; 13786 } else if (obj instanceof PackageSetting) { 13787 final PackageSetting ps = (PackageSetting) obj; 13788 if (ps.pkg != null) { 13789 return ps.pkg.applicationInfo.targetSdkVersion; 13790 } 13791 } 13792 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13793 } 13794 13795 @Override 13796 public void addPreferredActivity(IntentFilter filter, int match, 13797 ComponentName[] set, ComponentName activity, int userId) { 13798 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13799 "Adding preferred"); 13800 } 13801 13802 private void addPreferredActivityInternal(IntentFilter filter, int match, 13803 ComponentName[] set, ComponentName activity, boolean always, int userId, 13804 String opname) { 13805 // writer 13806 int callingUid = Binder.getCallingUid(); 13807 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13808 if (filter.countActions() == 0) { 13809 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13810 return; 13811 } 13812 synchronized (mPackages) { 13813 if (mContext.checkCallingOrSelfPermission( 13814 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13815 != PackageManager.PERMISSION_GRANTED) { 13816 if (getUidTargetSdkVersionLockedLPr(callingUid) 13817 < Build.VERSION_CODES.FROYO) { 13818 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13819 + callingUid); 13820 return; 13821 } 13822 mContext.enforceCallingOrSelfPermission( 13823 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13824 } 13825 13826 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13827 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13828 + userId + ":"); 13829 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13830 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13831 scheduleWritePackageRestrictionsLocked(userId); 13832 } 13833 } 13834 13835 @Override 13836 public void replacePreferredActivity(IntentFilter filter, int match, 13837 ComponentName[] set, ComponentName activity, int userId) { 13838 if (filter.countActions() != 1) { 13839 throw new IllegalArgumentException( 13840 "replacePreferredActivity expects filter to have only 1 action."); 13841 } 13842 if (filter.countDataAuthorities() != 0 13843 || filter.countDataPaths() != 0 13844 || filter.countDataSchemes() > 1 13845 || filter.countDataTypes() != 0) { 13846 throw new IllegalArgumentException( 13847 "replacePreferredActivity expects filter to have no data authorities, " + 13848 "paths, or types; and at most one scheme."); 13849 } 13850 13851 final int callingUid = Binder.getCallingUid(); 13852 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13853 synchronized (mPackages) { 13854 if (mContext.checkCallingOrSelfPermission( 13855 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13856 != PackageManager.PERMISSION_GRANTED) { 13857 if (getUidTargetSdkVersionLockedLPr(callingUid) 13858 < Build.VERSION_CODES.FROYO) { 13859 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13860 + Binder.getCallingUid()); 13861 return; 13862 } 13863 mContext.enforceCallingOrSelfPermission( 13864 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13865 } 13866 13867 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13868 if (pir != null) { 13869 // Get all of the existing entries that exactly match this filter. 13870 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13871 if (existing != null && existing.size() == 1) { 13872 PreferredActivity cur = existing.get(0); 13873 if (DEBUG_PREFERRED) { 13874 Slog.i(TAG, "Checking replace of preferred:"); 13875 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13876 if (!cur.mPref.mAlways) { 13877 Slog.i(TAG, " -- CUR; not mAlways!"); 13878 } else { 13879 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13880 Slog.i(TAG, " -- CUR: mSet=" 13881 + Arrays.toString(cur.mPref.mSetComponents)); 13882 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13883 Slog.i(TAG, " -- NEW: mMatch=" 13884 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13885 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13886 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13887 } 13888 } 13889 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13890 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13891 && cur.mPref.sameSet(set)) { 13892 // Setting the preferred activity to what it happens to be already 13893 if (DEBUG_PREFERRED) { 13894 Slog.i(TAG, "Replacing with same preferred activity " 13895 + cur.mPref.mShortComponent + " for user " 13896 + userId + ":"); 13897 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13898 } 13899 return; 13900 } 13901 } 13902 13903 if (existing != null) { 13904 if (DEBUG_PREFERRED) { 13905 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13906 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13907 } 13908 for (int i = 0; i < existing.size(); i++) { 13909 PreferredActivity pa = existing.get(i); 13910 if (DEBUG_PREFERRED) { 13911 Slog.i(TAG, "Removing existing preferred activity " 13912 + pa.mPref.mComponent + ":"); 13913 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13914 } 13915 pir.removeFilter(pa); 13916 } 13917 } 13918 } 13919 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13920 "Replacing preferred"); 13921 } 13922 } 13923 13924 @Override 13925 public void clearPackagePreferredActivities(String packageName) { 13926 final int uid = Binder.getCallingUid(); 13927 // writer 13928 synchronized (mPackages) { 13929 PackageParser.Package pkg = mPackages.get(packageName); 13930 if (pkg == null || pkg.applicationInfo.uid != uid) { 13931 if (mContext.checkCallingOrSelfPermission( 13932 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13933 != PackageManager.PERMISSION_GRANTED) { 13934 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13935 < Build.VERSION_CODES.FROYO) { 13936 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13937 + Binder.getCallingUid()); 13938 return; 13939 } 13940 mContext.enforceCallingOrSelfPermission( 13941 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13942 } 13943 } 13944 13945 int user = UserHandle.getCallingUserId(); 13946 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13947 scheduleWritePackageRestrictionsLocked(user); 13948 } 13949 } 13950 } 13951 13952 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13953 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13954 ArrayList<PreferredActivity> removed = null; 13955 boolean changed = false; 13956 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13957 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13958 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13959 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13960 continue; 13961 } 13962 Iterator<PreferredActivity> it = pir.filterIterator(); 13963 while (it.hasNext()) { 13964 PreferredActivity pa = it.next(); 13965 // Mark entry for removal only if it matches the package name 13966 // and the entry is of type "always". 13967 if (packageName == null || 13968 (pa.mPref.mComponent.getPackageName().equals(packageName) 13969 && pa.mPref.mAlways)) { 13970 if (removed == null) { 13971 removed = new ArrayList<PreferredActivity>(); 13972 } 13973 removed.add(pa); 13974 } 13975 } 13976 if (removed != null) { 13977 for (int j=0; j<removed.size(); j++) { 13978 PreferredActivity pa = removed.get(j); 13979 pir.removeFilter(pa); 13980 } 13981 changed = true; 13982 } 13983 } 13984 return changed; 13985 } 13986 13987 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13988 private void clearIntentFilterVerificationsLPw(int userId) { 13989 final int packageCount = mPackages.size(); 13990 for (int i = 0; i < packageCount; i++) { 13991 PackageParser.Package pkg = mPackages.valueAt(i); 13992 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13993 } 13994 } 13995 13996 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13997 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13998 if (userId == UserHandle.USER_ALL) { 13999 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14000 sUserManager.getUserIds())) { 14001 for (int oneUserId : sUserManager.getUserIds()) { 14002 scheduleWritePackageRestrictionsLocked(oneUserId); 14003 } 14004 } 14005 } else { 14006 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14007 scheduleWritePackageRestrictionsLocked(userId); 14008 } 14009 } 14010 } 14011 14012 void clearDefaultBrowserIfNeeded(String packageName) { 14013 for (int oneUserId : sUserManager.getUserIds()) { 14014 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14015 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14016 if (packageName.equals(defaultBrowserPackageName)) { 14017 setDefaultBrowserPackageName(null, oneUserId); 14018 } 14019 } 14020 } 14021 14022 @Override 14023 public void resetApplicationPreferences(int userId) { 14024 mContext.enforceCallingOrSelfPermission( 14025 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14026 // writer 14027 synchronized (mPackages) { 14028 final long identity = Binder.clearCallingIdentity(); 14029 try { 14030 clearPackagePreferredActivitiesLPw(null, userId); 14031 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14032 // TODO: We have to reset the default SMS and Phone. This requires 14033 // significant refactoring to keep all default apps in the package 14034 // manager (cleaner but more work) or have the services provide 14035 // callbacks to the package manager to request a default app reset. 14036 applyFactoryDefaultBrowserLPw(userId); 14037 clearIntentFilterVerificationsLPw(userId); 14038 primeDomainVerificationsLPw(userId); 14039 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14040 scheduleWritePackageRestrictionsLocked(userId); 14041 } finally { 14042 Binder.restoreCallingIdentity(identity); 14043 } 14044 } 14045 } 14046 14047 @Override 14048 public int getPreferredActivities(List<IntentFilter> outFilters, 14049 List<ComponentName> outActivities, String packageName) { 14050 14051 int num = 0; 14052 final int userId = UserHandle.getCallingUserId(); 14053 // reader 14054 synchronized (mPackages) { 14055 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14056 if (pir != null) { 14057 final Iterator<PreferredActivity> it = pir.filterIterator(); 14058 while (it.hasNext()) { 14059 final PreferredActivity pa = it.next(); 14060 if (packageName == null 14061 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14062 && pa.mPref.mAlways)) { 14063 if (outFilters != null) { 14064 outFilters.add(new IntentFilter(pa)); 14065 } 14066 if (outActivities != null) { 14067 outActivities.add(pa.mPref.mComponent); 14068 } 14069 } 14070 } 14071 } 14072 } 14073 14074 return num; 14075 } 14076 14077 @Override 14078 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14079 int userId) { 14080 int callingUid = Binder.getCallingUid(); 14081 if (callingUid != Process.SYSTEM_UID) { 14082 throw new SecurityException( 14083 "addPersistentPreferredActivity can only be run by the system"); 14084 } 14085 if (filter.countActions() == 0) { 14086 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14087 return; 14088 } 14089 synchronized (mPackages) { 14090 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14091 " :"); 14092 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14093 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14094 new PersistentPreferredActivity(filter, activity)); 14095 scheduleWritePackageRestrictionsLocked(userId); 14096 } 14097 } 14098 14099 @Override 14100 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14101 int callingUid = Binder.getCallingUid(); 14102 if (callingUid != Process.SYSTEM_UID) { 14103 throw new SecurityException( 14104 "clearPackagePersistentPreferredActivities can only be run by the system"); 14105 } 14106 ArrayList<PersistentPreferredActivity> removed = null; 14107 boolean changed = false; 14108 synchronized (mPackages) { 14109 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14110 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14111 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14112 .valueAt(i); 14113 if (userId != thisUserId) { 14114 continue; 14115 } 14116 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14117 while (it.hasNext()) { 14118 PersistentPreferredActivity ppa = it.next(); 14119 // Mark entry for removal only if it matches the package name. 14120 if (ppa.mComponent.getPackageName().equals(packageName)) { 14121 if (removed == null) { 14122 removed = new ArrayList<PersistentPreferredActivity>(); 14123 } 14124 removed.add(ppa); 14125 } 14126 } 14127 if (removed != null) { 14128 for (int j=0; j<removed.size(); j++) { 14129 PersistentPreferredActivity ppa = removed.get(j); 14130 ppir.removeFilter(ppa); 14131 } 14132 changed = true; 14133 } 14134 } 14135 14136 if (changed) { 14137 scheduleWritePackageRestrictionsLocked(userId); 14138 } 14139 } 14140 } 14141 14142 /** 14143 * Common machinery for picking apart a restored XML blob and passing 14144 * it to a caller-supplied functor to be applied to the running system. 14145 */ 14146 private void restoreFromXml(XmlPullParser parser, int userId, 14147 String expectedStartTag, BlobXmlRestorer functor) 14148 throws IOException, XmlPullParserException { 14149 int type; 14150 while ((type = parser.next()) != XmlPullParser.START_TAG 14151 && type != XmlPullParser.END_DOCUMENT) { 14152 } 14153 if (type != XmlPullParser.START_TAG) { 14154 // oops didn't find a start tag?! 14155 if (DEBUG_BACKUP) { 14156 Slog.e(TAG, "Didn't find start tag during restore"); 14157 } 14158 return; 14159 } 14160 14161 // this is supposed to be TAG_PREFERRED_BACKUP 14162 if (!expectedStartTag.equals(parser.getName())) { 14163 if (DEBUG_BACKUP) { 14164 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14165 } 14166 return; 14167 } 14168 14169 // skip interfering stuff, then we're aligned with the backing implementation 14170 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14171 functor.apply(parser, userId); 14172 } 14173 14174 private interface BlobXmlRestorer { 14175 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14176 } 14177 14178 /** 14179 * Non-Binder method, support for the backup/restore mechanism: write the 14180 * full set of preferred activities in its canonical XML format. Returns the 14181 * XML output as a byte array, or null if there is none. 14182 */ 14183 @Override 14184 public byte[] getPreferredActivityBackup(int userId) { 14185 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14186 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14187 } 14188 14189 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14190 try { 14191 final XmlSerializer serializer = new FastXmlSerializer(); 14192 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14193 serializer.startDocument(null, true); 14194 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14195 14196 synchronized (mPackages) { 14197 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14198 } 14199 14200 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14201 serializer.endDocument(); 14202 serializer.flush(); 14203 } catch (Exception e) { 14204 if (DEBUG_BACKUP) { 14205 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14206 } 14207 return null; 14208 } 14209 14210 return dataStream.toByteArray(); 14211 } 14212 14213 @Override 14214 public void restorePreferredActivities(byte[] backup, int userId) { 14215 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14216 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14217 } 14218 14219 try { 14220 final XmlPullParser parser = Xml.newPullParser(); 14221 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14222 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14223 new BlobXmlRestorer() { 14224 @Override 14225 public void apply(XmlPullParser parser, int userId) 14226 throws XmlPullParserException, IOException { 14227 synchronized (mPackages) { 14228 mSettings.readPreferredActivitiesLPw(parser, userId); 14229 } 14230 } 14231 } ); 14232 } catch (Exception e) { 14233 if (DEBUG_BACKUP) { 14234 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14235 } 14236 } 14237 } 14238 14239 /** 14240 * Non-Binder method, support for the backup/restore mechanism: write the 14241 * default browser (etc) settings in its canonical XML format. Returns the default 14242 * browser XML representation as a byte array, or null if there is none. 14243 */ 14244 @Override 14245 public byte[] getDefaultAppsBackup(int userId) { 14246 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14247 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14248 } 14249 14250 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14251 try { 14252 final XmlSerializer serializer = new FastXmlSerializer(); 14253 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14254 serializer.startDocument(null, true); 14255 serializer.startTag(null, TAG_DEFAULT_APPS); 14256 14257 synchronized (mPackages) { 14258 mSettings.writeDefaultAppsLPr(serializer, userId); 14259 } 14260 14261 serializer.endTag(null, TAG_DEFAULT_APPS); 14262 serializer.endDocument(); 14263 serializer.flush(); 14264 } catch (Exception e) { 14265 if (DEBUG_BACKUP) { 14266 Slog.e(TAG, "Unable to write default apps for backup", e); 14267 } 14268 return null; 14269 } 14270 14271 return dataStream.toByteArray(); 14272 } 14273 14274 @Override 14275 public void restoreDefaultApps(byte[] backup, int userId) { 14276 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14277 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14278 } 14279 14280 try { 14281 final XmlPullParser parser = Xml.newPullParser(); 14282 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14283 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14284 new BlobXmlRestorer() { 14285 @Override 14286 public void apply(XmlPullParser parser, int userId) 14287 throws XmlPullParserException, IOException { 14288 synchronized (mPackages) { 14289 mSettings.readDefaultAppsLPw(parser, userId); 14290 } 14291 } 14292 } ); 14293 } catch (Exception e) { 14294 if (DEBUG_BACKUP) { 14295 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14296 } 14297 } 14298 } 14299 14300 @Override 14301 public byte[] getIntentFilterVerificationBackup(int userId) { 14302 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14303 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14304 } 14305 14306 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14307 try { 14308 final XmlSerializer serializer = new FastXmlSerializer(); 14309 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14310 serializer.startDocument(null, true); 14311 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14312 14313 synchronized (mPackages) { 14314 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14315 } 14316 14317 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14318 serializer.endDocument(); 14319 serializer.flush(); 14320 } catch (Exception e) { 14321 if (DEBUG_BACKUP) { 14322 Slog.e(TAG, "Unable to write default apps for backup", e); 14323 } 14324 return null; 14325 } 14326 14327 return dataStream.toByteArray(); 14328 } 14329 14330 @Override 14331 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14332 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14333 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14334 } 14335 14336 try { 14337 final XmlPullParser parser = Xml.newPullParser(); 14338 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14339 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14340 new BlobXmlRestorer() { 14341 @Override 14342 public void apply(XmlPullParser parser, int userId) 14343 throws XmlPullParserException, IOException { 14344 synchronized (mPackages) { 14345 mSettings.readAllDomainVerificationsLPr(parser, userId); 14346 mSettings.writeLPr(); 14347 } 14348 } 14349 } ); 14350 } catch (Exception e) { 14351 if (DEBUG_BACKUP) { 14352 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14353 } 14354 } 14355 } 14356 14357 @Override 14358 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14359 int sourceUserId, int targetUserId, int flags) { 14360 mContext.enforceCallingOrSelfPermission( 14361 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14362 int callingUid = Binder.getCallingUid(); 14363 enforceOwnerRights(ownerPackage, callingUid); 14364 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14365 if (intentFilter.countActions() == 0) { 14366 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14367 return; 14368 } 14369 synchronized (mPackages) { 14370 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14371 ownerPackage, targetUserId, flags); 14372 CrossProfileIntentResolver resolver = 14373 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14374 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14375 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14376 if (existing != null) { 14377 int size = existing.size(); 14378 for (int i = 0; i < size; i++) { 14379 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14380 return; 14381 } 14382 } 14383 } 14384 resolver.addFilter(newFilter); 14385 scheduleWritePackageRestrictionsLocked(sourceUserId); 14386 } 14387 } 14388 14389 @Override 14390 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14391 mContext.enforceCallingOrSelfPermission( 14392 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14393 int callingUid = Binder.getCallingUid(); 14394 enforceOwnerRights(ownerPackage, callingUid); 14395 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14396 synchronized (mPackages) { 14397 CrossProfileIntentResolver resolver = 14398 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14399 ArraySet<CrossProfileIntentFilter> set = 14400 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14401 for (CrossProfileIntentFilter filter : set) { 14402 if (filter.getOwnerPackage().equals(ownerPackage)) { 14403 resolver.removeFilter(filter); 14404 } 14405 } 14406 scheduleWritePackageRestrictionsLocked(sourceUserId); 14407 } 14408 } 14409 14410 // Enforcing that callingUid is owning pkg on userId 14411 private void enforceOwnerRights(String pkg, int callingUid) { 14412 // The system owns everything. 14413 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14414 return; 14415 } 14416 int callingUserId = UserHandle.getUserId(callingUid); 14417 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14418 if (pi == null) { 14419 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14420 + callingUserId); 14421 } 14422 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14423 throw new SecurityException("Calling uid " + callingUid 14424 + " does not own package " + pkg); 14425 } 14426 } 14427 14428 @Override 14429 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14430 Intent intent = new Intent(Intent.ACTION_MAIN); 14431 intent.addCategory(Intent.CATEGORY_HOME); 14432 14433 final int callingUserId = UserHandle.getCallingUserId(); 14434 List<ResolveInfo> list = queryIntentActivities(intent, null, 14435 PackageManager.GET_META_DATA, callingUserId); 14436 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14437 true, false, false, callingUserId); 14438 14439 allHomeCandidates.clear(); 14440 if (list != null) { 14441 for (ResolveInfo ri : list) { 14442 allHomeCandidates.add(ri); 14443 } 14444 } 14445 return (preferred == null || preferred.activityInfo == null) 14446 ? null 14447 : new ComponentName(preferred.activityInfo.packageName, 14448 preferred.activityInfo.name); 14449 } 14450 14451 @Override 14452 public void setApplicationEnabledSetting(String appPackageName, 14453 int newState, int flags, int userId, String callingPackage) { 14454 if (!sUserManager.exists(userId)) return; 14455 if (callingPackage == null) { 14456 callingPackage = Integer.toString(Binder.getCallingUid()); 14457 } 14458 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14459 } 14460 14461 @Override 14462 public void setComponentEnabledSetting(ComponentName componentName, 14463 int newState, int flags, int userId) { 14464 if (!sUserManager.exists(userId)) return; 14465 setEnabledSetting(componentName.getPackageName(), 14466 componentName.getClassName(), newState, flags, userId, null); 14467 } 14468 14469 private void setEnabledSetting(final String packageName, String className, int newState, 14470 final int flags, int userId, String callingPackage) { 14471 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14472 || newState == COMPONENT_ENABLED_STATE_ENABLED 14473 || newState == COMPONENT_ENABLED_STATE_DISABLED 14474 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14475 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14476 throw new IllegalArgumentException("Invalid new component state: " 14477 + newState); 14478 } 14479 PackageSetting pkgSetting; 14480 final int uid = Binder.getCallingUid(); 14481 final int permission = mContext.checkCallingOrSelfPermission( 14482 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14483 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14484 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14485 boolean sendNow = false; 14486 boolean isApp = (className == null); 14487 String componentName = isApp ? packageName : className; 14488 int packageUid = -1; 14489 ArrayList<String> components; 14490 14491 // writer 14492 synchronized (mPackages) { 14493 pkgSetting = mSettings.mPackages.get(packageName); 14494 if (pkgSetting == null) { 14495 if (className == null) { 14496 throw new IllegalArgumentException( 14497 "Unknown package: " + packageName); 14498 } 14499 throw new IllegalArgumentException( 14500 "Unknown component: " + packageName 14501 + "/" + className); 14502 } 14503 // Allow root and verify that userId is not being specified by a different user 14504 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14505 throw new SecurityException( 14506 "Permission Denial: attempt to change component state from pid=" 14507 + Binder.getCallingPid() 14508 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14509 } 14510 if (className == null) { 14511 // We're dealing with an application/package level state change 14512 if (pkgSetting.getEnabled(userId) == newState) { 14513 // Nothing to do 14514 return; 14515 } 14516 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14517 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14518 // Don't care about who enables an app. 14519 callingPackage = null; 14520 } 14521 pkgSetting.setEnabled(newState, userId, callingPackage); 14522 // pkgSetting.pkg.mSetEnabled = newState; 14523 } else { 14524 // We're dealing with a component level state change 14525 // First, verify that this is a valid class name. 14526 PackageParser.Package pkg = pkgSetting.pkg; 14527 if (pkg == null || !pkg.hasComponentClassName(className)) { 14528 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14529 throw new IllegalArgumentException("Component class " + className 14530 + " does not exist in " + packageName); 14531 } else { 14532 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14533 + className + " does not exist in " + packageName); 14534 } 14535 } 14536 switch (newState) { 14537 case COMPONENT_ENABLED_STATE_ENABLED: 14538 if (!pkgSetting.enableComponentLPw(className, userId)) { 14539 return; 14540 } 14541 break; 14542 case COMPONENT_ENABLED_STATE_DISABLED: 14543 if (!pkgSetting.disableComponentLPw(className, userId)) { 14544 return; 14545 } 14546 break; 14547 case COMPONENT_ENABLED_STATE_DEFAULT: 14548 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14549 return; 14550 } 14551 break; 14552 default: 14553 Slog.e(TAG, "Invalid new component state: " + newState); 14554 return; 14555 } 14556 } 14557 scheduleWritePackageRestrictionsLocked(userId); 14558 components = mPendingBroadcasts.get(userId, packageName); 14559 final boolean newPackage = components == null; 14560 if (newPackage) { 14561 components = new ArrayList<String>(); 14562 } 14563 if (!components.contains(componentName)) { 14564 components.add(componentName); 14565 } 14566 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14567 sendNow = true; 14568 // Purge entry from pending broadcast list if another one exists already 14569 // since we are sending one right away. 14570 mPendingBroadcasts.remove(userId, packageName); 14571 } else { 14572 if (newPackage) { 14573 mPendingBroadcasts.put(userId, packageName, components); 14574 } 14575 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14576 // Schedule a message 14577 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14578 } 14579 } 14580 } 14581 14582 long callingId = Binder.clearCallingIdentity(); 14583 try { 14584 if (sendNow) { 14585 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14586 sendPackageChangedBroadcast(packageName, 14587 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14588 } 14589 } finally { 14590 Binder.restoreCallingIdentity(callingId); 14591 } 14592 } 14593 14594 private void sendPackageChangedBroadcast(String packageName, 14595 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14596 if (DEBUG_INSTALL) 14597 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14598 + componentNames); 14599 Bundle extras = new Bundle(4); 14600 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14601 String nameList[] = new String[componentNames.size()]; 14602 componentNames.toArray(nameList); 14603 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14604 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14605 extras.putInt(Intent.EXTRA_UID, packageUid); 14606 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14607 new int[] {UserHandle.getUserId(packageUid)}); 14608 } 14609 14610 @Override 14611 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14612 if (!sUserManager.exists(userId)) return; 14613 final int uid = Binder.getCallingUid(); 14614 final int permission = mContext.checkCallingOrSelfPermission( 14615 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14616 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14617 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14618 // writer 14619 synchronized (mPackages) { 14620 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14621 allowedByPermission, uid, userId)) { 14622 scheduleWritePackageRestrictionsLocked(userId); 14623 } 14624 } 14625 } 14626 14627 @Override 14628 public String getInstallerPackageName(String packageName) { 14629 // reader 14630 synchronized (mPackages) { 14631 return mSettings.getInstallerPackageNameLPr(packageName); 14632 } 14633 } 14634 14635 @Override 14636 public int getApplicationEnabledSetting(String packageName, int userId) { 14637 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14638 int uid = Binder.getCallingUid(); 14639 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14640 // reader 14641 synchronized (mPackages) { 14642 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14643 } 14644 } 14645 14646 @Override 14647 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14648 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14649 int uid = Binder.getCallingUid(); 14650 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14651 // reader 14652 synchronized (mPackages) { 14653 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14654 } 14655 } 14656 14657 @Override 14658 public void enterSafeMode() { 14659 enforceSystemOrRoot("Only the system can request entering safe mode"); 14660 14661 if (!mSystemReady) { 14662 mSafeMode = true; 14663 } 14664 } 14665 14666 @Override 14667 public void systemReady() { 14668 mSystemReady = true; 14669 14670 // Read the compatibilty setting when the system is ready. 14671 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14672 mContext.getContentResolver(), 14673 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14674 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14675 if (DEBUG_SETTINGS) { 14676 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14677 } 14678 14679 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14680 14681 synchronized (mPackages) { 14682 // Verify that all of the preferred activity components actually 14683 // exist. It is possible for applications to be updated and at 14684 // that point remove a previously declared activity component that 14685 // had been set as a preferred activity. We try to clean this up 14686 // the next time we encounter that preferred activity, but it is 14687 // possible for the user flow to never be able to return to that 14688 // situation so here we do a sanity check to make sure we haven't 14689 // left any junk around. 14690 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14691 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14692 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14693 removed.clear(); 14694 for (PreferredActivity pa : pir.filterSet()) { 14695 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14696 removed.add(pa); 14697 } 14698 } 14699 if (removed.size() > 0) { 14700 for (int r=0; r<removed.size(); r++) { 14701 PreferredActivity pa = removed.get(r); 14702 Slog.w(TAG, "Removing dangling preferred activity: " 14703 + pa.mPref.mComponent); 14704 pir.removeFilter(pa); 14705 } 14706 mSettings.writePackageRestrictionsLPr( 14707 mSettings.mPreferredActivities.keyAt(i)); 14708 } 14709 } 14710 14711 for (int userId : UserManagerService.getInstance().getUserIds()) { 14712 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14713 grantPermissionsUserIds = ArrayUtils.appendInt( 14714 grantPermissionsUserIds, userId); 14715 } 14716 } 14717 } 14718 sUserManager.systemReady(); 14719 14720 // If we upgraded grant all default permissions before kicking off. 14721 for (int userId : grantPermissionsUserIds) { 14722 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14723 } 14724 14725 // Kick off any messages waiting for system ready 14726 if (mPostSystemReadyMessages != null) { 14727 for (Message msg : mPostSystemReadyMessages) { 14728 msg.sendToTarget(); 14729 } 14730 mPostSystemReadyMessages = null; 14731 } 14732 14733 // Watch for external volumes that come and go over time 14734 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14735 storage.registerListener(mStorageListener); 14736 14737 mInstallerService.systemReady(); 14738 mPackageDexOptimizer.systemReady(); 14739 14740 MountServiceInternal mountServiceInternal = LocalServices.getService( 14741 MountServiceInternal.class); 14742 mountServiceInternal.addExternalStoragePolicy( 14743 new MountServiceInternal.ExternalStorageMountPolicy() { 14744 @Override 14745 public int getMountMode(int uid, String packageName) { 14746 if (Process.isIsolated(uid)) { 14747 return Zygote.MOUNT_EXTERNAL_NONE; 14748 } 14749 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14750 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14751 } 14752 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14753 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14754 } 14755 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14756 return Zygote.MOUNT_EXTERNAL_READ; 14757 } 14758 return Zygote.MOUNT_EXTERNAL_WRITE; 14759 } 14760 14761 @Override 14762 public boolean hasExternalStorage(int uid, String packageName) { 14763 return true; 14764 } 14765 }); 14766 } 14767 14768 @Override 14769 public boolean isSafeMode() { 14770 return mSafeMode; 14771 } 14772 14773 @Override 14774 public boolean hasSystemUidErrors() { 14775 return mHasSystemUidErrors; 14776 } 14777 14778 static String arrayToString(int[] array) { 14779 StringBuffer buf = new StringBuffer(128); 14780 buf.append('['); 14781 if (array != null) { 14782 for (int i=0; i<array.length; i++) { 14783 if (i > 0) buf.append(", "); 14784 buf.append(array[i]); 14785 } 14786 } 14787 buf.append(']'); 14788 return buf.toString(); 14789 } 14790 14791 static class DumpState { 14792 public static final int DUMP_LIBS = 1 << 0; 14793 public static final int DUMP_FEATURES = 1 << 1; 14794 public static final int DUMP_RESOLVERS = 1 << 2; 14795 public static final int DUMP_PERMISSIONS = 1 << 3; 14796 public static final int DUMP_PACKAGES = 1 << 4; 14797 public static final int DUMP_SHARED_USERS = 1 << 5; 14798 public static final int DUMP_MESSAGES = 1 << 6; 14799 public static final int DUMP_PROVIDERS = 1 << 7; 14800 public static final int DUMP_VERIFIERS = 1 << 8; 14801 public static final int DUMP_PREFERRED = 1 << 9; 14802 public static final int DUMP_PREFERRED_XML = 1 << 10; 14803 public static final int DUMP_KEYSETS = 1 << 11; 14804 public static final int DUMP_VERSION = 1 << 12; 14805 public static final int DUMP_INSTALLS = 1 << 13; 14806 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14807 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14808 14809 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14810 14811 private int mTypes; 14812 14813 private int mOptions; 14814 14815 private boolean mTitlePrinted; 14816 14817 private SharedUserSetting mSharedUser; 14818 14819 public boolean isDumping(int type) { 14820 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14821 return true; 14822 } 14823 14824 return (mTypes & type) != 0; 14825 } 14826 14827 public void setDump(int type) { 14828 mTypes |= type; 14829 } 14830 14831 public boolean isOptionEnabled(int option) { 14832 return (mOptions & option) != 0; 14833 } 14834 14835 public void setOptionEnabled(int option) { 14836 mOptions |= option; 14837 } 14838 14839 public boolean onTitlePrinted() { 14840 final boolean printed = mTitlePrinted; 14841 mTitlePrinted = true; 14842 return printed; 14843 } 14844 14845 public boolean getTitlePrinted() { 14846 return mTitlePrinted; 14847 } 14848 14849 public void setTitlePrinted(boolean enabled) { 14850 mTitlePrinted = enabled; 14851 } 14852 14853 public SharedUserSetting getSharedUser() { 14854 return mSharedUser; 14855 } 14856 14857 public void setSharedUser(SharedUserSetting user) { 14858 mSharedUser = user; 14859 } 14860 } 14861 14862 @Override 14863 public void onShellCommand(FileDescriptor in, FileDescriptor out, 14864 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 14865 (new PackageManagerShellCommand(this)).exec( 14866 this, in, out, err, args, resultReceiver); 14867 } 14868 14869 @Override 14870 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14871 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14872 != PackageManager.PERMISSION_GRANTED) { 14873 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14874 + Binder.getCallingPid() 14875 + ", uid=" + Binder.getCallingUid() 14876 + " without permission " 14877 + android.Manifest.permission.DUMP); 14878 return; 14879 } 14880 14881 DumpState dumpState = new DumpState(); 14882 boolean fullPreferred = false; 14883 boolean checkin = false; 14884 14885 String packageName = null; 14886 ArraySet<String> permissionNames = null; 14887 14888 int opti = 0; 14889 while (opti < args.length) { 14890 String opt = args[opti]; 14891 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14892 break; 14893 } 14894 opti++; 14895 14896 if ("-a".equals(opt)) { 14897 // Right now we only know how to print all. 14898 } else if ("-h".equals(opt)) { 14899 pw.println("Package manager dump options:"); 14900 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14901 pw.println(" --checkin: dump for a checkin"); 14902 pw.println(" -f: print details of intent filters"); 14903 pw.println(" -h: print this help"); 14904 pw.println(" cmd may be one of:"); 14905 pw.println(" l[ibraries]: list known shared libraries"); 14906 pw.println(" f[ibraries]: list device features"); 14907 pw.println(" k[eysets]: print known keysets"); 14908 pw.println(" r[esolvers]: dump intent resolvers"); 14909 pw.println(" perm[issions]: dump permissions"); 14910 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14911 pw.println(" pref[erred]: print preferred package settings"); 14912 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14913 pw.println(" prov[iders]: dump content providers"); 14914 pw.println(" p[ackages]: dump installed packages"); 14915 pw.println(" s[hared-users]: dump shared user IDs"); 14916 pw.println(" m[essages]: print collected runtime messages"); 14917 pw.println(" v[erifiers]: print package verifier info"); 14918 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14919 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14920 pw.println(" version: print database version info"); 14921 pw.println(" write: write current settings now"); 14922 pw.println(" installs: details about install sessions"); 14923 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14924 pw.println(" <package.name>: info about given package"); 14925 return; 14926 } else if ("--checkin".equals(opt)) { 14927 checkin = true; 14928 } else if ("-f".equals(opt)) { 14929 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14930 } else { 14931 pw.println("Unknown argument: " + opt + "; use -h for help"); 14932 } 14933 } 14934 14935 // Is the caller requesting to dump a particular piece of data? 14936 if (opti < args.length) { 14937 String cmd = args[opti]; 14938 opti++; 14939 // Is this a package name? 14940 if ("android".equals(cmd) || cmd.contains(".")) { 14941 packageName = cmd; 14942 // When dumping a single package, we always dump all of its 14943 // filter information since the amount of data will be reasonable. 14944 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14945 } else if ("check-permission".equals(cmd)) { 14946 if (opti >= args.length) { 14947 pw.println("Error: check-permission missing permission argument"); 14948 return; 14949 } 14950 String perm = args[opti]; 14951 opti++; 14952 if (opti >= args.length) { 14953 pw.println("Error: check-permission missing package argument"); 14954 return; 14955 } 14956 String pkg = args[opti]; 14957 opti++; 14958 int user = UserHandle.getUserId(Binder.getCallingUid()); 14959 if (opti < args.length) { 14960 try { 14961 user = Integer.parseInt(args[opti]); 14962 } catch (NumberFormatException e) { 14963 pw.println("Error: check-permission user argument is not a number: " 14964 + args[opti]); 14965 return; 14966 } 14967 } 14968 pw.println(checkPermission(perm, pkg, user)); 14969 return; 14970 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14971 dumpState.setDump(DumpState.DUMP_LIBS); 14972 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14973 dumpState.setDump(DumpState.DUMP_FEATURES); 14974 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14975 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14976 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14977 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14978 } else if ("permission".equals(cmd)) { 14979 if (opti >= args.length) { 14980 pw.println("Error: permission requires permission name"); 14981 return; 14982 } 14983 permissionNames = new ArraySet<>(); 14984 while (opti < args.length) { 14985 permissionNames.add(args[opti]); 14986 opti++; 14987 } 14988 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14989 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14990 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14991 dumpState.setDump(DumpState.DUMP_PREFERRED); 14992 } else if ("preferred-xml".equals(cmd)) { 14993 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14994 if (opti < args.length && "--full".equals(args[opti])) { 14995 fullPreferred = true; 14996 opti++; 14997 } 14998 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14999 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15000 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15001 dumpState.setDump(DumpState.DUMP_PACKAGES); 15002 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15003 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15004 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15005 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15006 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15007 dumpState.setDump(DumpState.DUMP_MESSAGES); 15008 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15009 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15010 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15011 || "intent-filter-verifiers".equals(cmd)) { 15012 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15013 } else if ("version".equals(cmd)) { 15014 dumpState.setDump(DumpState.DUMP_VERSION); 15015 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15016 dumpState.setDump(DumpState.DUMP_KEYSETS); 15017 } else if ("installs".equals(cmd)) { 15018 dumpState.setDump(DumpState.DUMP_INSTALLS); 15019 } else if ("write".equals(cmd)) { 15020 synchronized (mPackages) { 15021 mSettings.writeLPr(); 15022 pw.println("Settings written."); 15023 return; 15024 } 15025 } 15026 } 15027 15028 if (checkin) { 15029 pw.println("vers,1"); 15030 } 15031 15032 // reader 15033 synchronized (mPackages) { 15034 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15035 if (!checkin) { 15036 if (dumpState.onTitlePrinted()) 15037 pw.println(); 15038 pw.println("Database versions:"); 15039 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15040 } 15041 } 15042 15043 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15044 if (!checkin) { 15045 if (dumpState.onTitlePrinted()) 15046 pw.println(); 15047 pw.println("Verifiers:"); 15048 pw.print(" Required: "); 15049 pw.print(mRequiredVerifierPackage); 15050 pw.print(" (uid="); 15051 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15052 pw.println(")"); 15053 } else if (mRequiredVerifierPackage != null) { 15054 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15055 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15056 } 15057 } 15058 15059 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15060 packageName == null) { 15061 if (mIntentFilterVerifierComponent != null) { 15062 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15063 if (!checkin) { 15064 if (dumpState.onTitlePrinted()) 15065 pw.println(); 15066 pw.println("Intent Filter Verifier:"); 15067 pw.print(" Using: "); 15068 pw.print(verifierPackageName); 15069 pw.print(" (uid="); 15070 pw.print(getPackageUid(verifierPackageName, 0)); 15071 pw.println(")"); 15072 } else if (verifierPackageName != null) { 15073 pw.print("ifv,"); pw.print(verifierPackageName); 15074 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15075 } 15076 } else { 15077 pw.println(); 15078 pw.println("No Intent Filter Verifier available!"); 15079 } 15080 } 15081 15082 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15083 boolean printedHeader = false; 15084 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15085 while (it.hasNext()) { 15086 String name = it.next(); 15087 SharedLibraryEntry ent = mSharedLibraries.get(name); 15088 if (!checkin) { 15089 if (!printedHeader) { 15090 if (dumpState.onTitlePrinted()) 15091 pw.println(); 15092 pw.println("Libraries:"); 15093 printedHeader = true; 15094 } 15095 pw.print(" "); 15096 } else { 15097 pw.print("lib,"); 15098 } 15099 pw.print(name); 15100 if (!checkin) { 15101 pw.print(" -> "); 15102 } 15103 if (ent.path != null) { 15104 if (!checkin) { 15105 pw.print("(jar) "); 15106 pw.print(ent.path); 15107 } else { 15108 pw.print(",jar,"); 15109 pw.print(ent.path); 15110 } 15111 } else { 15112 if (!checkin) { 15113 pw.print("(apk) "); 15114 pw.print(ent.apk); 15115 } else { 15116 pw.print(",apk,"); 15117 pw.print(ent.apk); 15118 } 15119 } 15120 pw.println(); 15121 } 15122 } 15123 15124 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15125 if (dumpState.onTitlePrinted()) 15126 pw.println(); 15127 if (!checkin) { 15128 pw.println("Features:"); 15129 } 15130 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15131 while (it.hasNext()) { 15132 String name = it.next(); 15133 if (!checkin) { 15134 pw.print(" "); 15135 } else { 15136 pw.print("feat,"); 15137 } 15138 pw.println(name); 15139 } 15140 } 15141 15142 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15143 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15144 : "Activity Resolver Table:", " ", packageName, 15145 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15146 dumpState.setTitlePrinted(true); 15147 } 15148 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15149 : "Receiver Resolver Table:", " ", packageName, 15150 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15151 dumpState.setTitlePrinted(true); 15152 } 15153 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15154 : "Service Resolver Table:", " ", packageName, 15155 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15156 dumpState.setTitlePrinted(true); 15157 } 15158 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15159 : "Provider Resolver Table:", " ", packageName, 15160 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15161 dumpState.setTitlePrinted(true); 15162 } 15163 } 15164 15165 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15166 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15167 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15168 int user = mSettings.mPreferredActivities.keyAt(i); 15169 if (pir.dump(pw, 15170 dumpState.getTitlePrinted() 15171 ? "\nPreferred Activities User " + user + ":" 15172 : "Preferred Activities User " + user + ":", " ", 15173 packageName, true, false)) { 15174 dumpState.setTitlePrinted(true); 15175 } 15176 } 15177 } 15178 15179 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15180 pw.flush(); 15181 FileOutputStream fout = new FileOutputStream(fd); 15182 BufferedOutputStream str = new BufferedOutputStream(fout); 15183 XmlSerializer serializer = new FastXmlSerializer(); 15184 try { 15185 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15186 serializer.startDocument(null, true); 15187 serializer.setFeature( 15188 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15189 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15190 serializer.endDocument(); 15191 serializer.flush(); 15192 } catch (IllegalArgumentException e) { 15193 pw.println("Failed writing: " + e); 15194 } catch (IllegalStateException e) { 15195 pw.println("Failed writing: " + e); 15196 } catch (IOException e) { 15197 pw.println("Failed writing: " + e); 15198 } 15199 } 15200 15201 if (!checkin 15202 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15203 && packageName == null) { 15204 pw.println(); 15205 int count = mSettings.mPackages.size(); 15206 if (count == 0) { 15207 pw.println("No applications!"); 15208 pw.println(); 15209 } else { 15210 final String prefix = " "; 15211 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15212 if (allPackageSettings.size() == 0) { 15213 pw.println("No domain preferred apps!"); 15214 pw.println(); 15215 } else { 15216 pw.println("App verification status:"); 15217 pw.println(); 15218 count = 0; 15219 for (PackageSetting ps : allPackageSettings) { 15220 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15221 if (ivi == null || ivi.getPackageName() == null) continue; 15222 pw.println(prefix + "Package: " + ivi.getPackageName()); 15223 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15224 pw.println(prefix + "Status: " + ivi.getStatusString()); 15225 pw.println(); 15226 count++; 15227 } 15228 if (count == 0) { 15229 pw.println(prefix + "No app verification established."); 15230 pw.println(); 15231 } 15232 for (int userId : sUserManager.getUserIds()) { 15233 pw.println("App linkages for user " + userId + ":"); 15234 pw.println(); 15235 count = 0; 15236 for (PackageSetting ps : allPackageSettings) { 15237 final long status = ps.getDomainVerificationStatusForUser(userId); 15238 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15239 continue; 15240 } 15241 pw.println(prefix + "Package: " + ps.name); 15242 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15243 String statusStr = IntentFilterVerificationInfo. 15244 getStatusStringFromValue(status); 15245 pw.println(prefix + "Status: " + statusStr); 15246 pw.println(); 15247 count++; 15248 } 15249 if (count == 0) { 15250 pw.println(prefix + "No configured app linkages."); 15251 pw.println(); 15252 } 15253 } 15254 } 15255 } 15256 } 15257 15258 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15259 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15260 if (packageName == null && permissionNames == null) { 15261 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15262 if (iperm == 0) { 15263 if (dumpState.onTitlePrinted()) 15264 pw.println(); 15265 pw.println("AppOp Permissions:"); 15266 } 15267 pw.print(" AppOp Permission "); 15268 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15269 pw.println(":"); 15270 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15271 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15272 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15273 } 15274 } 15275 } 15276 } 15277 15278 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15279 boolean printedSomething = false; 15280 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15281 if (packageName != null && !packageName.equals(p.info.packageName)) { 15282 continue; 15283 } 15284 if (!printedSomething) { 15285 if (dumpState.onTitlePrinted()) 15286 pw.println(); 15287 pw.println("Registered ContentProviders:"); 15288 printedSomething = true; 15289 } 15290 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15291 pw.print(" "); pw.println(p.toString()); 15292 } 15293 printedSomething = false; 15294 for (Map.Entry<String, PackageParser.Provider> entry : 15295 mProvidersByAuthority.entrySet()) { 15296 PackageParser.Provider p = entry.getValue(); 15297 if (packageName != null && !packageName.equals(p.info.packageName)) { 15298 continue; 15299 } 15300 if (!printedSomething) { 15301 if (dumpState.onTitlePrinted()) 15302 pw.println(); 15303 pw.println("ContentProvider Authorities:"); 15304 printedSomething = true; 15305 } 15306 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15307 pw.print(" "); pw.println(p.toString()); 15308 if (p.info != null && p.info.applicationInfo != null) { 15309 final String appInfo = p.info.applicationInfo.toString(); 15310 pw.print(" applicationInfo="); pw.println(appInfo); 15311 } 15312 } 15313 } 15314 15315 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15316 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15317 } 15318 15319 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15320 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15321 } 15322 15323 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15324 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15325 } 15326 15327 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15328 // XXX should handle packageName != null by dumping only install data that 15329 // the given package is involved with. 15330 if (dumpState.onTitlePrinted()) pw.println(); 15331 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15332 } 15333 15334 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15335 if (dumpState.onTitlePrinted()) pw.println(); 15336 mSettings.dumpReadMessagesLPr(pw, dumpState); 15337 15338 pw.println(); 15339 pw.println("Package warning messages:"); 15340 BufferedReader in = null; 15341 String line = null; 15342 try { 15343 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15344 while ((line = in.readLine()) != null) { 15345 if (line.contains("ignored: updated version")) continue; 15346 pw.println(line); 15347 } 15348 } catch (IOException ignored) { 15349 } finally { 15350 IoUtils.closeQuietly(in); 15351 } 15352 } 15353 15354 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15355 BufferedReader in = null; 15356 String line = null; 15357 try { 15358 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15359 while ((line = in.readLine()) != null) { 15360 if (line.contains("ignored: updated version")) continue; 15361 pw.print("msg,"); 15362 pw.println(line); 15363 } 15364 } catch (IOException ignored) { 15365 } finally { 15366 IoUtils.closeQuietly(in); 15367 } 15368 } 15369 } 15370 } 15371 15372 private String dumpDomainString(String packageName) { 15373 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15374 List<IntentFilter> filters = getAllIntentFilters(packageName); 15375 15376 ArraySet<String> result = new ArraySet<>(); 15377 if (iviList.size() > 0) { 15378 for (IntentFilterVerificationInfo ivi : iviList) { 15379 for (String host : ivi.getDomains()) { 15380 result.add(host); 15381 } 15382 } 15383 } 15384 if (filters != null && filters.size() > 0) { 15385 for (IntentFilter filter : filters) { 15386 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15387 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15388 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15389 result.addAll(filter.getHostsList()); 15390 } 15391 } 15392 } 15393 15394 StringBuilder sb = new StringBuilder(result.size() * 16); 15395 for (String domain : result) { 15396 if (sb.length() > 0) sb.append(" "); 15397 sb.append(domain); 15398 } 15399 return sb.toString(); 15400 } 15401 15402 // ------- apps on sdcard specific code ------- 15403 static final boolean DEBUG_SD_INSTALL = false; 15404 15405 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15406 15407 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15408 15409 private boolean mMediaMounted = false; 15410 15411 static String getEncryptKey() { 15412 try { 15413 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15414 SD_ENCRYPTION_KEYSTORE_NAME); 15415 if (sdEncKey == null) { 15416 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15417 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15418 if (sdEncKey == null) { 15419 Slog.e(TAG, "Failed to create encryption keys"); 15420 return null; 15421 } 15422 } 15423 return sdEncKey; 15424 } catch (NoSuchAlgorithmException nsae) { 15425 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15426 return null; 15427 } catch (IOException ioe) { 15428 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15429 return null; 15430 } 15431 } 15432 15433 /* 15434 * Update media status on PackageManager. 15435 */ 15436 @Override 15437 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15438 int callingUid = Binder.getCallingUid(); 15439 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15440 throw new SecurityException("Media status can only be updated by the system"); 15441 } 15442 // reader; this apparently protects mMediaMounted, but should probably 15443 // be a different lock in that case. 15444 synchronized (mPackages) { 15445 Log.i(TAG, "Updating external media status from " 15446 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15447 + (mediaStatus ? "mounted" : "unmounted")); 15448 if (DEBUG_SD_INSTALL) 15449 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15450 + ", mMediaMounted=" + mMediaMounted); 15451 if (mediaStatus == mMediaMounted) { 15452 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15453 : 0, -1); 15454 mHandler.sendMessage(msg); 15455 return; 15456 } 15457 mMediaMounted = mediaStatus; 15458 } 15459 // Queue up an async operation since the package installation may take a 15460 // little while. 15461 mHandler.post(new Runnable() { 15462 public void run() { 15463 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15464 } 15465 }); 15466 } 15467 15468 /** 15469 * Called by MountService when the initial ASECs to scan are available. 15470 * Should block until all the ASEC containers are finished being scanned. 15471 */ 15472 public void scanAvailableAsecs() { 15473 updateExternalMediaStatusInner(true, false, false); 15474 if (mShouldRestoreconData) { 15475 SELinuxMMAC.setRestoreconDone(); 15476 mShouldRestoreconData = false; 15477 } 15478 } 15479 15480 /* 15481 * Collect information of applications on external media, map them against 15482 * existing containers and update information based on current mount status. 15483 * Please note that we always have to report status if reportStatus has been 15484 * set to true especially when unloading packages. 15485 */ 15486 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15487 boolean externalStorage) { 15488 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15489 int[] uidArr = EmptyArray.INT; 15490 15491 final String[] list = PackageHelper.getSecureContainerList(); 15492 if (ArrayUtils.isEmpty(list)) { 15493 Log.i(TAG, "No secure containers found"); 15494 } else { 15495 // Process list of secure containers and categorize them 15496 // as active or stale based on their package internal state. 15497 15498 // reader 15499 synchronized (mPackages) { 15500 for (String cid : list) { 15501 // Leave stages untouched for now; installer service owns them 15502 if (PackageInstallerService.isStageName(cid)) continue; 15503 15504 if (DEBUG_SD_INSTALL) 15505 Log.i(TAG, "Processing container " + cid); 15506 String pkgName = getAsecPackageName(cid); 15507 if (pkgName == null) { 15508 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15509 continue; 15510 } 15511 if (DEBUG_SD_INSTALL) 15512 Log.i(TAG, "Looking for pkg : " + pkgName); 15513 15514 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15515 if (ps == null) { 15516 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15517 continue; 15518 } 15519 15520 /* 15521 * Skip packages that are not external if we're unmounting 15522 * external storage. 15523 */ 15524 if (externalStorage && !isMounted && !isExternal(ps)) { 15525 continue; 15526 } 15527 15528 final AsecInstallArgs args = new AsecInstallArgs(cid, 15529 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15530 // The package status is changed only if the code path 15531 // matches between settings and the container id. 15532 if (ps.codePathString != null 15533 && ps.codePathString.startsWith(args.getCodePath())) { 15534 if (DEBUG_SD_INSTALL) { 15535 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15536 + " at code path: " + ps.codePathString); 15537 } 15538 15539 // We do have a valid package installed on sdcard 15540 processCids.put(args, ps.codePathString); 15541 final int uid = ps.appId; 15542 if (uid != -1) { 15543 uidArr = ArrayUtils.appendInt(uidArr, uid); 15544 } 15545 } else { 15546 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15547 + ps.codePathString); 15548 } 15549 } 15550 } 15551 15552 Arrays.sort(uidArr); 15553 } 15554 15555 // Process packages with valid entries. 15556 if (isMounted) { 15557 if (DEBUG_SD_INSTALL) 15558 Log.i(TAG, "Loading packages"); 15559 loadMediaPackages(processCids, uidArr, externalStorage); 15560 startCleaningPackages(); 15561 mInstallerService.onSecureContainersAvailable(); 15562 } else { 15563 if (DEBUG_SD_INSTALL) 15564 Log.i(TAG, "Unloading packages"); 15565 unloadMediaPackages(processCids, uidArr, reportStatus); 15566 } 15567 } 15568 15569 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15570 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15571 final int size = infos.size(); 15572 final String[] packageNames = new String[size]; 15573 final int[] packageUids = new int[size]; 15574 for (int i = 0; i < size; i++) { 15575 final ApplicationInfo info = infos.get(i); 15576 packageNames[i] = info.packageName; 15577 packageUids[i] = info.uid; 15578 } 15579 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15580 finishedReceiver); 15581 } 15582 15583 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15584 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15585 sendResourcesChangedBroadcast(mediaStatus, replacing, 15586 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15587 } 15588 15589 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15590 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15591 int size = pkgList.length; 15592 if (size > 0) { 15593 // Send broadcasts here 15594 Bundle extras = new Bundle(); 15595 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15596 if (uidArr != null) { 15597 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15598 } 15599 if (replacing) { 15600 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15601 } 15602 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15603 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15604 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15605 } 15606 } 15607 15608 /* 15609 * Look at potentially valid container ids from processCids If package 15610 * information doesn't match the one on record or package scanning fails, 15611 * the cid is added to list of removeCids. We currently don't delete stale 15612 * containers. 15613 */ 15614 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15615 boolean externalStorage) { 15616 ArrayList<String> pkgList = new ArrayList<String>(); 15617 Set<AsecInstallArgs> keys = processCids.keySet(); 15618 15619 for (AsecInstallArgs args : keys) { 15620 String codePath = processCids.get(args); 15621 if (DEBUG_SD_INSTALL) 15622 Log.i(TAG, "Loading container : " + args.cid); 15623 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15624 try { 15625 // Make sure there are no container errors first. 15626 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15627 Slog.e(TAG, "Failed to mount cid : " + args.cid 15628 + " when installing from sdcard"); 15629 continue; 15630 } 15631 // Check code path here. 15632 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15633 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15634 + " does not match one in settings " + codePath); 15635 continue; 15636 } 15637 // Parse package 15638 int parseFlags = mDefParseFlags; 15639 if (args.isExternalAsec()) { 15640 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15641 } 15642 if (args.isFwdLocked()) { 15643 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15644 } 15645 15646 synchronized (mInstallLock) { 15647 PackageParser.Package pkg = null; 15648 try { 15649 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15650 } catch (PackageManagerException e) { 15651 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15652 } 15653 // Scan the package 15654 if (pkg != null) { 15655 /* 15656 * TODO why is the lock being held? doPostInstall is 15657 * called in other places without the lock. This needs 15658 * to be straightened out. 15659 */ 15660 // writer 15661 synchronized (mPackages) { 15662 retCode = PackageManager.INSTALL_SUCCEEDED; 15663 pkgList.add(pkg.packageName); 15664 // Post process args 15665 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15666 pkg.applicationInfo.uid); 15667 } 15668 } else { 15669 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15670 } 15671 } 15672 15673 } finally { 15674 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15675 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15676 } 15677 } 15678 } 15679 // writer 15680 synchronized (mPackages) { 15681 // If the platform SDK has changed since the last time we booted, 15682 // we need to re-grant app permission to catch any new ones that 15683 // appear. This is really a hack, and means that apps can in some 15684 // cases get permissions that the user didn't initially explicitly 15685 // allow... it would be nice to have some better way to handle 15686 // this situation. 15687 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15688 : mSettings.getInternalVersion(); 15689 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15690 : StorageManager.UUID_PRIVATE_INTERNAL; 15691 15692 int updateFlags = UPDATE_PERMISSIONS_ALL; 15693 if (ver.sdkVersion != mSdkVersion) { 15694 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15695 + mSdkVersion + "; regranting permissions for external"); 15696 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15697 } 15698 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15699 15700 // Yay, everything is now upgraded 15701 ver.forceCurrent(); 15702 15703 // can downgrade to reader 15704 // Persist settings 15705 mSettings.writeLPr(); 15706 } 15707 // Send a broadcast to let everyone know we are done processing 15708 if (pkgList.size() > 0) { 15709 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15710 } 15711 } 15712 15713 /* 15714 * Utility method to unload a list of specified containers 15715 */ 15716 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15717 // Just unmount all valid containers. 15718 for (AsecInstallArgs arg : cidArgs) { 15719 synchronized (mInstallLock) { 15720 arg.doPostDeleteLI(false); 15721 } 15722 } 15723 } 15724 15725 /* 15726 * Unload packages mounted on external media. This involves deleting package 15727 * data from internal structures, sending broadcasts about diabled packages, 15728 * gc'ing to free up references, unmounting all secure containers 15729 * corresponding to packages on external media, and posting a 15730 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15731 * that we always have to post this message if status has been requested no 15732 * matter what. 15733 */ 15734 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15735 final boolean reportStatus) { 15736 if (DEBUG_SD_INSTALL) 15737 Log.i(TAG, "unloading media packages"); 15738 ArrayList<String> pkgList = new ArrayList<String>(); 15739 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15740 final Set<AsecInstallArgs> keys = processCids.keySet(); 15741 for (AsecInstallArgs args : keys) { 15742 String pkgName = args.getPackageName(); 15743 if (DEBUG_SD_INSTALL) 15744 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15745 // Delete package internally 15746 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15747 synchronized (mInstallLock) { 15748 boolean res = deletePackageLI(pkgName, null, false, null, null, 15749 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15750 if (res) { 15751 pkgList.add(pkgName); 15752 } else { 15753 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15754 failedList.add(args); 15755 } 15756 } 15757 } 15758 15759 // reader 15760 synchronized (mPackages) { 15761 // We didn't update the settings after removing each package; 15762 // write them now for all packages. 15763 mSettings.writeLPr(); 15764 } 15765 15766 // We have to absolutely send UPDATED_MEDIA_STATUS only 15767 // after confirming that all the receivers processed the ordered 15768 // broadcast when packages get disabled, force a gc to clean things up. 15769 // and unload all the containers. 15770 if (pkgList.size() > 0) { 15771 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15772 new IIntentReceiver.Stub() { 15773 public void performReceive(Intent intent, int resultCode, String data, 15774 Bundle extras, boolean ordered, boolean sticky, 15775 int sendingUser) throws RemoteException { 15776 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15777 reportStatus ? 1 : 0, 1, keys); 15778 mHandler.sendMessage(msg); 15779 } 15780 }); 15781 } else { 15782 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15783 keys); 15784 mHandler.sendMessage(msg); 15785 } 15786 } 15787 15788 private void loadPrivatePackages(final VolumeInfo vol) { 15789 mHandler.post(new Runnable() { 15790 @Override 15791 public void run() { 15792 loadPrivatePackagesInner(vol); 15793 } 15794 }); 15795 } 15796 15797 private void loadPrivatePackagesInner(VolumeInfo vol) { 15798 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15799 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15800 15801 final VersionInfo ver; 15802 final List<PackageSetting> packages; 15803 synchronized (mPackages) { 15804 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15805 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15806 } 15807 15808 for (PackageSetting ps : packages) { 15809 synchronized (mInstallLock) { 15810 final PackageParser.Package pkg; 15811 try { 15812 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 15813 loaded.add(pkg.applicationInfo); 15814 } catch (PackageManagerException e) { 15815 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15816 } 15817 15818 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15819 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15820 } 15821 } 15822 } 15823 15824 synchronized (mPackages) { 15825 int updateFlags = UPDATE_PERMISSIONS_ALL; 15826 if (ver.sdkVersion != mSdkVersion) { 15827 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15828 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15829 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15830 } 15831 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 15832 15833 // Yay, everything is now upgraded 15834 ver.forceCurrent(); 15835 15836 mSettings.writeLPr(); 15837 } 15838 15839 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15840 sendResourcesChangedBroadcast(true, false, loaded, null); 15841 } 15842 15843 private void unloadPrivatePackages(final VolumeInfo vol) { 15844 mHandler.post(new Runnable() { 15845 @Override 15846 public void run() { 15847 unloadPrivatePackagesInner(vol); 15848 } 15849 }); 15850 } 15851 15852 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15853 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15854 synchronized (mInstallLock) { 15855 synchronized (mPackages) { 15856 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15857 for (PackageSetting ps : packages) { 15858 if (ps.pkg == null) continue; 15859 15860 final ApplicationInfo info = ps.pkg.applicationInfo; 15861 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15862 if (deletePackageLI(ps.name, null, false, null, null, 15863 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15864 unloaded.add(info); 15865 } else { 15866 Slog.w(TAG, "Failed to unload " + ps.codePath); 15867 } 15868 } 15869 15870 mSettings.writeLPr(); 15871 } 15872 } 15873 15874 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15875 sendResourcesChangedBroadcast(false, false, unloaded, null); 15876 } 15877 15878 /** 15879 * Examine all users present on given mounted volume, and destroy data 15880 * belonging to users that are no longer valid, or whose user ID has been 15881 * recycled. 15882 */ 15883 private void reconcileUsers(String volumeUuid) { 15884 final File[] files = FileUtils 15885 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15886 for (File file : files) { 15887 if (!file.isDirectory()) continue; 15888 15889 final int userId; 15890 final UserInfo info; 15891 try { 15892 userId = Integer.parseInt(file.getName()); 15893 info = sUserManager.getUserInfo(userId); 15894 } catch (NumberFormatException e) { 15895 Slog.w(TAG, "Invalid user directory " + file); 15896 continue; 15897 } 15898 15899 boolean destroyUser = false; 15900 if (info == null) { 15901 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15902 + " because no matching user was found"); 15903 destroyUser = true; 15904 } else { 15905 try { 15906 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15907 } catch (IOException e) { 15908 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15909 + " because we failed to enforce serial number: " + e); 15910 destroyUser = true; 15911 } 15912 } 15913 15914 if (destroyUser) { 15915 synchronized (mInstallLock) { 15916 mInstaller.removeUserDataDirs(volumeUuid, userId); 15917 } 15918 } 15919 } 15920 15921 final UserManager um = mContext.getSystemService(UserManager.class); 15922 for (UserInfo user : um.getUsers()) { 15923 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15924 if (userDir.exists()) continue; 15925 15926 try { 15927 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15928 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15929 } catch (IOException e) { 15930 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15931 } 15932 } 15933 } 15934 15935 /** 15936 * Examine all apps present on given mounted volume, and destroy apps that 15937 * aren't expected, either due to uninstallation or reinstallation on 15938 * another volume. 15939 */ 15940 private void reconcileApps(String volumeUuid) { 15941 final File[] files = FileUtils 15942 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15943 for (File file : files) { 15944 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15945 && !PackageInstallerService.isStageName(file.getName()); 15946 if (!isPackage) { 15947 // Ignore entries which are not packages 15948 continue; 15949 } 15950 15951 boolean destroyApp = false; 15952 String packageName = null; 15953 try { 15954 final PackageLite pkg = PackageParser.parsePackageLite(file, 15955 PackageParser.PARSE_MUST_BE_APK); 15956 packageName = pkg.packageName; 15957 15958 synchronized (mPackages) { 15959 final PackageSetting ps = mSettings.mPackages.get(packageName); 15960 if (ps == null) { 15961 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15962 + volumeUuid + " because we found no install record"); 15963 destroyApp = true; 15964 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15965 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15966 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15967 destroyApp = true; 15968 } 15969 } 15970 15971 } catch (PackageParserException e) { 15972 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15973 destroyApp = true; 15974 } 15975 15976 if (destroyApp) { 15977 synchronized (mInstallLock) { 15978 if (packageName != null) { 15979 removeDataDirsLI(volumeUuid, packageName); 15980 } 15981 if (file.isDirectory()) { 15982 mInstaller.rmPackageDir(file.getAbsolutePath()); 15983 } else { 15984 file.delete(); 15985 } 15986 } 15987 } 15988 } 15989 } 15990 15991 private void unfreezePackage(String packageName) { 15992 synchronized (mPackages) { 15993 final PackageSetting ps = mSettings.mPackages.get(packageName); 15994 if (ps != null) { 15995 ps.frozen = false; 15996 } 15997 } 15998 } 15999 16000 @Override 16001 public int movePackage(final String packageName, final String volumeUuid) { 16002 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16003 16004 final int moveId = mNextMoveId.getAndIncrement(); 16005 mHandler.post(new Runnable() { 16006 @Override 16007 public void run() { 16008 try { 16009 movePackageInternal(packageName, volumeUuid, moveId); 16010 } catch (PackageManagerException e) { 16011 Slog.w(TAG, "Failed to move " + packageName, e); 16012 mMoveCallbacks.notifyStatusChanged(moveId, 16013 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16014 } 16015 } 16016 }); 16017 return moveId; 16018 } 16019 16020 private void movePackageInternal(final String packageName, final String volumeUuid, 16021 final int moveId) throws PackageManagerException { 16022 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16023 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16024 final PackageManager pm = mContext.getPackageManager(); 16025 16026 final boolean currentAsec; 16027 final String currentVolumeUuid; 16028 final File codeFile; 16029 final String installerPackageName; 16030 final String packageAbiOverride; 16031 final int appId; 16032 final String seinfo; 16033 final String label; 16034 16035 // reader 16036 synchronized (mPackages) { 16037 final PackageParser.Package pkg = mPackages.get(packageName); 16038 final PackageSetting ps = mSettings.mPackages.get(packageName); 16039 if (pkg == null || ps == null) { 16040 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16041 } 16042 16043 if (pkg.applicationInfo.isSystemApp()) { 16044 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16045 "Cannot move system application"); 16046 } 16047 16048 if (pkg.applicationInfo.isExternalAsec()) { 16049 currentAsec = true; 16050 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16051 } else if (pkg.applicationInfo.isForwardLocked()) { 16052 currentAsec = true; 16053 currentVolumeUuid = "forward_locked"; 16054 } else { 16055 currentAsec = false; 16056 currentVolumeUuid = ps.volumeUuid; 16057 16058 final File probe = new File(pkg.codePath); 16059 final File probeOat = new File(probe, "oat"); 16060 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16061 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16062 "Move only supported for modern cluster style installs"); 16063 } 16064 } 16065 16066 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16067 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16068 "Package already moved to " + volumeUuid); 16069 } 16070 16071 if (ps.frozen) { 16072 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16073 "Failed to move already frozen package"); 16074 } 16075 ps.frozen = true; 16076 16077 codeFile = new File(pkg.codePath); 16078 installerPackageName = ps.installerPackageName; 16079 packageAbiOverride = ps.cpuAbiOverrideString; 16080 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16081 seinfo = pkg.applicationInfo.seinfo; 16082 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16083 } 16084 16085 // Now that we're guarded by frozen state, kill app during move 16086 final long token = Binder.clearCallingIdentity(); 16087 try { 16088 killApplication(packageName, appId, "move pkg"); 16089 } finally { 16090 Binder.restoreCallingIdentity(token); 16091 } 16092 16093 final Bundle extras = new Bundle(); 16094 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16095 extras.putString(Intent.EXTRA_TITLE, label); 16096 mMoveCallbacks.notifyCreated(moveId, extras); 16097 16098 int installFlags; 16099 final boolean moveCompleteApp; 16100 final File measurePath; 16101 16102 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16103 installFlags = INSTALL_INTERNAL; 16104 moveCompleteApp = !currentAsec; 16105 measurePath = Environment.getDataAppDirectory(volumeUuid); 16106 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16107 installFlags = INSTALL_EXTERNAL; 16108 moveCompleteApp = false; 16109 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16110 } else { 16111 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16112 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16113 || !volume.isMountedWritable()) { 16114 unfreezePackage(packageName); 16115 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16116 "Move location not mounted private volume"); 16117 } 16118 16119 Preconditions.checkState(!currentAsec); 16120 16121 installFlags = INSTALL_INTERNAL; 16122 moveCompleteApp = true; 16123 measurePath = Environment.getDataAppDirectory(volumeUuid); 16124 } 16125 16126 final PackageStats stats = new PackageStats(null, -1); 16127 synchronized (mInstaller) { 16128 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16129 unfreezePackage(packageName); 16130 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16131 "Failed to measure package size"); 16132 } 16133 } 16134 16135 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16136 + stats.dataSize); 16137 16138 final long startFreeBytes = measurePath.getFreeSpace(); 16139 final long sizeBytes; 16140 if (moveCompleteApp) { 16141 sizeBytes = stats.codeSize + stats.dataSize; 16142 } else { 16143 sizeBytes = stats.codeSize; 16144 } 16145 16146 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16147 unfreezePackage(packageName); 16148 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16149 "Not enough free space to move"); 16150 } 16151 16152 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16153 16154 final CountDownLatch installedLatch = new CountDownLatch(1); 16155 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16156 @Override 16157 public void onUserActionRequired(Intent intent) throws RemoteException { 16158 throw new IllegalStateException(); 16159 } 16160 16161 @Override 16162 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16163 Bundle extras) throws RemoteException { 16164 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16165 + PackageManager.installStatusToString(returnCode, msg)); 16166 16167 installedLatch.countDown(); 16168 16169 // Regardless of success or failure of the move operation, 16170 // always unfreeze the package 16171 unfreezePackage(packageName); 16172 16173 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16174 switch (status) { 16175 case PackageInstaller.STATUS_SUCCESS: 16176 mMoveCallbacks.notifyStatusChanged(moveId, 16177 PackageManager.MOVE_SUCCEEDED); 16178 break; 16179 case PackageInstaller.STATUS_FAILURE_STORAGE: 16180 mMoveCallbacks.notifyStatusChanged(moveId, 16181 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16182 break; 16183 default: 16184 mMoveCallbacks.notifyStatusChanged(moveId, 16185 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16186 break; 16187 } 16188 } 16189 }; 16190 16191 final MoveInfo move; 16192 if (moveCompleteApp) { 16193 // Kick off a thread to report progress estimates 16194 new Thread() { 16195 @Override 16196 public void run() { 16197 while (true) { 16198 try { 16199 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16200 break; 16201 } 16202 } catch (InterruptedException ignored) { 16203 } 16204 16205 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16206 final int progress = 10 + (int) MathUtils.constrain( 16207 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16208 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16209 } 16210 } 16211 }.start(); 16212 16213 final String dataAppName = codeFile.getName(); 16214 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16215 dataAppName, appId, seinfo); 16216 } else { 16217 move = null; 16218 } 16219 16220 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16221 16222 final Message msg = mHandler.obtainMessage(INIT_COPY); 16223 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16224 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16225 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16226 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16227 msg.obj = params; 16228 16229 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16230 System.identityHashCode(msg.obj)); 16231 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16232 System.identityHashCode(msg.obj)); 16233 16234 mHandler.sendMessage(msg); 16235 } 16236 16237 @Override 16238 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16239 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16240 16241 final int realMoveId = mNextMoveId.getAndIncrement(); 16242 final Bundle extras = new Bundle(); 16243 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16244 mMoveCallbacks.notifyCreated(realMoveId, extras); 16245 16246 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16247 @Override 16248 public void onCreated(int moveId, Bundle extras) { 16249 // Ignored 16250 } 16251 16252 @Override 16253 public void onStatusChanged(int moveId, int status, long estMillis) { 16254 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16255 } 16256 }; 16257 16258 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16259 storage.setPrimaryStorageUuid(volumeUuid, callback); 16260 return realMoveId; 16261 } 16262 16263 @Override 16264 public int getMoveStatus(int moveId) { 16265 mContext.enforceCallingOrSelfPermission( 16266 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16267 return mMoveCallbacks.mLastStatus.get(moveId); 16268 } 16269 16270 @Override 16271 public void registerMoveCallback(IPackageMoveObserver callback) { 16272 mContext.enforceCallingOrSelfPermission( 16273 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16274 mMoveCallbacks.register(callback); 16275 } 16276 16277 @Override 16278 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16279 mContext.enforceCallingOrSelfPermission( 16280 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16281 mMoveCallbacks.unregister(callback); 16282 } 16283 16284 @Override 16285 public boolean setInstallLocation(int loc) { 16286 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16287 null); 16288 if (getInstallLocation() == loc) { 16289 return true; 16290 } 16291 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16292 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16293 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16294 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16295 return true; 16296 } 16297 return false; 16298 } 16299 16300 @Override 16301 public int getInstallLocation() { 16302 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16303 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16304 PackageHelper.APP_INSTALL_AUTO); 16305 } 16306 16307 /** Called by UserManagerService */ 16308 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16309 mDirtyUsers.remove(userHandle); 16310 mSettings.removeUserLPw(userHandle); 16311 mPendingBroadcasts.remove(userHandle); 16312 if (mInstaller != null) { 16313 // Technically, we shouldn't be doing this with the package lock 16314 // held. However, this is very rare, and there is already so much 16315 // other disk I/O going on, that we'll let it slide for now. 16316 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16317 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16318 final String volumeUuid = vol.getFsUuid(); 16319 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16320 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16321 } 16322 } 16323 mUserNeedsBadging.delete(userHandle); 16324 removeUnusedPackagesLILPw(userManager, userHandle); 16325 } 16326 16327 /** 16328 * We're removing userHandle and would like to remove any downloaded packages 16329 * that are no longer in use by any other user. 16330 * @param userHandle the user being removed 16331 */ 16332 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16333 final boolean DEBUG_CLEAN_APKS = false; 16334 int [] users = userManager.getUserIds(); 16335 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16336 while (psit.hasNext()) { 16337 PackageSetting ps = psit.next(); 16338 if (ps.pkg == null) { 16339 continue; 16340 } 16341 final String packageName = ps.pkg.packageName; 16342 // Skip over if system app 16343 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16344 continue; 16345 } 16346 if (DEBUG_CLEAN_APKS) { 16347 Slog.i(TAG, "Checking package " + packageName); 16348 } 16349 boolean keep = false; 16350 for (int i = 0; i < users.length; i++) { 16351 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16352 keep = true; 16353 if (DEBUG_CLEAN_APKS) { 16354 Slog.i(TAG, " Keeping package " + packageName + " for user " 16355 + users[i]); 16356 } 16357 break; 16358 } 16359 } 16360 if (!keep) { 16361 if (DEBUG_CLEAN_APKS) { 16362 Slog.i(TAG, " Removing package " + packageName); 16363 } 16364 mHandler.post(new Runnable() { 16365 public void run() { 16366 deletePackageX(packageName, userHandle, 0); 16367 } //end run 16368 }); 16369 } 16370 } 16371 } 16372 16373 /** Called by UserManagerService */ 16374 void createNewUserLILPw(int userHandle) { 16375 if (mInstaller != null) { 16376 mInstaller.createUserConfig(userHandle); 16377 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16378 applyFactoryDefaultBrowserLPw(userHandle); 16379 primeDomainVerificationsLPw(userHandle); 16380 } 16381 } 16382 16383 void newUserCreated(final int userHandle) { 16384 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16385 } 16386 16387 @Override 16388 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16389 mContext.enforceCallingOrSelfPermission( 16390 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16391 "Only package verification agents can read the verifier device identity"); 16392 16393 synchronized (mPackages) { 16394 return mSettings.getVerifierDeviceIdentityLPw(); 16395 } 16396 } 16397 16398 @Override 16399 public void setPermissionEnforced(String permission, boolean enforced) { 16400 // TODO: Now that we no longer change GID for storage, this should to away. 16401 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16402 "setPermissionEnforced"); 16403 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16404 synchronized (mPackages) { 16405 if (mSettings.mReadExternalStorageEnforced == null 16406 || mSettings.mReadExternalStorageEnforced != enforced) { 16407 mSettings.mReadExternalStorageEnforced = enforced; 16408 mSettings.writeLPr(); 16409 } 16410 } 16411 // kill any non-foreground processes so we restart them and 16412 // grant/revoke the GID. 16413 final IActivityManager am = ActivityManagerNative.getDefault(); 16414 if (am != null) { 16415 final long token = Binder.clearCallingIdentity(); 16416 try { 16417 am.killProcessesBelowForeground("setPermissionEnforcement"); 16418 } catch (RemoteException e) { 16419 } finally { 16420 Binder.restoreCallingIdentity(token); 16421 } 16422 } 16423 } else { 16424 throw new IllegalArgumentException("No selective enforcement for " + permission); 16425 } 16426 } 16427 16428 @Override 16429 @Deprecated 16430 public boolean isPermissionEnforced(String permission) { 16431 return true; 16432 } 16433 16434 @Override 16435 public boolean isStorageLow() { 16436 final long token = Binder.clearCallingIdentity(); 16437 try { 16438 final DeviceStorageMonitorInternal 16439 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16440 if (dsm != null) { 16441 return dsm.isMemoryLow(); 16442 } else { 16443 return false; 16444 } 16445 } finally { 16446 Binder.restoreCallingIdentity(token); 16447 } 16448 } 16449 16450 @Override 16451 public IPackageInstaller getPackageInstaller() { 16452 return mInstallerService; 16453 } 16454 16455 private boolean userNeedsBadging(int userId) { 16456 int index = mUserNeedsBadging.indexOfKey(userId); 16457 if (index < 0) { 16458 final UserInfo userInfo; 16459 final long token = Binder.clearCallingIdentity(); 16460 try { 16461 userInfo = sUserManager.getUserInfo(userId); 16462 } finally { 16463 Binder.restoreCallingIdentity(token); 16464 } 16465 final boolean b; 16466 if (userInfo != null && userInfo.isManagedProfile()) { 16467 b = true; 16468 } else { 16469 b = false; 16470 } 16471 mUserNeedsBadging.put(userId, b); 16472 return b; 16473 } 16474 return mUserNeedsBadging.valueAt(index); 16475 } 16476 16477 @Override 16478 public KeySet getKeySetByAlias(String packageName, String alias) { 16479 if (packageName == null || alias == null) { 16480 return null; 16481 } 16482 synchronized(mPackages) { 16483 final PackageParser.Package pkg = mPackages.get(packageName); 16484 if (pkg == null) { 16485 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16486 throw new IllegalArgumentException("Unknown package: " + packageName); 16487 } 16488 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16489 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16490 } 16491 } 16492 16493 @Override 16494 public KeySet getSigningKeySet(String packageName) { 16495 if (packageName == null) { 16496 return null; 16497 } 16498 synchronized(mPackages) { 16499 final PackageParser.Package pkg = mPackages.get(packageName); 16500 if (pkg == null) { 16501 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16502 throw new IllegalArgumentException("Unknown package: " + packageName); 16503 } 16504 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16505 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16506 throw new SecurityException("May not access signing KeySet of other apps."); 16507 } 16508 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16509 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16510 } 16511 } 16512 16513 @Override 16514 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16515 if (packageName == null || ks == null) { 16516 return false; 16517 } 16518 synchronized(mPackages) { 16519 final PackageParser.Package pkg = mPackages.get(packageName); 16520 if (pkg == null) { 16521 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16522 throw new IllegalArgumentException("Unknown package: " + packageName); 16523 } 16524 IBinder ksh = ks.getToken(); 16525 if (ksh instanceof KeySetHandle) { 16526 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16527 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16528 } 16529 return false; 16530 } 16531 } 16532 16533 @Override 16534 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16535 if (packageName == null || ks == null) { 16536 return false; 16537 } 16538 synchronized(mPackages) { 16539 final PackageParser.Package pkg = mPackages.get(packageName); 16540 if (pkg == null) { 16541 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16542 throw new IllegalArgumentException("Unknown package: " + packageName); 16543 } 16544 IBinder ksh = ks.getToken(); 16545 if (ksh instanceof KeySetHandle) { 16546 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16547 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16548 } 16549 return false; 16550 } 16551 } 16552 16553 /** 16554 * Check and throw if the given before/after packages would be considered a 16555 * downgrade. 16556 */ 16557 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16558 throws PackageManagerException { 16559 if (after.versionCode < before.mVersionCode) { 16560 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16561 "Update version code " + after.versionCode + " is older than current " 16562 + before.mVersionCode); 16563 } else if (after.versionCode == before.mVersionCode) { 16564 if (after.baseRevisionCode < before.baseRevisionCode) { 16565 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16566 "Update base revision code " + after.baseRevisionCode 16567 + " is older than current " + before.baseRevisionCode); 16568 } 16569 16570 if (!ArrayUtils.isEmpty(after.splitNames)) { 16571 for (int i = 0; i < after.splitNames.length; i++) { 16572 final String splitName = after.splitNames[i]; 16573 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16574 if (j != -1) { 16575 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16576 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16577 "Update split " + splitName + " revision code " 16578 + after.splitRevisionCodes[i] + " is older than current " 16579 + before.splitRevisionCodes[j]); 16580 } 16581 } 16582 } 16583 } 16584 } 16585 } 16586 16587 private static class MoveCallbacks extends Handler { 16588 private static final int MSG_CREATED = 1; 16589 private static final int MSG_STATUS_CHANGED = 2; 16590 16591 private final RemoteCallbackList<IPackageMoveObserver> 16592 mCallbacks = new RemoteCallbackList<>(); 16593 16594 private final SparseIntArray mLastStatus = new SparseIntArray(); 16595 16596 public MoveCallbacks(Looper looper) { 16597 super(looper); 16598 } 16599 16600 public void register(IPackageMoveObserver callback) { 16601 mCallbacks.register(callback); 16602 } 16603 16604 public void unregister(IPackageMoveObserver callback) { 16605 mCallbacks.unregister(callback); 16606 } 16607 16608 @Override 16609 public void handleMessage(Message msg) { 16610 final SomeArgs args = (SomeArgs) msg.obj; 16611 final int n = mCallbacks.beginBroadcast(); 16612 for (int i = 0; i < n; i++) { 16613 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16614 try { 16615 invokeCallback(callback, msg.what, args); 16616 } catch (RemoteException ignored) { 16617 } 16618 } 16619 mCallbacks.finishBroadcast(); 16620 args.recycle(); 16621 } 16622 16623 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16624 throws RemoteException { 16625 switch (what) { 16626 case MSG_CREATED: { 16627 callback.onCreated(args.argi1, (Bundle) args.arg2); 16628 break; 16629 } 16630 case MSG_STATUS_CHANGED: { 16631 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16632 break; 16633 } 16634 } 16635 } 16636 16637 private void notifyCreated(int moveId, Bundle extras) { 16638 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16639 16640 final SomeArgs args = SomeArgs.obtain(); 16641 args.argi1 = moveId; 16642 args.arg2 = extras; 16643 obtainMessage(MSG_CREATED, args).sendToTarget(); 16644 } 16645 16646 private void notifyStatusChanged(int moveId, int status) { 16647 notifyStatusChanged(moveId, status, -1); 16648 } 16649 16650 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16651 Slog.v(TAG, "Move " + moveId + " status " + status); 16652 16653 final SomeArgs args = SomeArgs.obtain(); 16654 args.argi1 = moveId; 16655 args.argi2 = status; 16656 args.arg3 = estMillis; 16657 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16658 16659 synchronized (mLastStatus) { 16660 mLastStatus.put(moveId, status); 16661 } 16662 } 16663 } 16664 16665 private final class OnPermissionChangeListeners extends Handler { 16666 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16667 16668 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16669 new RemoteCallbackList<>(); 16670 16671 public OnPermissionChangeListeners(Looper looper) { 16672 super(looper); 16673 } 16674 16675 @Override 16676 public void handleMessage(Message msg) { 16677 switch (msg.what) { 16678 case MSG_ON_PERMISSIONS_CHANGED: { 16679 final int uid = msg.arg1; 16680 handleOnPermissionsChanged(uid); 16681 } break; 16682 } 16683 } 16684 16685 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16686 mPermissionListeners.register(listener); 16687 16688 } 16689 16690 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16691 mPermissionListeners.unregister(listener); 16692 } 16693 16694 public void onPermissionsChanged(int uid) { 16695 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16696 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16697 } 16698 } 16699 16700 private void handleOnPermissionsChanged(int uid) { 16701 final int count = mPermissionListeners.beginBroadcast(); 16702 try { 16703 for (int i = 0; i < count; i++) { 16704 IOnPermissionsChangeListener callback = mPermissionListeners 16705 .getBroadcastItem(i); 16706 try { 16707 callback.onPermissionsChanged(uid); 16708 } catch (RemoteException e) { 16709 Log.e(TAG, "Permission listener is dead", e); 16710 } 16711 } 16712 } finally { 16713 mPermissionListeners.finishBroadcast(); 16714 } 16715 } 16716 } 16717 16718 private class PackageManagerInternalImpl extends PackageManagerInternal { 16719 @Override 16720 public void setLocationPackagesProvider(PackagesProvider provider) { 16721 synchronized (mPackages) { 16722 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16723 } 16724 } 16725 16726 @Override 16727 public void setImePackagesProvider(PackagesProvider provider) { 16728 synchronized (mPackages) { 16729 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16730 } 16731 } 16732 16733 @Override 16734 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16735 synchronized (mPackages) { 16736 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16737 } 16738 } 16739 16740 @Override 16741 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16742 synchronized (mPackages) { 16743 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16744 } 16745 } 16746 16747 @Override 16748 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16749 synchronized (mPackages) { 16750 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16751 } 16752 } 16753 16754 @Override 16755 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16756 synchronized (mPackages) { 16757 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16758 } 16759 } 16760 16761 @Override 16762 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16763 synchronized (mPackages) { 16764 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16765 } 16766 } 16767 16768 @Override 16769 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16770 synchronized (mPackages) { 16771 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16772 packageName, userId); 16773 } 16774 } 16775 16776 @Override 16777 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16778 synchronized (mPackages) { 16779 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16780 packageName, userId); 16781 } 16782 } 16783 @Override 16784 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16785 synchronized (mPackages) { 16786 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16787 packageName, userId); 16788 } 16789 } 16790 } 16791 16792 @Override 16793 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16794 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16795 synchronized (mPackages) { 16796 final long identity = Binder.clearCallingIdentity(); 16797 try { 16798 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16799 packageNames, userId); 16800 } finally { 16801 Binder.restoreCallingIdentity(identity); 16802 } 16803 } 16804 } 16805 16806 private static void enforceSystemOrPhoneCaller(String tag) { 16807 int callingUid = Binder.getCallingUid(); 16808 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16809 throw new SecurityException( 16810 "Cannot call " + tag + " from UID " + callingUid); 16811 } 16812 } 16813} 16814