PackageManagerService.java revision 4f5de340c9c7b12d7d67ca53bac863976b36fd32
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.InstructionSets.getAppDexInstructionSets; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 86 87import android.Manifest; 88import android.app.ActivityManager; 89import android.app.ActivityManagerNative; 90import android.app.AppGlobals; 91import android.app.IActivityManager; 92import android.app.admin.IDevicePolicyManager; 93import android.app.backup.IBackupManager; 94import android.app.usage.UsageStats; 95import android.app.usage.UsageStatsManager; 96import android.content.BroadcastReceiver; 97import android.content.ComponentName; 98import android.content.Context; 99import android.content.IIntentReceiver; 100import android.content.Intent; 101import android.content.IntentFilter; 102import android.content.IntentSender; 103import android.content.IntentSender.SendIntentException; 104import android.content.ServiceConnection; 105import android.content.pm.ActivityInfo; 106import android.content.pm.ApplicationInfo; 107import android.content.pm.FeatureInfo; 108import android.content.pm.IOnPermissionsChangeListener; 109import android.content.pm.IPackageDataObserver; 110import android.content.pm.IPackageDeleteObserver; 111import android.content.pm.IPackageDeleteObserver2; 112import android.content.pm.IPackageInstallObserver2; 113import android.content.pm.IPackageInstaller; 114import android.content.pm.IPackageManager; 115import android.content.pm.IPackageMoveObserver; 116import android.content.pm.IPackageStatsObserver; 117import android.content.pm.InstrumentationInfo; 118import android.content.pm.IntentFilterVerificationInfo; 119import android.content.pm.KeySet; 120import android.content.pm.ManifestDigest; 121import android.content.pm.PackageCleanItem; 122import android.content.pm.PackageInfo; 123import android.content.pm.PackageInfoLite; 124import android.content.pm.PackageInstaller; 125import android.content.pm.PackageManager; 126import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 127import android.content.pm.PackageManagerInternal; 128import android.content.pm.PackageParser; 129import android.content.pm.PackageParser.ActivityIntentInfo; 130import android.content.pm.PackageParser.PackageLite; 131import android.content.pm.PackageParser.PackageParserException; 132import android.content.pm.PackageStats; 133import android.content.pm.PackageUserState; 134import android.content.pm.ParceledListSlice; 135import android.content.pm.PermissionGroupInfo; 136import android.content.pm.PermissionInfo; 137import android.content.pm.ProviderInfo; 138import android.content.pm.ResolveInfo; 139import android.content.pm.ServiceInfo; 140import android.content.pm.Signature; 141import android.content.pm.UserInfo; 142import android.content.pm.VerificationParams; 143import android.content.pm.VerifierDeviceIdentity; 144import android.content.pm.VerifierInfo; 145import android.content.res.Resources; 146import android.hardware.display.DisplayManager; 147import android.net.Uri; 148import android.os.Debug; 149import android.os.Binder; 150import android.os.Build; 151import android.os.Bundle; 152import android.os.Environment; 153import android.os.Environment.UserEnvironment; 154import android.os.FileUtils; 155import android.os.Handler; 156import android.os.IBinder; 157import android.os.Looper; 158import android.os.Message; 159import android.os.Parcel; 160import android.os.ParcelFileDescriptor; 161import android.os.Process; 162import android.os.RemoteCallbackList; 163import android.os.RemoteException; 164import android.os.SELinux; 165import android.os.ServiceManager; 166import android.os.SystemClock; 167import android.os.SystemProperties; 168import android.os.Trace; 169import android.os.UserHandle; 170import android.os.UserManager; 171import android.os.storage.IMountService; 172import android.os.storage.MountServiceInternal; 173import android.os.storage.StorageEventListener; 174import android.os.storage.StorageManager; 175import android.os.storage.VolumeInfo; 176import android.os.storage.VolumeRecord; 177import android.security.KeyStore; 178import android.security.SystemKeyStore; 179import android.system.ErrnoException; 180import android.system.Os; 181import android.system.StructStat; 182import android.text.TextUtils; 183import android.text.format.DateUtils; 184import android.util.ArrayMap; 185import android.util.ArraySet; 186import android.util.AtomicFile; 187import android.util.DisplayMetrics; 188import android.util.EventLog; 189import android.util.ExceptionUtils; 190import android.util.Log; 191import android.util.LogPrinter; 192import android.util.MathUtils; 193import android.util.PrintStreamPrinter; 194import android.util.Slog; 195import android.util.SparseArray; 196import android.util.SparseBooleanArray; 197import android.util.SparseIntArray; 198import android.util.Xml; 199import android.view.Display; 200 201import dalvik.system.DexFile; 202import dalvik.system.VMRuntime; 203 204import libcore.io.IoUtils; 205import libcore.util.EmptyArray; 206 207import com.android.internal.R; 208import com.android.internal.annotations.GuardedBy; 209import com.android.internal.app.IMediaContainerService; 210import com.android.internal.app.ResolverActivity; 211import com.android.internal.content.NativeLibraryHelper; 212import com.android.internal.content.PackageHelper; 213import com.android.internal.os.IParcelFileDescriptorFactory; 214import com.android.internal.os.SomeArgs; 215import com.android.internal.os.Zygote; 216import com.android.internal.util.ArrayUtils; 217import com.android.internal.util.FastPrintWriter; 218import com.android.internal.util.FastXmlSerializer; 219import com.android.internal.util.IndentingPrintWriter; 220import com.android.internal.util.Preconditions; 221import com.android.server.EventLogTags; 222import com.android.server.FgThread; 223import com.android.server.IntentResolver; 224import com.android.server.LocalServices; 225import com.android.server.ServiceThread; 226import com.android.server.SystemConfig; 227import com.android.server.Watchdog; 228import com.android.server.pm.PermissionsState.PermissionState; 229import com.android.server.pm.Settings.DatabaseVersion; 230import com.android.server.pm.Settings.VersionInfo; 231import com.android.server.storage.DeviceStorageMonitorInternal; 232 233import org.xmlpull.v1.XmlPullParser; 234import org.xmlpull.v1.XmlPullParserException; 235import org.xmlpull.v1.XmlSerializer; 236 237import java.io.BufferedInputStream; 238import java.io.BufferedOutputStream; 239import java.io.BufferedReader; 240import java.io.ByteArrayInputStream; 241import java.io.ByteArrayOutputStream; 242import java.io.File; 243import java.io.FileDescriptor; 244import java.io.FileNotFoundException; 245import java.io.FileOutputStream; 246import java.io.FileReader; 247import java.io.FilenameFilter; 248import java.io.IOException; 249import java.io.InputStream; 250import java.io.PrintWriter; 251import java.nio.charset.StandardCharsets; 252import java.security.NoSuchAlgorithmException; 253import java.security.PublicKey; 254import java.security.cert.CertificateEncodingException; 255import java.security.cert.CertificateException; 256import java.text.SimpleDateFormat; 257import java.util.ArrayList; 258import java.util.Arrays; 259import java.util.Collection; 260import java.util.Collections; 261import java.util.Comparator; 262import java.util.Date; 263import java.util.Iterator; 264import java.util.List; 265import java.util.Map; 266import java.util.Objects; 267import java.util.Set; 268import java.util.concurrent.CountDownLatch; 269import java.util.concurrent.TimeUnit; 270import java.util.concurrent.atomic.AtomicBoolean; 271import java.util.concurrent.atomic.AtomicInteger; 272import java.util.concurrent.atomic.AtomicLong; 273 274/** 275 * Keep track of all those .apks everywhere. 276 * 277 * This is very central to the platform's security; please run the unit 278 * tests whenever making modifications here: 279 * 280runtest -c android.content.pm.PackageManagerTests frameworks-core 281 * 282 * {@hide} 283 */ 284public class PackageManagerService extends IPackageManager.Stub { 285 static final String TAG = "PackageManager"; 286 static final boolean DEBUG_SETTINGS = false; 287 static final boolean DEBUG_PREFERRED = false; 288 static final boolean DEBUG_UPGRADE = false; 289 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 290 private static final boolean DEBUG_BACKUP = false; 291 private static final boolean DEBUG_INSTALL = false; 292 private static final boolean DEBUG_REMOVE = false; 293 private static final boolean DEBUG_BROADCASTS = false; 294 private static final boolean DEBUG_SHOW_INFO = false; 295 private static final boolean DEBUG_PACKAGE_INFO = false; 296 private static final boolean DEBUG_INTENT_MATCHING = false; 297 private static final boolean DEBUG_PACKAGE_SCANNING = false; 298 private static final boolean DEBUG_VERIFY = false; 299 private static final boolean DEBUG_DEXOPT = false; 300 private static final boolean DEBUG_ABI_SELECTION = false; 301 302 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 303 304 private static final int RADIO_UID = Process.PHONE_UID; 305 private static final int LOG_UID = Process.LOG_UID; 306 private static final int NFC_UID = Process.NFC_UID; 307 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 308 private static final int SHELL_UID = Process.SHELL_UID; 309 310 // Cap the size of permission trees that 3rd party apps can define 311 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 312 313 // Suffix used during package installation when copying/moving 314 // package apks to install directory. 315 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 316 317 static final int SCAN_NO_DEX = 1<<1; 318 static final int SCAN_FORCE_DEX = 1<<2; 319 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 320 static final int SCAN_NEW_INSTALL = 1<<4; 321 static final int SCAN_NO_PATHS = 1<<5; 322 static final int SCAN_UPDATE_TIME = 1<<6; 323 static final int SCAN_DEFER_DEX = 1<<7; 324 static final int SCAN_BOOTING = 1<<8; 325 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 326 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 327 static final int SCAN_REPLACING = 1<<11; 328 static final int SCAN_REQUIRE_KNOWN = 1<<12; 329 static final int SCAN_MOVE = 1<<13; 330 static final int SCAN_INITIAL = 1<<14; 331 332 static final int REMOVE_CHATTY = 1<<16; 333 334 private static final int[] EMPTY_INT_ARRAY = new int[0]; 335 336 /** 337 * Timeout (in milliseconds) after which the watchdog should declare that 338 * our handler thread is wedged. The usual default for such things is one 339 * minute but we sometimes do very lengthy I/O operations on this thread, 340 * such as installing multi-gigabyte applications, so ours needs to be longer. 341 */ 342 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 343 344 /** 345 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 346 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 347 * settings entry if available, otherwise we use the hardcoded default. If it's been 348 * more than this long since the last fstrim, we force one during the boot sequence. 349 * 350 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 351 * one gets run at the next available charging+idle time. This final mandatory 352 * no-fstrim check kicks in only of the other scheduling criteria is never met. 353 */ 354 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 355 356 /** 357 * Whether verification is enabled by default. 358 */ 359 private static final boolean DEFAULT_VERIFY_ENABLE = true; 360 361 /** 362 * The default maximum time to wait for the verification agent to return in 363 * milliseconds. 364 */ 365 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 366 367 /** 368 * The default response for package verification timeout. 369 * 370 * This can be either PackageManager.VERIFICATION_ALLOW or 371 * PackageManager.VERIFICATION_REJECT. 372 */ 373 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 374 375 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 376 377 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 378 DEFAULT_CONTAINER_PACKAGE, 379 "com.android.defcontainer.DefaultContainerService"); 380 381 private static final String KILL_APP_REASON_GIDS_CHANGED = 382 "permission grant or revoke changed gids"; 383 384 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 385 "permissions revoked"; 386 387 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 388 389 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 390 391 /** Permission grant: not grant the permission. */ 392 private static final int GRANT_DENIED = 1; 393 394 /** Permission grant: grant the permission as an install permission. */ 395 private static final int GRANT_INSTALL = 2; 396 397 /** Permission grant: grant the permission as an install permission for a legacy app. */ 398 private static final int GRANT_INSTALL_LEGACY = 3; 399 400 /** Permission grant: grant the permission as a runtime one. */ 401 private static final int GRANT_RUNTIME = 4; 402 403 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 404 private static final int GRANT_UPGRADE = 5; 405 406 /** Canonical intent used to identify what counts as a "web browser" app */ 407 private static final Intent sBrowserIntent; 408 static { 409 sBrowserIntent = new Intent(); 410 sBrowserIntent.setAction(Intent.ACTION_VIEW); 411 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 412 sBrowserIntent.setData(Uri.parse("http:")); 413 } 414 415 final ServiceThread mHandlerThread; 416 417 final PackageHandler mHandler; 418 419 /** 420 * Messages for {@link #mHandler} that need to wait for system ready before 421 * being dispatched. 422 */ 423 private ArrayList<Message> mPostSystemReadyMessages; 424 425 final int mSdkVersion = Build.VERSION.SDK_INT; 426 427 final Context mContext; 428 final boolean mFactoryTest; 429 final boolean mOnlyCore; 430 final boolean mLazyDexOpt; 431 final long mDexOptLRUThresholdInMills; 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.OWNER)) { 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 try { 1150 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1151 System.identityHashCode(params)); 1152 // If this is the only one pending we might 1153 // have to bind to the service again. 1154 if (!connectToService()) { 1155 Slog.e(TAG, "Failed to bind to media container service"); 1156 params.serviceError(); 1157 return; 1158 } else { 1159 // Once we bind to the service, the first 1160 // pending request will be processed. 1161 mPendingInstalls.add(idx, params); 1162 } 1163 } finally { 1164 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1165 System.identityHashCode(params)); 1166 } 1167 } else { 1168 mPendingInstalls.add(idx, params); 1169 // Already bound to the service. Just make 1170 // sure we trigger off processing the first request. 1171 if (idx == 0) { 1172 mHandler.sendEmptyMessage(MCS_BOUND); 1173 } 1174 } 1175 break; 1176 } 1177 case MCS_BOUND: { 1178 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1179 if (msg.obj != null) { 1180 mContainerService = (IMediaContainerService) msg.obj; 1181 } 1182 if (mContainerService == null) { 1183 if (!mBound) { 1184 // Something seriously wrong since we are not bound and we are not 1185 // waiting for connection. Bail out. 1186 Slog.e(TAG, "Cannot bind to media container service"); 1187 for (HandlerParams params : mPendingInstalls) { 1188 // Indicate service bind error 1189 params.serviceError(); 1190 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1191 System.identityHashCode(params)); 1192 } 1193 mPendingInstalls.clear(); 1194 } else { 1195 Slog.w(TAG, "Waiting to connect to media container service"); 1196 } 1197 } else if (mPendingInstalls.size() > 0) { 1198 HandlerParams params = mPendingInstalls.get(0); 1199 if (params != null) { 1200 if (params.startCopy()) { 1201 // We are done... look for more work or to 1202 // go idle. 1203 if (DEBUG_SD_INSTALL) Log.i(TAG, 1204 "Checking for more work or unbind..."); 1205 // Delete pending install 1206 if (mPendingInstalls.size() > 0) { 1207 mPendingInstalls.remove(0); 1208 } 1209 if (mPendingInstalls.size() == 0) { 1210 if (mBound) { 1211 if (DEBUG_SD_INSTALL) Log.i(TAG, 1212 "Posting delayed MCS_UNBIND"); 1213 removeMessages(MCS_UNBIND); 1214 Message ubmsg = obtainMessage(MCS_UNBIND); 1215 // Unbind after a little delay, to avoid 1216 // continual thrashing. 1217 sendMessageDelayed(ubmsg, 10000); 1218 } 1219 } else { 1220 // There are more pending requests in queue. 1221 // Just post MCS_BOUND message to trigger processing 1222 // of next pending install. 1223 if (DEBUG_SD_INSTALL) Log.i(TAG, 1224 "Posting MCS_BOUND for next work"); 1225 mHandler.sendEmptyMessage(MCS_BOUND); 1226 } 1227 } 1228 } 1229 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1230 System.identityHashCode(params)); 1231 } else { 1232 // Should never happen ideally. 1233 Slog.w(TAG, "Empty queue"); 1234 } 1235 break; 1236 } 1237 case MCS_RECONNECT: { 1238 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1239 if (mPendingInstalls.size() > 0) { 1240 if (mBound) { 1241 disconnectService(); 1242 } 1243 if (!connectToService()) { 1244 Slog.e(TAG, "Failed to bind to media container service"); 1245 for (HandlerParams params : mPendingInstalls) { 1246 // Indicate service bind error 1247 params.serviceError(); 1248 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1249 System.identityHashCode(params)); 1250 } 1251 mPendingInstalls.clear(); 1252 } 1253 } 1254 break; 1255 } 1256 case MCS_UNBIND: { 1257 // If there is no actual work left, then time to unbind. 1258 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1259 1260 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1261 if (mBound) { 1262 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1263 1264 disconnectService(); 1265 } 1266 } else if (mPendingInstalls.size() > 0) { 1267 // There are more pending requests in queue. 1268 // Just post MCS_BOUND message to trigger processing 1269 // of next pending install. 1270 mHandler.sendEmptyMessage(MCS_BOUND); 1271 } 1272 1273 break; 1274 } 1275 case MCS_GIVE_UP: { 1276 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1277 HandlerParams params = mPendingInstalls.remove(0); 1278 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1279 System.identityHashCode(params)); 1280 break; 1281 } 1282 case SEND_PENDING_BROADCAST: { 1283 String packages[]; 1284 ArrayList<String> components[]; 1285 int size = 0; 1286 int uids[]; 1287 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1288 synchronized (mPackages) { 1289 if (mPendingBroadcasts == null) { 1290 return; 1291 } 1292 size = mPendingBroadcasts.size(); 1293 if (size <= 0) { 1294 // Nothing to be done. Just return 1295 return; 1296 } 1297 packages = new String[size]; 1298 components = new ArrayList[size]; 1299 uids = new int[size]; 1300 int i = 0; // filling out the above arrays 1301 1302 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1303 int packageUserId = mPendingBroadcasts.userIdAt(n); 1304 Iterator<Map.Entry<String, ArrayList<String>>> it 1305 = mPendingBroadcasts.packagesForUserId(packageUserId) 1306 .entrySet().iterator(); 1307 while (it.hasNext() && i < size) { 1308 Map.Entry<String, ArrayList<String>> ent = it.next(); 1309 packages[i] = ent.getKey(); 1310 components[i] = ent.getValue(); 1311 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1312 uids[i] = (ps != null) 1313 ? UserHandle.getUid(packageUserId, ps.appId) 1314 : -1; 1315 i++; 1316 } 1317 } 1318 size = i; 1319 mPendingBroadcasts.clear(); 1320 } 1321 // Send broadcasts 1322 for (int i = 0; i < size; i++) { 1323 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1324 } 1325 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1326 break; 1327 } 1328 case START_CLEANING_PACKAGE: { 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 final String packageName = (String)msg.obj; 1331 final int userId = msg.arg1; 1332 final boolean andCode = msg.arg2 != 0; 1333 synchronized (mPackages) { 1334 if (userId == UserHandle.USER_ALL) { 1335 int[] users = sUserManager.getUserIds(); 1336 for (int user : users) { 1337 mSettings.addPackageToCleanLPw( 1338 new PackageCleanItem(user, packageName, andCode)); 1339 } 1340 } else { 1341 mSettings.addPackageToCleanLPw( 1342 new PackageCleanItem(userId, packageName, andCode)); 1343 } 1344 } 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 startCleaningPackages(); 1347 } break; 1348 case POST_INSTALL: { 1349 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1350 PostInstallData data = mRunningInstalls.get(msg.arg1); 1351 mRunningInstalls.delete(msg.arg1); 1352 boolean deleteOld = false; 1353 1354 if (data != null) { 1355 InstallArgs args = data.args; 1356 PackageInstalledInfo res = data.res; 1357 1358 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1359 final String packageName = res.pkg.applicationInfo.packageName; 1360 res.removedInfo.sendBroadcast(false, true, false); 1361 Bundle extras = new Bundle(1); 1362 extras.putInt(Intent.EXTRA_UID, res.uid); 1363 1364 // Now that we successfully installed the package, grant runtime 1365 // permissions if requested before broadcasting the install. 1366 if ((args.installFlags 1367 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1368 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1369 args.installGrantPermissions); 1370 } 1371 1372 // Determine the set of users who are adding this 1373 // package for the first time vs. those who are seeing 1374 // an update. 1375 int[] firstUsers; 1376 int[] updateUsers = new int[0]; 1377 if (res.origUsers == null || res.origUsers.length == 0) { 1378 firstUsers = res.newUsers; 1379 } else { 1380 firstUsers = new int[0]; 1381 for (int i=0; i<res.newUsers.length; i++) { 1382 int user = res.newUsers[i]; 1383 boolean isNew = true; 1384 for (int j=0; j<res.origUsers.length; j++) { 1385 if (res.origUsers[j] == user) { 1386 isNew = false; 1387 break; 1388 } 1389 } 1390 if (isNew) { 1391 int[] newFirst = new int[firstUsers.length+1]; 1392 System.arraycopy(firstUsers, 0, newFirst, 0, 1393 firstUsers.length); 1394 newFirst[firstUsers.length] = user; 1395 firstUsers = newFirst; 1396 } else { 1397 int[] newUpdate = new int[updateUsers.length+1]; 1398 System.arraycopy(updateUsers, 0, newUpdate, 0, 1399 updateUsers.length); 1400 newUpdate[updateUsers.length] = user; 1401 updateUsers = newUpdate; 1402 } 1403 } 1404 } 1405 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1406 packageName, extras, null, null, firstUsers); 1407 final boolean update = res.removedInfo.removedPackage != null; 1408 if (update) { 1409 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1410 } 1411 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1412 packageName, extras, null, null, updateUsers); 1413 if (update) { 1414 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1415 packageName, extras, null, null, updateUsers); 1416 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1417 null, null, packageName, null, updateUsers); 1418 1419 // treat asec-hosted packages like removable media on upgrade 1420 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1421 if (DEBUG_INSTALL) { 1422 Slog.i(TAG, "upgrading pkg " + res.pkg 1423 + " is ASEC-hosted -> AVAILABLE"); 1424 } 1425 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1426 ArrayList<String> pkgList = new ArrayList<String>(1); 1427 pkgList.add(packageName); 1428 sendResourcesChangedBroadcast(true, true, 1429 pkgList,uidArray, null); 1430 } 1431 } 1432 if (res.removedInfo.args != null) { 1433 // Remove the replaced package's older resources safely now 1434 deleteOld = true; 1435 } 1436 1437 // If this app is a browser and it's newly-installed for some 1438 // users, clear any default-browser state in those users 1439 if (firstUsers.length > 0) { 1440 // the app's nature doesn't depend on the user, so we can just 1441 // check its browser nature in any user and generalize. 1442 if (packageIsBrowser(packageName, firstUsers[0])) { 1443 synchronized (mPackages) { 1444 for (int userId : firstUsers) { 1445 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1446 } 1447 } 1448 } 1449 } 1450 // Log current value of "unknown sources" setting 1451 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1452 getUnknownSourcesSettings()); 1453 } 1454 // Force a gc to clear up things 1455 Runtime.getRuntime().gc(); 1456 // We delete after a gc for applications on sdcard. 1457 if (deleteOld) { 1458 synchronized (mInstallLock) { 1459 res.removedInfo.args.doPostDeleteLI(true); 1460 } 1461 } 1462 if (args.observer != null) { 1463 try { 1464 Bundle extras = extrasForInstallResult(res); 1465 args.observer.onPackageInstalled(res.name, res.returnCode, 1466 res.returnMsg, extras); 1467 } catch (RemoteException e) { 1468 Slog.i(TAG, "Observer no longer exists."); 1469 } 1470 } 1471 } else { 1472 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1473 } 1474 1475 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1476 } break; 1477 case UPDATED_MEDIA_STATUS: { 1478 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1479 boolean reportStatus = msg.arg1 == 1; 1480 boolean doGc = msg.arg2 == 1; 1481 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1482 if (doGc) { 1483 // Force a gc to clear up stale containers. 1484 Runtime.getRuntime().gc(); 1485 } 1486 if (msg.obj != null) { 1487 @SuppressWarnings("unchecked") 1488 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1489 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1490 // Unload containers 1491 unloadAllContainers(args); 1492 } 1493 if (reportStatus) { 1494 try { 1495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1496 PackageHelper.getMountService().finishMediaUpdate(); 1497 } catch (RemoteException e) { 1498 Log.e(TAG, "MountService not running?"); 1499 } 1500 } 1501 } break; 1502 case WRITE_SETTINGS: { 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1504 synchronized (mPackages) { 1505 removeMessages(WRITE_SETTINGS); 1506 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1507 mSettings.writeLPr(); 1508 mDirtyUsers.clear(); 1509 } 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1511 } break; 1512 case WRITE_PACKAGE_RESTRICTIONS: { 1513 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1514 synchronized (mPackages) { 1515 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1516 for (int userId : mDirtyUsers) { 1517 mSettings.writePackageRestrictionsLPr(userId); 1518 } 1519 mDirtyUsers.clear(); 1520 } 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1522 } break; 1523 case CHECK_PENDING_VERIFICATION: { 1524 final int verificationId = msg.arg1; 1525 final PackageVerificationState state = mPendingVerification.get(verificationId); 1526 1527 if ((state != null) && !state.timeoutExtended()) { 1528 final InstallArgs args = state.getInstallArgs(); 1529 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1530 1531 Slog.i(TAG, "Verification timed out for " + originUri); 1532 mPendingVerification.remove(verificationId); 1533 1534 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1535 1536 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1537 Slog.i(TAG, "Continuing with installation of " + originUri); 1538 state.setVerifierResponse(Binder.getCallingUid(), 1539 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1540 broadcastPackageVerified(verificationId, originUri, 1541 PackageManager.VERIFICATION_ALLOW, 1542 state.getInstallArgs().getUser()); 1543 try { 1544 ret = args.copyApk(mContainerService, true); 1545 } catch (RemoteException e) { 1546 Slog.e(TAG, "Could not contact the ContainerService"); 1547 } 1548 } else { 1549 broadcastPackageVerified(verificationId, originUri, 1550 PackageManager.VERIFICATION_REJECT, 1551 state.getInstallArgs().getUser()); 1552 } 1553 1554 processPendingInstall(args, ret); 1555 mHandler.sendEmptyMessage(MCS_UNBIND); 1556 } 1557 Trace.asyncTraceEnd( 1558 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 1559 break; 1560 } 1561 case PACKAGE_VERIFIED: { 1562 final int verificationId = msg.arg1; 1563 1564 final PackageVerificationState state = mPendingVerification.get(verificationId); 1565 if (state == null) { 1566 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1567 break; 1568 } 1569 1570 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1571 1572 state.setVerifierResponse(response.callerUid, response.code); 1573 1574 if (state.isVerificationComplete()) { 1575 mPendingVerification.remove(verificationId); 1576 1577 final InstallArgs args = state.getInstallArgs(); 1578 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1579 1580 int ret; 1581 if (state.isInstallAllowed()) { 1582 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1583 broadcastPackageVerified(verificationId, originUri, 1584 response.code, state.getInstallArgs().getUser()); 1585 try { 1586 ret = args.copyApk(mContainerService, true); 1587 } catch (RemoteException e) { 1588 Slog.e(TAG, "Could not contact the ContainerService"); 1589 } 1590 } else { 1591 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1592 } 1593 1594 processPendingInstall(args, ret); 1595 1596 mHandler.sendEmptyMessage(MCS_UNBIND); 1597 } 1598 1599 break; 1600 } 1601 case START_INTENT_FILTER_VERIFICATIONS: { 1602 IFVerificationParams params = (IFVerificationParams) msg.obj; 1603 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1604 params.replacing, params.pkg); 1605 break; 1606 } 1607 case INTENT_FILTER_VERIFIED: { 1608 final int verificationId = msg.arg1; 1609 1610 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1611 verificationId); 1612 if (state == null) { 1613 Slog.w(TAG, "Invalid IntentFilter verification token " 1614 + verificationId + " received"); 1615 break; 1616 } 1617 1618 final int userId = state.getUserId(); 1619 1620 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1621 "Processing IntentFilter verification with token:" 1622 + verificationId + " and userId:" + userId); 1623 1624 final IntentFilterVerificationResponse response = 1625 (IntentFilterVerificationResponse) msg.obj; 1626 1627 state.setVerifierResponse(response.callerUid, response.code); 1628 1629 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1630 "IntentFilter verification with token:" + verificationId 1631 + " and userId:" + userId 1632 + " is settings verifier response with response code:" 1633 + response.code); 1634 1635 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1636 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1637 + response.getFailedDomainsString()); 1638 } 1639 1640 if (state.isVerificationComplete()) { 1641 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1642 } else { 1643 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1644 "IntentFilter verification with token:" + verificationId 1645 + " was not said to be complete"); 1646 } 1647 1648 break; 1649 } 1650 } 1651 } 1652 } 1653 1654 private StorageEventListener mStorageListener = new StorageEventListener() { 1655 @Override 1656 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1657 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1658 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1659 final String volumeUuid = vol.getFsUuid(); 1660 1661 // Clean up any users or apps that were removed or recreated 1662 // while this volume was missing 1663 reconcileUsers(volumeUuid); 1664 reconcileApps(volumeUuid); 1665 1666 // Clean up any install sessions that expired or were 1667 // cancelled while this volume was missing 1668 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1669 1670 loadPrivatePackages(vol); 1671 1672 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1673 unloadPrivatePackages(vol); 1674 } 1675 } 1676 1677 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1678 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1679 updateExternalMediaStatus(true, false); 1680 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1681 updateExternalMediaStatus(false, false); 1682 } 1683 } 1684 } 1685 1686 @Override 1687 public void onVolumeForgotten(String fsUuid) { 1688 if (TextUtils.isEmpty(fsUuid)) { 1689 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1690 return; 1691 } 1692 1693 // Remove any apps installed on the forgotten volume 1694 synchronized (mPackages) { 1695 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1696 for (PackageSetting ps : packages) { 1697 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1698 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1699 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1700 } 1701 1702 mSettings.onVolumeForgotten(fsUuid); 1703 mSettings.writeLPr(); 1704 } 1705 } 1706 }; 1707 1708 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1709 String[] grantedPermissions) { 1710 if (userId >= UserHandle.USER_OWNER) { 1711 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1712 } else if (userId == UserHandle.USER_ALL) { 1713 final int[] userIds; 1714 synchronized (mPackages) { 1715 userIds = UserManagerService.getInstance().getUserIds(); 1716 } 1717 for (int someUserId : userIds) { 1718 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1719 } 1720 } 1721 1722 // We could have touched GID membership, so flush out packages.list 1723 synchronized (mPackages) { 1724 mSettings.writePackageListLPr(); 1725 } 1726 } 1727 1728 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1729 String[] grantedPermissions) { 1730 SettingBase sb = (SettingBase) pkg.mExtras; 1731 if (sb == null) { 1732 return; 1733 } 1734 1735 PermissionsState permissionsState = sb.getPermissionsState(); 1736 1737 for (String permission : pkg.requestedPermissions) { 1738 BasePermission bp = mSettings.mPermissions.get(permission); 1739 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1740 || ArrayUtils.contains(grantedPermissions, permission))) { 1741 permissionsState.grantRuntimePermission(bp, userId); 1742 } 1743 } 1744 } 1745 1746 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1747 Bundle extras = null; 1748 switch (res.returnCode) { 1749 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1750 extras = new Bundle(); 1751 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1752 res.origPermission); 1753 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1754 res.origPackage); 1755 break; 1756 } 1757 case PackageManager.INSTALL_SUCCEEDED: { 1758 extras = new Bundle(); 1759 extras.putBoolean(Intent.EXTRA_REPLACING, 1760 res.removedInfo != null && res.removedInfo.removedPackage != null); 1761 break; 1762 } 1763 } 1764 return extras; 1765 } 1766 1767 void scheduleWriteSettingsLocked() { 1768 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1769 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1770 } 1771 } 1772 1773 void scheduleWritePackageRestrictionsLocked(int userId) { 1774 if (!sUserManager.exists(userId)) return; 1775 mDirtyUsers.add(userId); 1776 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1777 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1778 } 1779 } 1780 1781 public static PackageManagerService main(Context context, Installer installer, 1782 boolean factoryTest, boolean onlyCore) { 1783 PackageManagerService m = new PackageManagerService(context, installer, 1784 factoryTest, onlyCore); 1785 ServiceManager.addService("package", m); 1786 return m; 1787 } 1788 1789 static String[] splitString(String str, char sep) { 1790 int count = 1; 1791 int i = 0; 1792 while ((i=str.indexOf(sep, i)) >= 0) { 1793 count++; 1794 i++; 1795 } 1796 1797 String[] res = new String[count]; 1798 i=0; 1799 count = 0; 1800 int lastI=0; 1801 while ((i=str.indexOf(sep, i)) >= 0) { 1802 res[count] = str.substring(lastI, i); 1803 count++; 1804 i++; 1805 lastI = i; 1806 } 1807 res[count] = str.substring(lastI, str.length()); 1808 return res; 1809 } 1810 1811 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1812 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1813 Context.DISPLAY_SERVICE); 1814 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1815 } 1816 1817 public PackageManagerService(Context context, Installer installer, 1818 boolean factoryTest, boolean onlyCore) { 1819 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1820 SystemClock.uptimeMillis()); 1821 1822 if (mSdkVersion <= 0) { 1823 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1824 } 1825 1826 mContext = context; 1827 mFactoryTest = factoryTest; 1828 mOnlyCore = onlyCore; 1829 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1830 mMetrics = new DisplayMetrics(); 1831 mSettings = new Settings(mPackages); 1832 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1833 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1834 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1835 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1836 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1837 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1838 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1839 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1840 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1841 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1842 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1843 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1844 1845 // TODO: add a property to control this? 1846 long dexOptLRUThresholdInMinutes; 1847 if (mLazyDexOpt) { 1848 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1849 } else { 1850 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1851 } 1852 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1853 1854 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1855 if (separateProcesses != null && separateProcesses.length() > 0) { 1856 if ("*".equals(separateProcesses)) { 1857 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1858 mSeparateProcesses = null; 1859 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1860 } else { 1861 mDefParseFlags = 0; 1862 mSeparateProcesses = separateProcesses.split(","); 1863 Slog.w(TAG, "Running with debug.separate_processes: " 1864 + separateProcesses); 1865 } 1866 } else { 1867 mDefParseFlags = 0; 1868 mSeparateProcesses = null; 1869 } 1870 1871 mInstaller = installer; 1872 mPackageDexOptimizer = new PackageDexOptimizer(this); 1873 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1874 1875 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1876 FgThread.get().getLooper()); 1877 1878 getDefaultDisplayMetrics(context, mMetrics); 1879 1880 SystemConfig systemConfig = SystemConfig.getInstance(); 1881 mGlobalGids = systemConfig.getGlobalGids(); 1882 mSystemPermissions = systemConfig.getSystemPermissions(); 1883 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1884 1885 synchronized (mInstallLock) { 1886 // writer 1887 synchronized (mPackages) { 1888 mHandlerThread = new ServiceThread(TAG, 1889 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1890 mHandlerThread.start(); 1891 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1892 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1893 1894 File dataDir = Environment.getDataDirectory(); 1895 mAppDataDir = new File(dataDir, "data"); 1896 mAppInstallDir = new File(dataDir, "app"); 1897 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1898 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1899 mUserAppDataDir = new File(dataDir, "user"); 1900 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1901 1902 sUserManager = new UserManagerService(context, this, 1903 mInstallLock, mPackages); 1904 1905 // Propagate permission configuration in to package manager. 1906 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1907 = systemConfig.getPermissions(); 1908 for (int i=0; i<permConfig.size(); i++) { 1909 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1910 BasePermission bp = mSettings.mPermissions.get(perm.name); 1911 if (bp == null) { 1912 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1913 mSettings.mPermissions.put(perm.name, bp); 1914 } 1915 if (perm.gids != null) { 1916 bp.setGids(perm.gids, perm.perUser); 1917 } 1918 } 1919 1920 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1921 for (int i=0; i<libConfig.size(); i++) { 1922 mSharedLibraries.put(libConfig.keyAt(i), 1923 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1924 } 1925 1926 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1927 1928 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1929 1930 String customResolverActivity = Resources.getSystem().getString( 1931 R.string.config_customResolverActivity); 1932 if (TextUtils.isEmpty(customResolverActivity)) { 1933 customResolverActivity = null; 1934 } else { 1935 mCustomResolverComponentName = ComponentName.unflattenFromString( 1936 customResolverActivity); 1937 } 1938 1939 long startTime = SystemClock.uptimeMillis(); 1940 1941 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1942 startTime); 1943 1944 // Set flag to monitor and not change apk file paths when 1945 // scanning install directories. 1946 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1947 1948 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1949 1950 /** 1951 * Add everything in the in the boot class path to the 1952 * list of process files because dexopt will have been run 1953 * if necessary during zygote startup. 1954 */ 1955 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1956 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1957 1958 if (bootClassPath != null) { 1959 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1960 for (String element : bootClassPathElements) { 1961 alreadyDexOpted.add(element); 1962 } 1963 } else { 1964 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1965 } 1966 1967 if (systemServerClassPath != null) { 1968 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1969 for (String element : systemServerClassPathElements) { 1970 alreadyDexOpted.add(element); 1971 } 1972 } else { 1973 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1974 } 1975 1976 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1977 final String[] dexCodeInstructionSets = 1978 getDexCodeInstructionSets( 1979 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1980 1981 /** 1982 * Ensure all external libraries have had dexopt run on them. 1983 */ 1984 if (mSharedLibraries.size() > 0) { 1985 // NOTE: For now, we're compiling these system "shared libraries" 1986 // (and framework jars) into all available architectures. It's possible 1987 // to compile them only when we come across an app that uses them (there's 1988 // already logic for that in scanPackageLI) but that adds some complexity. 1989 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1990 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1991 final String lib = libEntry.path; 1992 if (lib == null) { 1993 continue; 1994 } 1995 1996 try { 1997 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1998 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1999 alreadyDexOpted.add(lib); 2000 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2001 } 2002 } catch (FileNotFoundException e) { 2003 Slog.w(TAG, "Library not found: " + lib); 2004 } catch (IOException e) { 2005 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2006 + e.getMessage()); 2007 } 2008 } 2009 } 2010 } 2011 2012 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2013 2014 // Gross hack for now: we know this file doesn't contain any 2015 // code, so don't dexopt it to avoid the resulting log spew. 2016 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2017 2018 // Gross hack for now: we know this file is only part of 2019 // the boot class path for art, so don't dexopt it to 2020 // avoid the resulting log spew. 2021 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2022 2023 /** 2024 * There are a number of commands implemented in Java, which 2025 * we currently need to do the dexopt on so that they can be 2026 * run from a non-root shell. 2027 */ 2028 String[] frameworkFiles = frameworkDir.list(); 2029 if (frameworkFiles != null) { 2030 // TODO: We could compile these only for the most preferred ABI. We should 2031 // first double check that the dex files for these commands are not referenced 2032 // by other system apps. 2033 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2034 for (int i=0; i<frameworkFiles.length; i++) { 2035 File libPath = new File(frameworkDir, frameworkFiles[i]); 2036 String path = libPath.getPath(); 2037 // Skip the file if we already did it. 2038 if (alreadyDexOpted.contains(path)) { 2039 continue; 2040 } 2041 // Skip the file if it is not a type we want to dexopt. 2042 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2043 continue; 2044 } 2045 try { 2046 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2047 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2048 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2049 } 2050 } catch (FileNotFoundException e) { 2051 Slog.w(TAG, "Jar not found: " + path); 2052 } catch (IOException e) { 2053 Slog.w(TAG, "Exception reading jar: " + path, e); 2054 } 2055 } 2056 } 2057 } 2058 2059 final VersionInfo ver = mSettings.getInternalVersion(); 2060 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2061 // when upgrading from pre-M, promote system app permissions from install to runtime 2062 mPromoteSystemApps = 2063 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2064 2065 // save off the names of pre-existing system packages prior to scanning; we don't 2066 // want to automatically grant runtime permissions for new system apps 2067 if (mPromoteSystemApps) { 2068 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2069 while (pkgSettingIter.hasNext()) { 2070 PackageSetting ps = pkgSettingIter.next(); 2071 if (isSystemApp(ps)) { 2072 mExistingSystemPackages.add(ps.name); 2073 } 2074 } 2075 } 2076 2077 // Collect vendor overlay packages. 2078 // (Do this before scanning any apps.) 2079 // For security and version matching reason, only consider 2080 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2081 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2082 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2083 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2084 2085 // Find base frameworks (resource packages without code). 2086 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2087 | PackageParser.PARSE_IS_SYSTEM_DIR 2088 | PackageParser.PARSE_IS_PRIVILEGED, 2089 scanFlags | SCAN_NO_DEX, 0); 2090 2091 // Collected privileged system packages. 2092 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2093 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2094 | PackageParser.PARSE_IS_SYSTEM_DIR 2095 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2096 2097 // Collect ordinary system packages. 2098 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2099 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2100 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2101 2102 // Collect all vendor packages. 2103 File vendorAppDir = new File("/vendor/app"); 2104 try { 2105 vendorAppDir = vendorAppDir.getCanonicalFile(); 2106 } catch (IOException e) { 2107 // failed to look up canonical path, continue with original one 2108 } 2109 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2110 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2111 2112 // Collect all OEM packages. 2113 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2114 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2116 2117 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2118 mInstaller.moveFiles(); 2119 2120 // Prune any system packages that no longer exist. 2121 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2122 if (!mOnlyCore) { 2123 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2124 while (psit.hasNext()) { 2125 PackageSetting ps = psit.next(); 2126 2127 /* 2128 * If this is not a system app, it can't be a 2129 * disable system app. 2130 */ 2131 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2132 continue; 2133 } 2134 2135 /* 2136 * If the package is scanned, it's not erased. 2137 */ 2138 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2139 if (scannedPkg != null) { 2140 /* 2141 * If the system app is both scanned and in the 2142 * disabled packages list, then it must have been 2143 * added via OTA. Remove it from the currently 2144 * scanned package so the previously user-installed 2145 * application can be scanned. 2146 */ 2147 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2148 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2149 + ps.name + "; removing system app. Last known codePath=" 2150 + ps.codePathString + ", installStatus=" + ps.installStatus 2151 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2152 + scannedPkg.mVersionCode); 2153 removePackageLI(ps, true); 2154 mExpectingBetter.put(ps.name, ps.codePath); 2155 } 2156 2157 continue; 2158 } 2159 2160 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2161 psit.remove(); 2162 logCriticalInfo(Log.WARN, "System package " + ps.name 2163 + " no longer exists; wiping its data"); 2164 removeDataDirsLI(null, ps.name); 2165 } else { 2166 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2167 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2168 possiblyDeletedUpdatedSystemApps.add(ps.name); 2169 } 2170 } 2171 } 2172 } 2173 2174 //look for any incomplete package installations 2175 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2176 //clean up list 2177 for(int i = 0; i < deletePkgsList.size(); i++) { 2178 //clean up here 2179 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2180 } 2181 //delete tmp files 2182 deleteTempPackageFiles(); 2183 2184 // Remove any shared userIDs that have no associated packages 2185 mSettings.pruneSharedUsersLPw(); 2186 2187 if (!mOnlyCore) { 2188 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2189 SystemClock.uptimeMillis()); 2190 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2191 2192 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2193 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2194 2195 /** 2196 * Remove disable package settings for any updated system 2197 * apps that were removed via an OTA. If they're not a 2198 * previously-updated app, remove them completely. 2199 * Otherwise, just revoke their system-level permissions. 2200 */ 2201 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2202 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2203 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2204 2205 String msg; 2206 if (deletedPkg == null) { 2207 msg = "Updated system package " + deletedAppName 2208 + " no longer exists; wiping its data"; 2209 removeDataDirsLI(null, deletedAppName); 2210 } else { 2211 msg = "Updated system app + " + deletedAppName 2212 + " no longer present; removing system privileges for " 2213 + deletedAppName; 2214 2215 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2216 2217 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2218 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2219 } 2220 logCriticalInfo(Log.WARN, msg); 2221 } 2222 2223 /** 2224 * Make sure all system apps that we expected to appear on 2225 * the userdata partition actually showed up. If they never 2226 * appeared, crawl back and revive the system version. 2227 */ 2228 for (int i = 0; i < mExpectingBetter.size(); i++) { 2229 final String packageName = mExpectingBetter.keyAt(i); 2230 if (!mPackages.containsKey(packageName)) { 2231 final File scanFile = mExpectingBetter.valueAt(i); 2232 2233 logCriticalInfo(Log.WARN, "Expected better " + packageName 2234 + " but never showed up; reverting to system"); 2235 2236 final int reparseFlags; 2237 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2238 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2239 | PackageParser.PARSE_IS_SYSTEM_DIR 2240 | PackageParser.PARSE_IS_PRIVILEGED; 2241 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2242 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2243 | PackageParser.PARSE_IS_SYSTEM_DIR; 2244 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2245 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2246 | PackageParser.PARSE_IS_SYSTEM_DIR; 2247 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2248 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2249 | PackageParser.PARSE_IS_SYSTEM_DIR; 2250 } else { 2251 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2252 continue; 2253 } 2254 2255 mSettings.enableSystemPackageLPw(packageName); 2256 2257 try { 2258 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2259 } catch (PackageManagerException e) { 2260 Slog.e(TAG, "Failed to parse original system package: " 2261 + e.getMessage()); 2262 } 2263 } 2264 } 2265 } 2266 mExpectingBetter.clear(); 2267 2268 // Now that we know all of the shared libraries, update all clients to have 2269 // the correct library paths. 2270 updateAllSharedLibrariesLPw(); 2271 2272 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2273 // NOTE: We ignore potential failures here during a system scan (like 2274 // the rest of the commands above) because there's precious little we 2275 // can do about it. A settings error is reported, though. 2276 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2277 false /* force dexopt */, false /* defer dexopt */); 2278 } 2279 2280 // Now that we know all the packages we are keeping, 2281 // read and update their last usage times. 2282 mPackageUsage.readLP(); 2283 2284 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2285 SystemClock.uptimeMillis()); 2286 Slog.i(TAG, "Time to scan packages: " 2287 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2288 + " seconds"); 2289 2290 // If the platform SDK has changed since the last time we booted, 2291 // we need to re-grant app permission to catch any new ones that 2292 // appear. This is really a hack, and means that apps can in some 2293 // cases get permissions that the user didn't initially explicitly 2294 // allow... it would be nice to have some better way to handle 2295 // this situation. 2296 int updateFlags = UPDATE_PERMISSIONS_ALL; 2297 if (ver.sdkVersion != mSdkVersion) { 2298 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2299 + mSdkVersion + "; regranting permissions for internal storage"); 2300 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2301 } 2302 updatePermissionsLPw(null, null, updateFlags); 2303 ver.sdkVersion = mSdkVersion; 2304 // clear only after permissions have been updated 2305 mExistingSystemPackages.clear(); 2306 mPromoteSystemApps = false; 2307 2308 // If this is the first boot, and it is a normal boot, then 2309 // we need to initialize the default preferred apps. 2310 if (!mRestoredSettings && !onlyCore) { 2311 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2312 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2313 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2314 } 2315 2316 // If this is first boot after an OTA, and a normal boot, then 2317 // we need to clear code cache directories. 2318 if (mIsUpgrade && !onlyCore) { 2319 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2320 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2321 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2322 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2323 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2324 } 2325 } 2326 ver.fingerprint = Build.FINGERPRINT; 2327 } 2328 2329 checkDefaultBrowser(); 2330 2331 // All the changes are done during package scanning. 2332 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2333 2334 // can downgrade to reader 2335 mSettings.writeLPr(); 2336 2337 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2338 SystemClock.uptimeMillis()); 2339 2340 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2341 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2342 2343 mInstallerService = new PackageInstallerService(context, this); 2344 2345 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2346 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2347 mIntentFilterVerifierComponent); 2348 2349 } // synchronized (mPackages) 2350 } // synchronized (mInstallLock) 2351 2352 // Now after opening every single application zip, make sure they 2353 // are all flushed. Not really needed, but keeps things nice and 2354 // tidy. 2355 Runtime.getRuntime().gc(); 2356 2357 // Expose private service for system components to use. 2358 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2359 } 2360 2361 @Override 2362 public boolean isFirstBoot() { 2363 return !mRestoredSettings; 2364 } 2365 2366 @Override 2367 public boolean isOnlyCoreApps() { 2368 return mOnlyCore; 2369 } 2370 2371 @Override 2372 public boolean isUpgrade() { 2373 return mIsUpgrade; 2374 } 2375 2376 private String getRequiredVerifierLPr() { 2377 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2378 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2379 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2380 2381 String requiredVerifier = null; 2382 2383 final int N = receivers.size(); 2384 for (int i = 0; i < N; i++) { 2385 final ResolveInfo info = receivers.get(i); 2386 2387 if (info.activityInfo == null) { 2388 continue; 2389 } 2390 2391 final String packageName = info.activityInfo.packageName; 2392 2393 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2394 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2395 continue; 2396 } 2397 2398 if (requiredVerifier != null) { 2399 throw new RuntimeException("There can be only one required verifier"); 2400 } 2401 2402 requiredVerifier = packageName; 2403 } 2404 2405 return requiredVerifier; 2406 } 2407 2408 private String getRequiredInstallerLPr() { 2409 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2410 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2411 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2412 2413 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2414 PACKAGE_MIME_TYPE, 0, 0); 2415 2416 String requiredInstaller = null; 2417 2418 final int N = installers.size(); 2419 for (int i = 0; i < N; i++) { 2420 final ResolveInfo info = installers.get(i); 2421 final String packageName = info.activityInfo.packageName; 2422 2423 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2424 continue; 2425 } 2426 2427 if (requiredInstaller != null) { 2428 throw new RuntimeException("There must be one required installer"); 2429 } 2430 2431 requiredInstaller = packageName; 2432 } 2433 2434 if (requiredInstaller == null) { 2435 throw new RuntimeException("There must be one required installer"); 2436 } 2437 2438 return requiredInstaller; 2439 } 2440 2441 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2442 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2443 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2444 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2445 2446 ComponentName verifierComponentName = null; 2447 2448 int priority = -1000; 2449 final int N = receivers.size(); 2450 for (int i = 0; i < N; i++) { 2451 final ResolveInfo info = receivers.get(i); 2452 2453 if (info.activityInfo == null) { 2454 continue; 2455 } 2456 2457 final String packageName = info.activityInfo.packageName; 2458 2459 final PackageSetting ps = mSettings.mPackages.get(packageName); 2460 if (ps == null) { 2461 continue; 2462 } 2463 2464 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2465 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2466 continue; 2467 } 2468 2469 // Select the IntentFilterVerifier with the highest priority 2470 if (priority < info.priority) { 2471 priority = info.priority; 2472 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2473 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2474 + verifierComponentName + " with priority: " + info.priority); 2475 } 2476 } 2477 2478 return verifierComponentName; 2479 } 2480 2481 private void primeDomainVerificationsLPw(int userId) { 2482 if (DEBUG_DOMAIN_VERIFICATION) { 2483 Slog.d(TAG, "Priming domain verifications in user " + userId); 2484 } 2485 2486 SystemConfig systemConfig = SystemConfig.getInstance(); 2487 ArraySet<String> packages = systemConfig.getLinkedApps(); 2488 ArraySet<String> domains = new ArraySet<String>(); 2489 2490 for (String packageName : packages) { 2491 PackageParser.Package pkg = mPackages.get(packageName); 2492 if (pkg != null) { 2493 if (!pkg.isSystemApp()) { 2494 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2495 continue; 2496 } 2497 2498 domains.clear(); 2499 for (PackageParser.Activity a : pkg.activities) { 2500 for (ActivityIntentInfo filter : a.intents) { 2501 if (hasValidDomains(filter)) { 2502 domains.addAll(filter.getHostsList()); 2503 } 2504 } 2505 } 2506 2507 if (domains.size() > 0) { 2508 if (DEBUG_DOMAIN_VERIFICATION) { 2509 Slog.v(TAG, " + " + packageName); 2510 } 2511 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2512 // state w.r.t. the formal app-linkage "no verification attempted" state; 2513 // and then 'always' in the per-user state actually used for intent resolution. 2514 final IntentFilterVerificationInfo ivi; 2515 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2516 new ArrayList<String>(domains)); 2517 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2518 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2519 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2520 } else { 2521 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2522 + "' does not handle web links"); 2523 } 2524 } else { 2525 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2526 } 2527 } 2528 2529 scheduleWritePackageRestrictionsLocked(userId); 2530 scheduleWriteSettingsLocked(); 2531 } 2532 2533 private void applyFactoryDefaultBrowserLPw(int userId) { 2534 // The default browser app's package name is stored in a string resource, 2535 // with a product-specific overlay used for vendor customization. 2536 String browserPkg = mContext.getResources().getString( 2537 com.android.internal.R.string.default_browser); 2538 if (!TextUtils.isEmpty(browserPkg)) { 2539 // non-empty string => required to be a known package 2540 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2541 if (ps == null) { 2542 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2543 browserPkg = null; 2544 } else { 2545 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2546 } 2547 } 2548 2549 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2550 // default. If there's more than one, just leave everything alone. 2551 if (browserPkg == null) { 2552 calculateDefaultBrowserLPw(userId); 2553 } 2554 } 2555 2556 private void calculateDefaultBrowserLPw(int userId) { 2557 List<String> allBrowsers = resolveAllBrowserApps(userId); 2558 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2559 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2560 } 2561 2562 private List<String> resolveAllBrowserApps(int userId) { 2563 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2564 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2565 PackageManager.MATCH_ALL, userId); 2566 2567 final int count = list.size(); 2568 List<String> result = new ArrayList<String>(count); 2569 for (int i=0; i<count; i++) { 2570 ResolveInfo info = list.get(i); 2571 if (info.activityInfo == null 2572 || !info.handleAllWebDataURI 2573 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2574 || result.contains(info.activityInfo.packageName)) { 2575 continue; 2576 } 2577 result.add(info.activityInfo.packageName); 2578 } 2579 2580 return result; 2581 } 2582 2583 private boolean packageIsBrowser(String packageName, int userId) { 2584 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2585 PackageManager.MATCH_ALL, userId); 2586 final int N = list.size(); 2587 for (int i = 0; i < N; i++) { 2588 ResolveInfo info = list.get(i); 2589 if (packageName.equals(info.activityInfo.packageName)) { 2590 return true; 2591 } 2592 } 2593 return false; 2594 } 2595 2596 private void checkDefaultBrowser() { 2597 final int myUserId = UserHandle.myUserId(); 2598 final String packageName = getDefaultBrowserPackageName(myUserId); 2599 if (packageName != null) { 2600 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2601 if (info == null) { 2602 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2603 synchronized (mPackages) { 2604 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2605 } 2606 } 2607 } 2608 } 2609 2610 @Override 2611 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2612 throws RemoteException { 2613 try { 2614 return super.onTransact(code, data, reply, flags); 2615 } catch (RuntimeException e) { 2616 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2617 Slog.wtf(TAG, "Package Manager Crash", e); 2618 } 2619 throw e; 2620 } 2621 } 2622 2623 void cleanupInstallFailedPackage(PackageSetting ps) { 2624 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2625 2626 removeDataDirsLI(ps.volumeUuid, ps.name); 2627 if (ps.codePath != null) { 2628 if (ps.codePath.isDirectory()) { 2629 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2630 } else { 2631 ps.codePath.delete(); 2632 } 2633 } 2634 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2635 if (ps.resourcePath.isDirectory()) { 2636 FileUtils.deleteContents(ps.resourcePath); 2637 } 2638 ps.resourcePath.delete(); 2639 } 2640 mSettings.removePackageLPw(ps.name); 2641 } 2642 2643 static int[] appendInts(int[] cur, int[] add) { 2644 if (add == null) return cur; 2645 if (cur == null) return add; 2646 final int N = add.length; 2647 for (int i=0; i<N; i++) { 2648 cur = appendInt(cur, add[i]); 2649 } 2650 return cur; 2651 } 2652 2653 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2654 if (!sUserManager.exists(userId)) return null; 2655 final PackageSetting ps = (PackageSetting) p.mExtras; 2656 if (ps == null) { 2657 return null; 2658 } 2659 2660 final PermissionsState permissionsState = ps.getPermissionsState(); 2661 2662 final int[] gids = permissionsState.computeGids(userId); 2663 final Set<String> permissions = permissionsState.getPermissions(userId); 2664 final PackageUserState state = ps.readUserState(userId); 2665 2666 return PackageParser.generatePackageInfo(p, gids, flags, 2667 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2668 } 2669 2670 @Override 2671 public boolean isPackageFrozen(String packageName) { 2672 synchronized (mPackages) { 2673 final PackageSetting ps = mSettings.mPackages.get(packageName); 2674 if (ps != null) { 2675 return ps.frozen; 2676 } 2677 } 2678 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2679 return true; 2680 } 2681 2682 @Override 2683 public boolean isPackageAvailable(String packageName, int userId) { 2684 if (!sUserManager.exists(userId)) return false; 2685 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2686 synchronized (mPackages) { 2687 PackageParser.Package p = mPackages.get(packageName); 2688 if (p != null) { 2689 final PackageSetting ps = (PackageSetting) p.mExtras; 2690 if (ps != null) { 2691 final PackageUserState state = ps.readUserState(userId); 2692 if (state != null) { 2693 return PackageParser.isAvailable(state); 2694 } 2695 } 2696 } 2697 } 2698 return false; 2699 } 2700 2701 @Override 2702 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2703 if (!sUserManager.exists(userId)) return null; 2704 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2705 // reader 2706 synchronized (mPackages) { 2707 PackageParser.Package p = mPackages.get(packageName); 2708 if (DEBUG_PACKAGE_INFO) 2709 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2710 if (p != null) { 2711 return generatePackageInfo(p, flags, userId); 2712 } 2713 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2714 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2715 } 2716 } 2717 return null; 2718 } 2719 2720 @Override 2721 public String[] currentToCanonicalPackageNames(String[] names) { 2722 String[] out = new String[names.length]; 2723 // reader 2724 synchronized (mPackages) { 2725 for (int i=names.length-1; i>=0; i--) { 2726 PackageSetting ps = mSettings.mPackages.get(names[i]); 2727 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2728 } 2729 } 2730 return out; 2731 } 2732 2733 @Override 2734 public String[] canonicalToCurrentPackageNames(String[] names) { 2735 String[] out = new String[names.length]; 2736 // reader 2737 synchronized (mPackages) { 2738 for (int i=names.length-1; i>=0; i--) { 2739 String cur = mSettings.mRenamedPackages.get(names[i]); 2740 out[i] = cur != null ? cur : names[i]; 2741 } 2742 } 2743 return out; 2744 } 2745 2746 @Override 2747 public int getPackageUid(String packageName, int userId) { 2748 if (!sUserManager.exists(userId)) return -1; 2749 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2750 2751 // reader 2752 synchronized (mPackages) { 2753 PackageParser.Package p = mPackages.get(packageName); 2754 if(p != null) { 2755 return UserHandle.getUid(userId, p.applicationInfo.uid); 2756 } 2757 PackageSetting ps = mSettings.mPackages.get(packageName); 2758 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2759 return -1; 2760 } 2761 p = ps.pkg; 2762 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2763 } 2764 } 2765 2766 @Override 2767 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2768 if (!sUserManager.exists(userId)) { 2769 return null; 2770 } 2771 2772 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2773 "getPackageGids"); 2774 2775 // reader 2776 synchronized (mPackages) { 2777 PackageParser.Package p = mPackages.get(packageName); 2778 if (DEBUG_PACKAGE_INFO) { 2779 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2780 } 2781 if (p != null) { 2782 PackageSetting ps = (PackageSetting) p.mExtras; 2783 return ps.getPermissionsState().computeGids(userId); 2784 } 2785 } 2786 2787 return null; 2788 } 2789 2790 static PermissionInfo generatePermissionInfo( 2791 BasePermission bp, int flags) { 2792 if (bp.perm != null) { 2793 return PackageParser.generatePermissionInfo(bp.perm, flags); 2794 } 2795 PermissionInfo pi = new PermissionInfo(); 2796 pi.name = bp.name; 2797 pi.packageName = bp.sourcePackage; 2798 pi.nonLocalizedLabel = bp.name; 2799 pi.protectionLevel = bp.protectionLevel; 2800 return pi; 2801 } 2802 2803 @Override 2804 public PermissionInfo getPermissionInfo(String name, int flags) { 2805 // reader 2806 synchronized (mPackages) { 2807 final BasePermission p = mSettings.mPermissions.get(name); 2808 if (p != null) { 2809 return generatePermissionInfo(p, flags); 2810 } 2811 return null; 2812 } 2813 } 2814 2815 @Override 2816 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2817 // reader 2818 synchronized (mPackages) { 2819 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2820 for (BasePermission p : mSettings.mPermissions.values()) { 2821 if (group == null) { 2822 if (p.perm == null || p.perm.info.group == null) { 2823 out.add(generatePermissionInfo(p, flags)); 2824 } 2825 } else { 2826 if (p.perm != null && group.equals(p.perm.info.group)) { 2827 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2828 } 2829 } 2830 } 2831 2832 if (out.size() > 0) { 2833 return out; 2834 } 2835 return mPermissionGroups.containsKey(group) ? out : null; 2836 } 2837 } 2838 2839 @Override 2840 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2841 // reader 2842 synchronized (mPackages) { 2843 return PackageParser.generatePermissionGroupInfo( 2844 mPermissionGroups.get(name), flags); 2845 } 2846 } 2847 2848 @Override 2849 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2850 // reader 2851 synchronized (mPackages) { 2852 final int N = mPermissionGroups.size(); 2853 ArrayList<PermissionGroupInfo> out 2854 = new ArrayList<PermissionGroupInfo>(N); 2855 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2856 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2857 } 2858 return out; 2859 } 2860 } 2861 2862 private ApplicationInfo generateApplicationInfoFromSettingsLPw(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 if (ps.pkg == null) { 2868 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2869 flags, userId); 2870 if (pInfo != null) { 2871 return pInfo.applicationInfo; 2872 } 2873 return null; 2874 } 2875 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2876 ps.readUserState(userId), userId); 2877 } 2878 return null; 2879 } 2880 2881 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2882 int userId) { 2883 if (!sUserManager.exists(userId)) return null; 2884 PackageSetting ps = mSettings.mPackages.get(packageName); 2885 if (ps != null) { 2886 PackageParser.Package pkg = ps.pkg; 2887 if (pkg == null) { 2888 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2889 return null; 2890 } 2891 // Only data remains, so we aren't worried about code paths 2892 pkg = new PackageParser.Package(packageName); 2893 pkg.applicationInfo.packageName = packageName; 2894 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2895 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2896 pkg.applicationInfo.dataDir = Environment 2897 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2898 .getAbsolutePath(); 2899 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2900 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2901 } 2902 return generatePackageInfo(pkg, flags, userId); 2903 } 2904 return null; 2905 } 2906 2907 @Override 2908 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2911 // writer 2912 synchronized (mPackages) { 2913 PackageParser.Package p = mPackages.get(packageName); 2914 if (DEBUG_PACKAGE_INFO) Log.v( 2915 TAG, "getApplicationInfo " + packageName 2916 + ": " + p); 2917 if (p != null) { 2918 PackageSetting ps = mSettings.mPackages.get(packageName); 2919 if (ps == null) return null; 2920 // Note: isEnabledLP() does not apply here - always return info 2921 return PackageParser.generateApplicationInfo( 2922 p, flags, ps.readUserState(userId), userId); 2923 } 2924 if ("android".equals(packageName)||"system".equals(packageName)) { 2925 return mAndroidApplication; 2926 } 2927 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2928 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2929 } 2930 } 2931 return null; 2932 } 2933 2934 @Override 2935 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2936 final IPackageDataObserver observer) { 2937 mContext.enforceCallingOrSelfPermission( 2938 android.Manifest.permission.CLEAR_APP_CACHE, null); 2939 // Queue up an async operation since clearing cache may take a little while. 2940 mHandler.post(new Runnable() { 2941 public void run() { 2942 mHandler.removeCallbacks(this); 2943 int retCode = -1; 2944 synchronized (mInstallLock) { 2945 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2946 if (retCode < 0) { 2947 Slog.w(TAG, "Couldn't clear application caches"); 2948 } 2949 } 2950 if (observer != null) { 2951 try { 2952 observer.onRemoveCompleted(null, (retCode >= 0)); 2953 } catch (RemoteException e) { 2954 Slog.w(TAG, "RemoveException when invoking call back"); 2955 } 2956 } 2957 } 2958 }); 2959 } 2960 2961 @Override 2962 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2963 final IntentSender pi) { 2964 mContext.enforceCallingOrSelfPermission( 2965 android.Manifest.permission.CLEAR_APP_CACHE, null); 2966 // Queue up an async operation since clearing cache may take a little while. 2967 mHandler.post(new Runnable() { 2968 public void run() { 2969 mHandler.removeCallbacks(this); 2970 int retCode = -1; 2971 synchronized (mInstallLock) { 2972 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2973 if (retCode < 0) { 2974 Slog.w(TAG, "Couldn't clear application caches"); 2975 } 2976 } 2977 if(pi != null) { 2978 try { 2979 // Callback via pending intent 2980 int code = (retCode >= 0) ? 1 : 0; 2981 pi.sendIntent(null, code, null, 2982 null, null); 2983 } catch (SendIntentException e1) { 2984 Slog.i(TAG, "Failed to send pending intent"); 2985 } 2986 } 2987 } 2988 }); 2989 } 2990 2991 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2992 synchronized (mInstallLock) { 2993 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2994 throw new IOException("Failed to free enough space"); 2995 } 2996 } 2997 } 2998 2999 @Override 3000 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3001 if (!sUserManager.exists(userId)) return null; 3002 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3003 synchronized (mPackages) { 3004 PackageParser.Activity a = mActivities.mActivities.get(component); 3005 3006 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3007 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3008 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3009 if (ps == null) return null; 3010 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3011 userId); 3012 } 3013 if (mResolveComponentName.equals(component)) { 3014 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3015 new PackageUserState(), userId); 3016 } 3017 } 3018 return null; 3019 } 3020 3021 @Override 3022 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3023 String resolvedType) { 3024 synchronized (mPackages) { 3025 if (component.equals(mResolveComponentName)) { 3026 // The resolver supports EVERYTHING! 3027 return true; 3028 } 3029 PackageParser.Activity a = mActivities.mActivities.get(component); 3030 if (a == null) { 3031 return false; 3032 } 3033 for (int i=0; i<a.intents.size(); i++) { 3034 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3035 intent.getData(), intent.getCategories(), TAG) >= 0) { 3036 return true; 3037 } 3038 } 3039 return false; 3040 } 3041 } 3042 3043 @Override 3044 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3045 if (!sUserManager.exists(userId)) return null; 3046 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3047 synchronized (mPackages) { 3048 PackageParser.Activity a = mReceivers.mActivities.get(component); 3049 if (DEBUG_PACKAGE_INFO) Log.v( 3050 TAG, "getReceiverInfo " + component + ": " + a); 3051 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3052 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3053 if (ps == null) return null; 3054 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3055 userId); 3056 } 3057 } 3058 return null; 3059 } 3060 3061 @Override 3062 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3063 if (!sUserManager.exists(userId)) return null; 3064 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3065 synchronized (mPackages) { 3066 PackageParser.Service s = mServices.mServices.get(component); 3067 if (DEBUG_PACKAGE_INFO) Log.v( 3068 TAG, "getServiceInfo " + component + ": " + s); 3069 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3070 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3071 if (ps == null) return null; 3072 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3073 userId); 3074 } 3075 } 3076 return null; 3077 } 3078 3079 @Override 3080 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3081 if (!sUserManager.exists(userId)) return null; 3082 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3083 synchronized (mPackages) { 3084 PackageParser.Provider p = mProviders.mProviders.get(component); 3085 if (DEBUG_PACKAGE_INFO) Log.v( 3086 TAG, "getProviderInfo " + component + ": " + p); 3087 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3088 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3089 if (ps == null) return null; 3090 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3091 userId); 3092 } 3093 } 3094 return null; 3095 } 3096 3097 @Override 3098 public String[] getSystemSharedLibraryNames() { 3099 Set<String> libSet; 3100 synchronized (mPackages) { 3101 libSet = mSharedLibraries.keySet(); 3102 int size = libSet.size(); 3103 if (size > 0) { 3104 String[] libs = new String[size]; 3105 libSet.toArray(libs); 3106 return libs; 3107 } 3108 } 3109 return null; 3110 } 3111 3112 /** 3113 * @hide 3114 */ 3115 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3116 synchronized (mPackages) { 3117 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3118 if (lib != null && lib.apk != null) { 3119 return mPackages.get(lib.apk); 3120 } 3121 } 3122 return null; 3123 } 3124 3125 @Override 3126 public FeatureInfo[] getSystemAvailableFeatures() { 3127 Collection<FeatureInfo> featSet; 3128 synchronized (mPackages) { 3129 featSet = mAvailableFeatures.values(); 3130 int size = featSet.size(); 3131 if (size > 0) { 3132 FeatureInfo[] features = new FeatureInfo[size+1]; 3133 featSet.toArray(features); 3134 FeatureInfo fi = new FeatureInfo(); 3135 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3136 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3137 features[size] = fi; 3138 return features; 3139 } 3140 } 3141 return null; 3142 } 3143 3144 @Override 3145 public boolean hasSystemFeature(String name) { 3146 synchronized (mPackages) { 3147 return mAvailableFeatures.containsKey(name); 3148 } 3149 } 3150 3151 private void checkValidCaller(int uid, int userId) { 3152 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3153 return; 3154 3155 throw new SecurityException("Caller uid=" + uid 3156 + " is not privileged to communicate with user=" + userId); 3157 } 3158 3159 @Override 3160 public int checkPermission(String permName, String pkgName, int userId) { 3161 if (!sUserManager.exists(userId)) { 3162 return PackageManager.PERMISSION_DENIED; 3163 } 3164 3165 synchronized (mPackages) { 3166 final PackageParser.Package p = mPackages.get(pkgName); 3167 if (p != null && p.mExtras != null) { 3168 final PackageSetting ps = (PackageSetting) p.mExtras; 3169 final PermissionsState permissionsState = ps.getPermissionsState(); 3170 if (permissionsState.hasPermission(permName, userId)) { 3171 return PackageManager.PERMISSION_GRANTED; 3172 } 3173 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3174 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3175 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3176 return PackageManager.PERMISSION_GRANTED; 3177 } 3178 } 3179 } 3180 3181 return PackageManager.PERMISSION_DENIED; 3182 } 3183 3184 @Override 3185 public int checkUidPermission(String permName, int uid) { 3186 final int userId = UserHandle.getUserId(uid); 3187 3188 if (!sUserManager.exists(userId)) { 3189 return PackageManager.PERMISSION_DENIED; 3190 } 3191 3192 synchronized (mPackages) { 3193 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3194 if (obj != null) { 3195 final SettingBase ps = (SettingBase) obj; 3196 final PermissionsState permissionsState = ps.getPermissionsState(); 3197 if (permissionsState.hasPermission(permName, userId)) { 3198 return PackageManager.PERMISSION_GRANTED; 3199 } 3200 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3201 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3202 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3203 return PackageManager.PERMISSION_GRANTED; 3204 } 3205 } else { 3206 ArraySet<String> perms = mSystemPermissions.get(uid); 3207 if (perms != null) { 3208 if (perms.contains(permName)) { 3209 return PackageManager.PERMISSION_GRANTED; 3210 } 3211 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3212 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3213 return PackageManager.PERMISSION_GRANTED; 3214 } 3215 } 3216 } 3217 } 3218 3219 return PackageManager.PERMISSION_DENIED; 3220 } 3221 3222 @Override 3223 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3224 if (UserHandle.getCallingUserId() != userId) { 3225 mContext.enforceCallingPermission( 3226 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3227 "isPermissionRevokedByPolicy for user " + userId); 3228 } 3229 3230 if (checkPermission(permission, packageName, userId) 3231 == PackageManager.PERMISSION_GRANTED) { 3232 return false; 3233 } 3234 3235 final long identity = Binder.clearCallingIdentity(); 3236 try { 3237 final int flags = getPermissionFlags(permission, packageName, userId); 3238 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3239 } finally { 3240 Binder.restoreCallingIdentity(identity); 3241 } 3242 } 3243 3244 @Override 3245 public String getPermissionControllerPackageName() { 3246 synchronized (mPackages) { 3247 return mRequiredInstallerPackage; 3248 } 3249 } 3250 3251 /** 3252 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3253 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3254 * @param checkShell TODO(yamasani): 3255 * @param message the message to log on security exception 3256 */ 3257 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3258 boolean checkShell, String message) { 3259 if (userId < 0) { 3260 throw new IllegalArgumentException("Invalid userId " + userId); 3261 } 3262 if (checkShell) { 3263 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3264 } 3265 if (userId == UserHandle.getUserId(callingUid)) return; 3266 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3267 if (requireFullPermission) { 3268 mContext.enforceCallingOrSelfPermission( 3269 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3270 } else { 3271 try { 3272 mContext.enforceCallingOrSelfPermission( 3273 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3274 } catch (SecurityException se) { 3275 mContext.enforceCallingOrSelfPermission( 3276 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3277 } 3278 } 3279 } 3280 } 3281 3282 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3283 if (callingUid == Process.SHELL_UID) { 3284 if (userHandle >= 0 3285 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3286 throw new SecurityException("Shell does not have permission to access user " 3287 + userHandle); 3288 } else if (userHandle < 0) { 3289 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3290 + Debug.getCallers(3)); 3291 } 3292 } 3293 } 3294 3295 private BasePermission findPermissionTreeLP(String permName) { 3296 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3297 if (permName.startsWith(bp.name) && 3298 permName.length() > bp.name.length() && 3299 permName.charAt(bp.name.length()) == '.') { 3300 return bp; 3301 } 3302 } 3303 return null; 3304 } 3305 3306 private BasePermission checkPermissionTreeLP(String permName) { 3307 if (permName != null) { 3308 BasePermission bp = findPermissionTreeLP(permName); 3309 if (bp != null) { 3310 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3311 return bp; 3312 } 3313 throw new SecurityException("Calling uid " 3314 + Binder.getCallingUid() 3315 + " is not allowed to add to permission tree " 3316 + bp.name + " owned by uid " + bp.uid); 3317 } 3318 } 3319 throw new SecurityException("No permission tree found for " + permName); 3320 } 3321 3322 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3323 if (s1 == null) { 3324 return s2 == null; 3325 } 3326 if (s2 == null) { 3327 return false; 3328 } 3329 if (s1.getClass() != s2.getClass()) { 3330 return false; 3331 } 3332 return s1.equals(s2); 3333 } 3334 3335 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3336 if (pi1.icon != pi2.icon) return false; 3337 if (pi1.logo != pi2.logo) return false; 3338 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3339 if (!compareStrings(pi1.name, pi2.name)) return false; 3340 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3341 // We'll take care of setting this one. 3342 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3343 // These are not currently stored in settings. 3344 //if (!compareStrings(pi1.group, pi2.group)) return false; 3345 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3346 //if (pi1.labelRes != pi2.labelRes) return false; 3347 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3348 return true; 3349 } 3350 3351 int permissionInfoFootprint(PermissionInfo info) { 3352 int size = info.name.length(); 3353 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3354 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3355 return size; 3356 } 3357 3358 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3359 int size = 0; 3360 for (BasePermission perm : mSettings.mPermissions.values()) { 3361 if (perm.uid == tree.uid) { 3362 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3363 } 3364 } 3365 return size; 3366 } 3367 3368 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3369 // We calculate the max size of permissions defined by this uid and throw 3370 // if that plus the size of 'info' would exceed our stated maximum. 3371 if (tree.uid != Process.SYSTEM_UID) { 3372 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3373 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3374 throw new SecurityException("Permission tree size cap exceeded"); 3375 } 3376 } 3377 } 3378 3379 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3380 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3381 throw new SecurityException("Label must be specified in permission"); 3382 } 3383 BasePermission tree = checkPermissionTreeLP(info.name); 3384 BasePermission bp = mSettings.mPermissions.get(info.name); 3385 boolean added = bp == null; 3386 boolean changed = true; 3387 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3388 if (added) { 3389 enforcePermissionCapLocked(info, tree); 3390 bp = new BasePermission(info.name, tree.sourcePackage, 3391 BasePermission.TYPE_DYNAMIC); 3392 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3393 throw new SecurityException( 3394 "Not allowed to modify non-dynamic permission " 3395 + info.name); 3396 } else { 3397 if (bp.protectionLevel == fixedLevel 3398 && bp.perm.owner.equals(tree.perm.owner) 3399 && bp.uid == tree.uid 3400 && comparePermissionInfos(bp.perm.info, info)) { 3401 changed = false; 3402 } 3403 } 3404 bp.protectionLevel = fixedLevel; 3405 info = new PermissionInfo(info); 3406 info.protectionLevel = fixedLevel; 3407 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3408 bp.perm.info.packageName = tree.perm.info.packageName; 3409 bp.uid = tree.uid; 3410 if (added) { 3411 mSettings.mPermissions.put(info.name, bp); 3412 } 3413 if (changed) { 3414 if (!async) { 3415 mSettings.writeLPr(); 3416 } else { 3417 scheduleWriteSettingsLocked(); 3418 } 3419 } 3420 return added; 3421 } 3422 3423 @Override 3424 public boolean addPermission(PermissionInfo info) { 3425 synchronized (mPackages) { 3426 return addPermissionLocked(info, false); 3427 } 3428 } 3429 3430 @Override 3431 public boolean addPermissionAsync(PermissionInfo info) { 3432 synchronized (mPackages) { 3433 return addPermissionLocked(info, true); 3434 } 3435 } 3436 3437 @Override 3438 public void removePermission(String name) { 3439 synchronized (mPackages) { 3440 checkPermissionTreeLP(name); 3441 BasePermission bp = mSettings.mPermissions.get(name); 3442 if (bp != null) { 3443 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3444 throw new SecurityException( 3445 "Not allowed to modify non-dynamic permission " 3446 + name); 3447 } 3448 mSettings.mPermissions.remove(name); 3449 mSettings.writeLPr(); 3450 } 3451 } 3452 } 3453 3454 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3455 BasePermission bp) { 3456 int index = pkg.requestedPermissions.indexOf(bp.name); 3457 if (index == -1) { 3458 throw new SecurityException("Package " + pkg.packageName 3459 + " has not requested permission " + bp.name); 3460 } 3461 if (!bp.isRuntime() && !bp.isDevelopment()) { 3462 throw new SecurityException("Permission " + bp.name 3463 + " is not a changeable permission type"); 3464 } 3465 } 3466 3467 @Override 3468 public void grantRuntimePermission(String packageName, String name, final int userId) { 3469 if (!sUserManager.exists(userId)) { 3470 Log.e(TAG, "No such user:" + userId); 3471 return; 3472 } 3473 3474 mContext.enforceCallingOrSelfPermission( 3475 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3476 "grantRuntimePermission"); 3477 3478 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3479 "grantRuntimePermission"); 3480 3481 final int uid; 3482 final SettingBase sb; 3483 3484 synchronized (mPackages) { 3485 final PackageParser.Package pkg = mPackages.get(packageName); 3486 if (pkg == null) { 3487 throw new IllegalArgumentException("Unknown package: " + packageName); 3488 } 3489 3490 final BasePermission bp = mSettings.mPermissions.get(name); 3491 if (bp == null) { 3492 throw new IllegalArgumentException("Unknown permission: " + name); 3493 } 3494 3495 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3496 3497 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3498 sb = (SettingBase) pkg.mExtras; 3499 if (sb == null) { 3500 throw new IllegalArgumentException("Unknown package: " + packageName); 3501 } 3502 3503 final PermissionsState permissionsState = sb.getPermissionsState(); 3504 3505 final int flags = permissionsState.getPermissionFlags(name, userId); 3506 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3507 throw new SecurityException("Cannot grant system fixed permission: " 3508 + name + " for package: " + packageName); 3509 } 3510 3511 if (bp.isDevelopment()) { 3512 // Development permissions must be handled specially, since they are not 3513 // normal runtime permissions. For now they apply to all users. 3514 if (permissionsState.grantInstallPermission(bp) != 3515 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3516 scheduleWriteSettingsLocked(); 3517 } 3518 return; 3519 } 3520 3521 final int result = permissionsState.grantRuntimePermission(bp, userId); 3522 switch (result) { 3523 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3524 return; 3525 } 3526 3527 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3528 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3529 mHandler.post(new Runnable() { 3530 @Override 3531 public void run() { 3532 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3533 } 3534 }); 3535 } break; 3536 } 3537 3538 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3539 3540 // Not critical if that is lost - app has to request again. 3541 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3542 } 3543 3544 // Only need to do this if user is initialized. Otherwise it's a new user 3545 // and there are no processes running as the user yet and there's no need 3546 // to make an expensive call to remount processes for the changed permissions. 3547 if (READ_EXTERNAL_STORAGE.equals(name) 3548 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3549 final long token = Binder.clearCallingIdentity(); 3550 try { 3551 if (sUserManager.isInitialized(userId)) { 3552 MountServiceInternal mountServiceInternal = LocalServices.getService( 3553 MountServiceInternal.class); 3554 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3555 } 3556 } finally { 3557 Binder.restoreCallingIdentity(token); 3558 } 3559 } 3560 } 3561 3562 @Override 3563 public void revokeRuntimePermission(String packageName, String name, int userId) { 3564 if (!sUserManager.exists(userId)) { 3565 Log.e(TAG, "No such user:" + userId); 3566 return; 3567 } 3568 3569 mContext.enforceCallingOrSelfPermission( 3570 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3571 "revokeRuntimePermission"); 3572 3573 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3574 "revokeRuntimePermission"); 3575 3576 final int appId; 3577 3578 synchronized (mPackages) { 3579 final PackageParser.Package pkg = mPackages.get(packageName); 3580 if (pkg == null) { 3581 throw new IllegalArgumentException("Unknown package: " + packageName); 3582 } 3583 3584 final BasePermission bp = mSettings.mPermissions.get(name); 3585 if (bp == null) { 3586 throw new IllegalArgumentException("Unknown permission: " + name); 3587 } 3588 3589 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3590 3591 SettingBase sb = (SettingBase) pkg.mExtras; 3592 if (sb == null) { 3593 throw new IllegalArgumentException("Unknown package: " + packageName); 3594 } 3595 3596 final PermissionsState permissionsState = sb.getPermissionsState(); 3597 3598 final int flags = permissionsState.getPermissionFlags(name, userId); 3599 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3600 throw new SecurityException("Cannot revoke system fixed permission: " 3601 + name + " for package: " + packageName); 3602 } 3603 3604 if (bp.isDevelopment()) { 3605 // Development permissions must be handled specially, since they are not 3606 // normal runtime permissions. For now they apply to all users. 3607 if (permissionsState.revokeInstallPermission(bp) != 3608 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3609 scheduleWriteSettingsLocked(); 3610 } 3611 return; 3612 } 3613 3614 if (permissionsState.revokeRuntimePermission(bp, userId) == 3615 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3616 return; 3617 } 3618 3619 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3620 3621 // Critical, after this call app should never have the permission. 3622 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3623 3624 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3625 } 3626 3627 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3628 } 3629 3630 @Override 3631 public void resetRuntimePermissions() { 3632 mContext.enforceCallingOrSelfPermission( 3633 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3634 "revokeRuntimePermission"); 3635 3636 int callingUid = Binder.getCallingUid(); 3637 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3638 mContext.enforceCallingOrSelfPermission( 3639 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3640 "resetRuntimePermissions"); 3641 } 3642 3643 synchronized (mPackages) { 3644 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3645 for (int userId : UserManagerService.getInstance().getUserIds()) { 3646 final int packageCount = mPackages.size(); 3647 for (int i = 0; i < packageCount; i++) { 3648 PackageParser.Package pkg = mPackages.valueAt(i); 3649 if (!(pkg.mExtras instanceof PackageSetting)) { 3650 continue; 3651 } 3652 PackageSetting ps = (PackageSetting) pkg.mExtras; 3653 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3654 } 3655 } 3656 } 3657 } 3658 3659 @Override 3660 public int getPermissionFlags(String name, String packageName, int userId) { 3661 if (!sUserManager.exists(userId)) { 3662 return 0; 3663 } 3664 3665 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3666 3667 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3668 "getPermissionFlags"); 3669 3670 synchronized (mPackages) { 3671 final PackageParser.Package pkg = mPackages.get(packageName); 3672 if (pkg == null) { 3673 throw new IllegalArgumentException("Unknown package: " + packageName); 3674 } 3675 3676 final BasePermission bp = mSettings.mPermissions.get(name); 3677 if (bp == null) { 3678 throw new IllegalArgumentException("Unknown permission: " + name); 3679 } 3680 3681 SettingBase sb = (SettingBase) pkg.mExtras; 3682 if (sb == null) { 3683 throw new IllegalArgumentException("Unknown package: " + packageName); 3684 } 3685 3686 PermissionsState permissionsState = sb.getPermissionsState(); 3687 return permissionsState.getPermissionFlags(name, userId); 3688 } 3689 } 3690 3691 @Override 3692 public void updatePermissionFlags(String name, String packageName, int flagMask, 3693 int flagValues, int userId) { 3694 if (!sUserManager.exists(userId)) { 3695 return; 3696 } 3697 3698 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3699 3700 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3701 "updatePermissionFlags"); 3702 3703 // Only the system can change these flags and nothing else. 3704 if (getCallingUid() != Process.SYSTEM_UID) { 3705 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3706 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3707 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3708 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3709 } 3710 3711 synchronized (mPackages) { 3712 final PackageParser.Package pkg = mPackages.get(packageName); 3713 if (pkg == null) { 3714 throw new IllegalArgumentException("Unknown package: " + packageName); 3715 } 3716 3717 final BasePermission bp = mSettings.mPermissions.get(name); 3718 if (bp == null) { 3719 throw new IllegalArgumentException("Unknown permission: " + name); 3720 } 3721 3722 SettingBase sb = (SettingBase) pkg.mExtras; 3723 if (sb == null) { 3724 throw new IllegalArgumentException("Unknown package: " + packageName); 3725 } 3726 3727 PermissionsState permissionsState = sb.getPermissionsState(); 3728 3729 // Only the package manager can change flags for system component permissions. 3730 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3731 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3732 return; 3733 } 3734 3735 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3736 3737 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3738 // Install and runtime permissions are stored in different places, 3739 // so figure out what permission changed and persist the change. 3740 if (permissionsState.getInstallPermissionState(name) != null) { 3741 scheduleWriteSettingsLocked(); 3742 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3743 || hadState) { 3744 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3745 } 3746 } 3747 } 3748 } 3749 3750 /** 3751 * Update the permission flags for all packages and runtime permissions of a user in order 3752 * to allow device or profile owner to remove POLICY_FIXED. 3753 */ 3754 @Override 3755 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3756 if (!sUserManager.exists(userId)) { 3757 return; 3758 } 3759 3760 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3761 3762 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3763 "updatePermissionFlagsForAllApps"); 3764 3765 // Only the system can change system fixed flags. 3766 if (getCallingUid() != Process.SYSTEM_UID) { 3767 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3768 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3769 } 3770 3771 synchronized (mPackages) { 3772 boolean changed = false; 3773 final int packageCount = mPackages.size(); 3774 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3775 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3776 SettingBase sb = (SettingBase) pkg.mExtras; 3777 if (sb == null) { 3778 continue; 3779 } 3780 PermissionsState permissionsState = sb.getPermissionsState(); 3781 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3782 userId, flagMask, flagValues); 3783 } 3784 if (changed) { 3785 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3786 } 3787 } 3788 } 3789 3790 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3791 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3792 != PackageManager.PERMISSION_GRANTED 3793 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3794 != PackageManager.PERMISSION_GRANTED) { 3795 throw new SecurityException(message + " requires " 3796 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3797 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3798 } 3799 } 3800 3801 @Override 3802 public boolean shouldShowRequestPermissionRationale(String permissionName, 3803 String packageName, int userId) { 3804 if (UserHandle.getCallingUserId() != userId) { 3805 mContext.enforceCallingPermission( 3806 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3807 "canShowRequestPermissionRationale for user " + userId); 3808 } 3809 3810 final int uid = getPackageUid(packageName, userId); 3811 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3812 return false; 3813 } 3814 3815 if (checkPermission(permissionName, packageName, userId) 3816 == PackageManager.PERMISSION_GRANTED) { 3817 return false; 3818 } 3819 3820 final int flags; 3821 3822 final long identity = Binder.clearCallingIdentity(); 3823 try { 3824 flags = getPermissionFlags(permissionName, 3825 packageName, userId); 3826 } finally { 3827 Binder.restoreCallingIdentity(identity); 3828 } 3829 3830 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3831 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3832 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3833 3834 if ((flags & fixedFlags) != 0) { 3835 return false; 3836 } 3837 3838 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3839 } 3840 3841 @Override 3842 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3843 mContext.enforceCallingOrSelfPermission( 3844 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3845 "addOnPermissionsChangeListener"); 3846 3847 synchronized (mPackages) { 3848 mOnPermissionChangeListeners.addListenerLocked(listener); 3849 } 3850 } 3851 3852 @Override 3853 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3854 synchronized (mPackages) { 3855 mOnPermissionChangeListeners.removeListenerLocked(listener); 3856 } 3857 } 3858 3859 @Override 3860 public boolean isProtectedBroadcast(String actionName) { 3861 synchronized (mPackages) { 3862 return mProtectedBroadcasts.contains(actionName); 3863 } 3864 } 3865 3866 @Override 3867 public int checkSignatures(String pkg1, String pkg2) { 3868 synchronized (mPackages) { 3869 final PackageParser.Package p1 = mPackages.get(pkg1); 3870 final PackageParser.Package p2 = mPackages.get(pkg2); 3871 if (p1 == null || p1.mExtras == null 3872 || p2 == null || p2.mExtras == null) { 3873 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3874 } 3875 return compareSignatures(p1.mSignatures, p2.mSignatures); 3876 } 3877 } 3878 3879 @Override 3880 public int checkUidSignatures(int uid1, int uid2) { 3881 // Map to base uids. 3882 uid1 = UserHandle.getAppId(uid1); 3883 uid2 = UserHandle.getAppId(uid2); 3884 // reader 3885 synchronized (mPackages) { 3886 Signature[] s1; 3887 Signature[] s2; 3888 Object obj = mSettings.getUserIdLPr(uid1); 3889 if (obj != null) { 3890 if (obj instanceof SharedUserSetting) { 3891 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3892 } else if (obj instanceof PackageSetting) { 3893 s1 = ((PackageSetting)obj).signatures.mSignatures; 3894 } else { 3895 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3896 } 3897 } else { 3898 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3899 } 3900 obj = mSettings.getUserIdLPr(uid2); 3901 if (obj != null) { 3902 if (obj instanceof SharedUserSetting) { 3903 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3904 } else if (obj instanceof PackageSetting) { 3905 s2 = ((PackageSetting)obj).signatures.mSignatures; 3906 } else { 3907 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3908 } 3909 } else { 3910 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3911 } 3912 return compareSignatures(s1, s2); 3913 } 3914 } 3915 3916 private void killUid(int appId, int userId, String reason) { 3917 final long identity = Binder.clearCallingIdentity(); 3918 try { 3919 IActivityManager am = ActivityManagerNative.getDefault(); 3920 if (am != null) { 3921 try { 3922 am.killUid(appId, userId, reason); 3923 } catch (RemoteException e) { 3924 /* ignore - same process */ 3925 } 3926 } 3927 } finally { 3928 Binder.restoreCallingIdentity(identity); 3929 } 3930 } 3931 3932 /** 3933 * Compares two sets of signatures. Returns: 3934 * <br /> 3935 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3936 * <br /> 3937 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3938 * <br /> 3939 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3940 * <br /> 3941 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3942 * <br /> 3943 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3944 */ 3945 static int compareSignatures(Signature[] s1, Signature[] s2) { 3946 if (s1 == null) { 3947 return s2 == null 3948 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3949 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3950 } 3951 3952 if (s2 == null) { 3953 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3954 } 3955 3956 if (s1.length != s2.length) { 3957 return PackageManager.SIGNATURE_NO_MATCH; 3958 } 3959 3960 // Since both signature sets are of size 1, we can compare without HashSets. 3961 if (s1.length == 1) { 3962 return s1[0].equals(s2[0]) ? 3963 PackageManager.SIGNATURE_MATCH : 3964 PackageManager.SIGNATURE_NO_MATCH; 3965 } 3966 3967 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3968 for (Signature sig : s1) { 3969 set1.add(sig); 3970 } 3971 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3972 for (Signature sig : s2) { 3973 set2.add(sig); 3974 } 3975 // Make sure s2 contains all signatures in s1. 3976 if (set1.equals(set2)) { 3977 return PackageManager.SIGNATURE_MATCH; 3978 } 3979 return PackageManager.SIGNATURE_NO_MATCH; 3980 } 3981 3982 /** 3983 * If the database version for this type of package (internal storage or 3984 * external storage) is less than the version where package signatures 3985 * were updated, return true. 3986 */ 3987 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3988 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3989 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3990 } 3991 3992 /** 3993 * Used for backward compatibility to make sure any packages with 3994 * certificate chains get upgraded to the new style. {@code existingSigs} 3995 * will be in the old format (since they were stored on disk from before the 3996 * system upgrade) and {@code scannedSigs} will be in the newer format. 3997 */ 3998 private int compareSignaturesCompat(PackageSignatures existingSigs, 3999 PackageParser.Package scannedPkg) { 4000 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4001 return PackageManager.SIGNATURE_NO_MATCH; 4002 } 4003 4004 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4005 for (Signature sig : existingSigs.mSignatures) { 4006 existingSet.add(sig); 4007 } 4008 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4009 for (Signature sig : scannedPkg.mSignatures) { 4010 try { 4011 Signature[] chainSignatures = sig.getChainSignatures(); 4012 for (Signature chainSig : chainSignatures) { 4013 scannedCompatSet.add(chainSig); 4014 } 4015 } catch (CertificateEncodingException e) { 4016 scannedCompatSet.add(sig); 4017 } 4018 } 4019 /* 4020 * Make sure the expanded scanned set contains all signatures in the 4021 * existing one. 4022 */ 4023 if (scannedCompatSet.equals(existingSet)) { 4024 // Migrate the old signatures to the new scheme. 4025 existingSigs.assignSignatures(scannedPkg.mSignatures); 4026 // The new KeySets will be re-added later in the scanning process. 4027 synchronized (mPackages) { 4028 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4029 } 4030 return PackageManager.SIGNATURE_MATCH; 4031 } 4032 return PackageManager.SIGNATURE_NO_MATCH; 4033 } 4034 4035 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4036 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4037 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4038 } 4039 4040 private int compareSignaturesRecover(PackageSignatures existingSigs, 4041 PackageParser.Package scannedPkg) { 4042 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4043 return PackageManager.SIGNATURE_NO_MATCH; 4044 } 4045 4046 String msg = null; 4047 try { 4048 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4049 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4050 + scannedPkg.packageName); 4051 return PackageManager.SIGNATURE_MATCH; 4052 } 4053 } catch (CertificateException e) { 4054 msg = e.getMessage(); 4055 } 4056 4057 logCriticalInfo(Log.INFO, 4058 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4059 return PackageManager.SIGNATURE_NO_MATCH; 4060 } 4061 4062 @Override 4063 public String[] getPackagesForUid(int uid) { 4064 uid = UserHandle.getAppId(uid); 4065 // reader 4066 synchronized (mPackages) { 4067 Object obj = mSettings.getUserIdLPr(uid); 4068 if (obj instanceof SharedUserSetting) { 4069 final SharedUserSetting sus = (SharedUserSetting) obj; 4070 final int N = sus.packages.size(); 4071 final String[] res = new String[N]; 4072 final Iterator<PackageSetting> it = sus.packages.iterator(); 4073 int i = 0; 4074 while (it.hasNext()) { 4075 res[i++] = it.next().name; 4076 } 4077 return res; 4078 } else if (obj instanceof PackageSetting) { 4079 final PackageSetting ps = (PackageSetting) obj; 4080 return new String[] { ps.name }; 4081 } 4082 } 4083 return null; 4084 } 4085 4086 @Override 4087 public String getNameForUid(int uid) { 4088 // reader 4089 synchronized (mPackages) { 4090 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4091 if (obj instanceof SharedUserSetting) { 4092 final SharedUserSetting sus = (SharedUserSetting) obj; 4093 return sus.name + ":" + sus.userId; 4094 } else if (obj instanceof PackageSetting) { 4095 final PackageSetting ps = (PackageSetting) obj; 4096 return ps.name; 4097 } 4098 } 4099 return null; 4100 } 4101 4102 @Override 4103 public int getUidForSharedUser(String sharedUserName) { 4104 if(sharedUserName == null) { 4105 return -1; 4106 } 4107 // reader 4108 synchronized (mPackages) { 4109 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4110 if (suid == null) { 4111 return -1; 4112 } 4113 return suid.userId; 4114 } 4115 } 4116 4117 @Override 4118 public int getFlagsForUid(int uid) { 4119 synchronized (mPackages) { 4120 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4121 if (obj instanceof SharedUserSetting) { 4122 final SharedUserSetting sus = (SharedUserSetting) obj; 4123 return sus.pkgFlags; 4124 } else if (obj instanceof PackageSetting) { 4125 final PackageSetting ps = (PackageSetting) obj; 4126 return ps.pkgFlags; 4127 } 4128 } 4129 return 0; 4130 } 4131 4132 @Override 4133 public int getPrivateFlagsForUid(int uid) { 4134 synchronized (mPackages) { 4135 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4136 if (obj instanceof SharedUserSetting) { 4137 final SharedUserSetting sus = (SharedUserSetting) obj; 4138 return sus.pkgPrivateFlags; 4139 } else if (obj instanceof PackageSetting) { 4140 final PackageSetting ps = (PackageSetting) obj; 4141 return ps.pkgPrivateFlags; 4142 } 4143 } 4144 return 0; 4145 } 4146 4147 @Override 4148 public boolean isUidPrivileged(int uid) { 4149 uid = UserHandle.getAppId(uid); 4150 // reader 4151 synchronized (mPackages) { 4152 Object obj = mSettings.getUserIdLPr(uid); 4153 if (obj instanceof SharedUserSetting) { 4154 final SharedUserSetting sus = (SharedUserSetting) obj; 4155 final Iterator<PackageSetting> it = sus.packages.iterator(); 4156 while (it.hasNext()) { 4157 if (it.next().isPrivileged()) { 4158 return true; 4159 } 4160 } 4161 } else if (obj instanceof PackageSetting) { 4162 final PackageSetting ps = (PackageSetting) obj; 4163 return ps.isPrivileged(); 4164 } 4165 } 4166 return false; 4167 } 4168 4169 @Override 4170 public String[] getAppOpPermissionPackages(String permissionName) { 4171 synchronized (mPackages) { 4172 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4173 if (pkgs == null) { 4174 return null; 4175 } 4176 return pkgs.toArray(new String[pkgs.size()]); 4177 } 4178 } 4179 4180 @Override 4181 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4182 int flags, int userId) { 4183 if (!sUserManager.exists(userId)) return null; 4184 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4185 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4186 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4187 } 4188 4189 @Override 4190 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4191 IntentFilter filter, int match, ComponentName activity) { 4192 final int userId = UserHandle.getCallingUserId(); 4193 if (DEBUG_PREFERRED) { 4194 Log.v(TAG, "setLastChosenActivity intent=" + intent 4195 + " resolvedType=" + resolvedType 4196 + " flags=" + flags 4197 + " filter=" + filter 4198 + " match=" + match 4199 + " activity=" + activity); 4200 filter.dump(new PrintStreamPrinter(System.out), " "); 4201 } 4202 intent.setComponent(null); 4203 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4204 // Find any earlier preferred or last chosen entries and nuke them 4205 findPreferredActivity(intent, resolvedType, 4206 flags, query, 0, false, true, false, userId); 4207 // Add the new activity as the last chosen for this filter 4208 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4209 "Setting last chosen"); 4210 } 4211 4212 @Override 4213 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4214 final int userId = UserHandle.getCallingUserId(); 4215 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4216 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4217 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4218 false, false, false, userId); 4219 } 4220 4221 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4222 int flags, List<ResolveInfo> query, int userId) { 4223 if (query != null) { 4224 final int N = query.size(); 4225 if (N == 1) { 4226 return query.get(0); 4227 } else if (N > 1) { 4228 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4229 // If there is more than one activity with the same priority, 4230 // then let the user decide between them. 4231 ResolveInfo r0 = query.get(0); 4232 ResolveInfo r1 = query.get(1); 4233 if (DEBUG_INTENT_MATCHING || debug) { 4234 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4235 + r1.activityInfo.name + "=" + r1.priority); 4236 } 4237 // If the first activity has a higher priority, or a different 4238 // default, then it is always desireable to pick it. 4239 if (r0.priority != r1.priority 4240 || r0.preferredOrder != r1.preferredOrder 4241 || r0.isDefault != r1.isDefault) { 4242 return query.get(0); 4243 } 4244 // If we have saved a preference for a preferred activity for 4245 // this Intent, use that. 4246 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4247 flags, query, r0.priority, true, false, debug, userId); 4248 if (ri != null) { 4249 return ri; 4250 } 4251 if (userId != 0) { 4252 ri = new ResolveInfo(mResolveInfo); 4253 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4254 ri.activityInfo.applicationInfo = new ApplicationInfo( 4255 ri.activityInfo.applicationInfo); 4256 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4257 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4258 return ri; 4259 } 4260 return mResolveInfo; 4261 } 4262 } 4263 return null; 4264 } 4265 4266 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4267 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4268 final int N = query.size(); 4269 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4270 .get(userId); 4271 // Get the list of persistent preferred activities that handle the intent 4272 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4273 List<PersistentPreferredActivity> pprefs = ppir != null 4274 ? ppir.queryIntent(intent, resolvedType, 4275 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4276 : null; 4277 if (pprefs != null && pprefs.size() > 0) { 4278 final int M = pprefs.size(); 4279 for (int i=0; i<M; i++) { 4280 final PersistentPreferredActivity ppa = pprefs.get(i); 4281 if (DEBUG_PREFERRED || debug) { 4282 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4283 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4284 + "\n component=" + ppa.mComponent); 4285 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4286 } 4287 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4288 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4289 if (DEBUG_PREFERRED || debug) { 4290 Slog.v(TAG, "Found persistent preferred activity:"); 4291 if (ai != null) { 4292 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4293 } else { 4294 Slog.v(TAG, " null"); 4295 } 4296 } 4297 if (ai == null) { 4298 // This previously registered persistent preferred activity 4299 // component is no longer known. Ignore it and do NOT remove it. 4300 continue; 4301 } 4302 for (int j=0; j<N; j++) { 4303 final ResolveInfo ri = query.get(j); 4304 if (!ri.activityInfo.applicationInfo.packageName 4305 .equals(ai.applicationInfo.packageName)) { 4306 continue; 4307 } 4308 if (!ri.activityInfo.name.equals(ai.name)) { 4309 continue; 4310 } 4311 // Found a persistent preference that can handle the intent. 4312 if (DEBUG_PREFERRED || debug) { 4313 Slog.v(TAG, "Returning persistent preferred activity: " + 4314 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4315 } 4316 return ri; 4317 } 4318 } 4319 } 4320 return null; 4321 } 4322 4323 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4324 List<ResolveInfo> query, int priority, boolean always, 4325 boolean removeMatches, boolean debug, int userId) { 4326 if (!sUserManager.exists(userId)) return null; 4327 // writer 4328 synchronized (mPackages) { 4329 if (intent.getSelector() != null) { 4330 intent = intent.getSelector(); 4331 } 4332 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4333 4334 // Try to find a matching persistent preferred activity. 4335 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4336 debug, userId); 4337 4338 // If a persistent preferred activity matched, use it. 4339 if (pri != null) { 4340 return pri; 4341 } 4342 4343 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4344 // Get the list of preferred activities that handle the intent 4345 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4346 List<PreferredActivity> prefs = pir != null 4347 ? pir.queryIntent(intent, resolvedType, 4348 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4349 : null; 4350 if (prefs != null && prefs.size() > 0) { 4351 boolean changed = false; 4352 try { 4353 // First figure out how good the original match set is. 4354 // We will only allow preferred activities that came 4355 // from the same match quality. 4356 int match = 0; 4357 4358 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4359 4360 final int N = query.size(); 4361 for (int j=0; j<N; j++) { 4362 final ResolveInfo ri = query.get(j); 4363 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4364 + ": 0x" + Integer.toHexString(match)); 4365 if (ri.match > match) { 4366 match = ri.match; 4367 } 4368 } 4369 4370 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4371 + Integer.toHexString(match)); 4372 4373 match &= IntentFilter.MATCH_CATEGORY_MASK; 4374 final int M = prefs.size(); 4375 for (int i=0; i<M; i++) { 4376 final PreferredActivity pa = prefs.get(i); 4377 if (DEBUG_PREFERRED || debug) { 4378 Slog.v(TAG, "Checking PreferredActivity ds=" 4379 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4380 + "\n component=" + pa.mPref.mComponent); 4381 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4382 } 4383 if (pa.mPref.mMatch != match) { 4384 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4385 + Integer.toHexString(pa.mPref.mMatch)); 4386 continue; 4387 } 4388 // If it's not an "always" type preferred activity and that's what we're 4389 // looking for, skip it. 4390 if (always && !pa.mPref.mAlways) { 4391 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4392 continue; 4393 } 4394 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4395 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4396 if (DEBUG_PREFERRED || debug) { 4397 Slog.v(TAG, "Found preferred activity:"); 4398 if (ai != null) { 4399 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4400 } else { 4401 Slog.v(TAG, " null"); 4402 } 4403 } 4404 if (ai == null) { 4405 // This previously registered preferred activity 4406 // component is no longer known. Most likely an update 4407 // to the app was installed and in the new version this 4408 // component no longer exists. Clean it up by removing 4409 // it from the preferred activities list, and skip it. 4410 Slog.w(TAG, "Removing dangling preferred activity: " 4411 + pa.mPref.mComponent); 4412 pir.removeFilter(pa); 4413 changed = true; 4414 continue; 4415 } 4416 for (int j=0; j<N; j++) { 4417 final ResolveInfo ri = query.get(j); 4418 if (!ri.activityInfo.applicationInfo.packageName 4419 .equals(ai.applicationInfo.packageName)) { 4420 continue; 4421 } 4422 if (!ri.activityInfo.name.equals(ai.name)) { 4423 continue; 4424 } 4425 4426 if (removeMatches) { 4427 pir.removeFilter(pa); 4428 changed = true; 4429 if (DEBUG_PREFERRED) { 4430 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4431 } 4432 break; 4433 } 4434 4435 // Okay we found a previously set preferred or last chosen app. 4436 // If the result set is different from when this 4437 // was created, we need to clear it and re-ask the 4438 // user their preference, if we're looking for an "always" type entry. 4439 if (always && !pa.mPref.sameSet(query)) { 4440 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4441 + intent + " type " + resolvedType); 4442 if (DEBUG_PREFERRED) { 4443 Slog.v(TAG, "Removing preferred activity since set changed " 4444 + pa.mPref.mComponent); 4445 } 4446 pir.removeFilter(pa); 4447 // Re-add the filter as a "last chosen" entry (!always) 4448 PreferredActivity lastChosen = new PreferredActivity( 4449 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4450 pir.addFilter(lastChosen); 4451 changed = true; 4452 return null; 4453 } 4454 4455 // Yay! Either the set matched or we're looking for the last chosen 4456 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4457 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4458 return ri; 4459 } 4460 } 4461 } finally { 4462 if (changed) { 4463 if (DEBUG_PREFERRED) { 4464 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4465 } 4466 scheduleWritePackageRestrictionsLocked(userId); 4467 } 4468 } 4469 } 4470 } 4471 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4472 return null; 4473 } 4474 4475 /* 4476 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4477 */ 4478 @Override 4479 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4480 int targetUserId) { 4481 mContext.enforceCallingOrSelfPermission( 4482 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4483 List<CrossProfileIntentFilter> matches = 4484 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4485 if (matches != null) { 4486 int size = matches.size(); 4487 for (int i = 0; i < size; i++) { 4488 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4489 } 4490 } 4491 if (hasWebURI(intent)) { 4492 // cross-profile app linking works only towards the parent. 4493 final UserInfo parent = getProfileParent(sourceUserId); 4494 synchronized(mPackages) { 4495 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4496 intent, resolvedType, 0, sourceUserId, parent.id); 4497 return xpDomainInfo != null; 4498 } 4499 } 4500 return false; 4501 } 4502 4503 private UserInfo getProfileParent(int userId) { 4504 final long identity = Binder.clearCallingIdentity(); 4505 try { 4506 return sUserManager.getProfileParent(userId); 4507 } finally { 4508 Binder.restoreCallingIdentity(identity); 4509 } 4510 } 4511 4512 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4513 String resolvedType, int userId) { 4514 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4515 if (resolver != null) { 4516 return resolver.queryIntent(intent, resolvedType, false, userId); 4517 } 4518 return null; 4519 } 4520 4521 @Override 4522 public List<ResolveInfo> queryIntentActivities(Intent intent, 4523 String resolvedType, int flags, int userId) { 4524 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4525 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4526 ComponentName comp = intent.getComponent(); 4527 if (comp == null) { 4528 if (intent.getSelector() != null) { 4529 intent = intent.getSelector(); 4530 comp = intent.getComponent(); 4531 } 4532 } 4533 4534 if (comp != null) { 4535 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4536 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4537 if (ai != null) { 4538 final ResolveInfo ri = new ResolveInfo(); 4539 ri.activityInfo = ai; 4540 list.add(ri); 4541 } 4542 return list; 4543 } 4544 4545 // reader 4546 synchronized (mPackages) { 4547 final String pkgName = intent.getPackage(); 4548 if (pkgName == null) { 4549 List<CrossProfileIntentFilter> matchingFilters = 4550 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4551 // Check for results that need to skip the current profile. 4552 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4553 resolvedType, flags, userId); 4554 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4555 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4556 result.add(xpResolveInfo); 4557 return filterIfNotSystemUser(result, userId); 4558 } 4559 4560 // Check for results in the current profile. 4561 List<ResolveInfo> result = mActivities.queryIntent( 4562 intent, resolvedType, flags, userId); 4563 4564 // Check for cross profile results. 4565 xpResolveInfo = queryCrossProfileIntents( 4566 matchingFilters, intent, resolvedType, flags, userId); 4567 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4568 result.add(xpResolveInfo); 4569 Collections.sort(result, mResolvePrioritySorter); 4570 } 4571 result = filterIfNotSystemUser(result, userId); 4572 if (hasWebURI(intent)) { 4573 CrossProfileDomainInfo xpDomainInfo = null; 4574 final UserInfo parent = getProfileParent(userId); 4575 if (parent != null) { 4576 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4577 flags, userId, parent.id); 4578 } 4579 if (xpDomainInfo != null) { 4580 if (xpResolveInfo != null) { 4581 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4582 // in the result. 4583 result.remove(xpResolveInfo); 4584 } 4585 if (result.size() == 0) { 4586 result.add(xpDomainInfo.resolveInfo); 4587 return result; 4588 } 4589 } else if (result.size() <= 1) { 4590 return result; 4591 } 4592 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4593 xpDomainInfo, userId); 4594 Collections.sort(result, mResolvePrioritySorter); 4595 } 4596 return result; 4597 } 4598 final PackageParser.Package pkg = mPackages.get(pkgName); 4599 if (pkg != null) { 4600 return filterIfNotSystemUser( 4601 mActivities.queryIntentForPackage( 4602 intent, resolvedType, flags, pkg.activities, userId), 4603 userId); 4604 } 4605 return new ArrayList<ResolveInfo>(); 4606 } 4607 } 4608 4609 private static class CrossProfileDomainInfo { 4610 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4611 ResolveInfo resolveInfo; 4612 /* Best domain verification status of the activities found in the other profile */ 4613 int bestDomainVerificationStatus; 4614 } 4615 4616 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4617 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4618 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4619 sourceUserId)) { 4620 return null; 4621 } 4622 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4623 resolvedType, flags, parentUserId); 4624 4625 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4626 return null; 4627 } 4628 CrossProfileDomainInfo result = null; 4629 int size = resultTargetUser.size(); 4630 for (int i = 0; i < size; i++) { 4631 ResolveInfo riTargetUser = resultTargetUser.get(i); 4632 // Intent filter verification is only for filters that specify a host. So don't return 4633 // those that handle all web uris. 4634 if (riTargetUser.handleAllWebDataURI) { 4635 continue; 4636 } 4637 String packageName = riTargetUser.activityInfo.packageName; 4638 PackageSetting ps = mSettings.mPackages.get(packageName); 4639 if (ps == null) { 4640 continue; 4641 } 4642 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4643 int status = (int)(verificationState >> 32); 4644 if (result == null) { 4645 result = new CrossProfileDomainInfo(); 4646 result.resolveInfo = 4647 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4648 result.bestDomainVerificationStatus = status; 4649 } else { 4650 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4651 result.bestDomainVerificationStatus); 4652 } 4653 } 4654 // Don't consider matches with status NEVER across profiles. 4655 if (result != null && result.bestDomainVerificationStatus 4656 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4657 return null; 4658 } 4659 return result; 4660 } 4661 4662 /** 4663 * Verification statuses are ordered from the worse to the best, except for 4664 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4665 */ 4666 private int bestDomainVerificationStatus(int status1, int status2) { 4667 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4668 return status2; 4669 } 4670 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4671 return status1; 4672 } 4673 return (int) MathUtils.max(status1, status2); 4674 } 4675 4676 private boolean isUserEnabled(int userId) { 4677 long callingId = Binder.clearCallingIdentity(); 4678 try { 4679 UserInfo userInfo = sUserManager.getUserInfo(userId); 4680 return userInfo != null && userInfo.isEnabled(); 4681 } finally { 4682 Binder.restoreCallingIdentity(callingId); 4683 } 4684 } 4685 4686 /** 4687 * Filter out activities with systemUserOnly flag set, when current user is not System. 4688 * 4689 * @return filtered list 4690 */ 4691 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4692 if (userId == UserHandle.USER_SYSTEM) { 4693 return resolveInfos; 4694 } 4695 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4696 ResolveInfo info = resolveInfos.get(i); 4697 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4698 resolveInfos.remove(i); 4699 } 4700 } 4701 return resolveInfos; 4702 } 4703 4704 private static boolean hasWebURI(Intent intent) { 4705 if (intent.getData() == null) { 4706 return false; 4707 } 4708 final String scheme = intent.getScheme(); 4709 if (TextUtils.isEmpty(scheme)) { 4710 return false; 4711 } 4712 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4713 } 4714 4715 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4716 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4717 int userId) { 4718 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4719 4720 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4721 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4722 candidates.size()); 4723 } 4724 4725 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4726 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4727 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4728 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4729 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4730 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4731 4732 synchronized (mPackages) { 4733 final int count = candidates.size(); 4734 // First, try to use linked apps. Partition the candidates into four lists: 4735 // one for the final results, one for the "do not use ever", one for "undefined status" 4736 // and finally one for "browser app type". 4737 for (int n=0; n<count; n++) { 4738 ResolveInfo info = candidates.get(n); 4739 String packageName = info.activityInfo.packageName; 4740 PackageSetting ps = mSettings.mPackages.get(packageName); 4741 if (ps != null) { 4742 // Add to the special match all list (Browser use case) 4743 if (info.handleAllWebDataURI) { 4744 matchAllList.add(info); 4745 continue; 4746 } 4747 // Try to get the status from User settings first 4748 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4749 int status = (int)(packedStatus >> 32); 4750 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4751 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4752 if (DEBUG_DOMAIN_VERIFICATION) { 4753 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4754 + " : linkgen=" + linkGeneration); 4755 } 4756 // Use link-enabled generation as preferredOrder, i.e. 4757 // prefer newly-enabled over earlier-enabled. 4758 info.preferredOrder = linkGeneration; 4759 alwaysList.add(info); 4760 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4761 if (DEBUG_DOMAIN_VERIFICATION) { 4762 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4763 } 4764 neverList.add(info); 4765 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4766 if (DEBUG_DOMAIN_VERIFICATION) { 4767 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4768 } 4769 alwaysAskList.add(info); 4770 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4771 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4772 if (DEBUG_DOMAIN_VERIFICATION) { 4773 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4774 } 4775 undefinedList.add(info); 4776 } 4777 } 4778 } 4779 4780 // We'll want to include browser possibilities in a few cases 4781 boolean includeBrowser = false; 4782 4783 // First try to add the "always" resolution(s) for the current user, if any 4784 if (alwaysList.size() > 0) { 4785 result.addAll(alwaysList); 4786 // if there is an "always" for the parent user, add it. 4787 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4788 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4789 result.add(xpDomainInfo.resolveInfo); 4790 } else { 4791 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4792 result.addAll(undefinedList); 4793 if (xpDomainInfo != null && ( 4794 xpDomainInfo.bestDomainVerificationStatus 4795 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4796 || xpDomainInfo.bestDomainVerificationStatus 4797 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4798 result.add(xpDomainInfo.resolveInfo); 4799 } 4800 includeBrowser = true; 4801 } 4802 4803 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4804 // If there were 'always' entries their preferred order has been set, so we also 4805 // back that off to make the alternatives equivalent 4806 if (alwaysAskList.size() > 0) { 4807 for (ResolveInfo i : result) { 4808 i.preferredOrder = 0; 4809 } 4810 result.addAll(alwaysAskList); 4811 includeBrowser = true; 4812 } 4813 4814 if (includeBrowser) { 4815 // Also add browsers (all of them or only the default one) 4816 if (DEBUG_DOMAIN_VERIFICATION) { 4817 Slog.v(TAG, " ...including browsers in candidate set"); 4818 } 4819 if ((matchFlags & MATCH_ALL) != 0) { 4820 result.addAll(matchAllList); 4821 } else { 4822 // Browser/generic handling case. If there's a default browser, go straight 4823 // to that (but only if there is no other higher-priority match). 4824 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4825 int maxMatchPrio = 0; 4826 ResolveInfo defaultBrowserMatch = null; 4827 final int numCandidates = matchAllList.size(); 4828 for (int n = 0; n < numCandidates; n++) { 4829 ResolveInfo info = matchAllList.get(n); 4830 // track the highest overall match priority... 4831 if (info.priority > maxMatchPrio) { 4832 maxMatchPrio = info.priority; 4833 } 4834 // ...and the highest-priority default browser match 4835 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4836 if (defaultBrowserMatch == null 4837 || (defaultBrowserMatch.priority < info.priority)) { 4838 if (debug) { 4839 Slog.v(TAG, "Considering default browser match " + info); 4840 } 4841 defaultBrowserMatch = info; 4842 } 4843 } 4844 } 4845 if (defaultBrowserMatch != null 4846 && defaultBrowserMatch.priority >= maxMatchPrio 4847 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4848 { 4849 if (debug) { 4850 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4851 } 4852 result.add(defaultBrowserMatch); 4853 } else { 4854 result.addAll(matchAllList); 4855 } 4856 } 4857 4858 // If there is nothing selected, add all candidates and remove the ones that the user 4859 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4860 if (result.size() == 0) { 4861 result.addAll(candidates); 4862 result.removeAll(neverList); 4863 } 4864 } 4865 } 4866 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4867 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4868 result.size()); 4869 for (ResolveInfo info : result) { 4870 Slog.v(TAG, " + " + info.activityInfo); 4871 } 4872 } 4873 return result; 4874 } 4875 4876 // Returns a packed value as a long: 4877 // 4878 // high 'int'-sized word: link status: undefined/ask/never/always. 4879 // low 'int'-sized word: relative priority among 'always' results. 4880 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4881 long result = ps.getDomainVerificationStatusForUser(userId); 4882 // if none available, get the master status 4883 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4884 if (ps.getIntentFilterVerificationInfo() != null) { 4885 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4886 } 4887 } 4888 return result; 4889 } 4890 4891 private ResolveInfo querySkipCurrentProfileIntents( 4892 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4893 int flags, int sourceUserId) { 4894 if (matchingFilters != null) { 4895 int size = matchingFilters.size(); 4896 for (int i = 0; i < size; i ++) { 4897 CrossProfileIntentFilter filter = matchingFilters.get(i); 4898 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4899 // Checking if there are activities in the target user that can handle the 4900 // intent. 4901 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4902 flags, sourceUserId); 4903 if (resolveInfo != null) { 4904 return resolveInfo; 4905 } 4906 } 4907 } 4908 } 4909 return null; 4910 } 4911 4912 // Return matching ResolveInfo if any for skip current profile intent filters. 4913 private ResolveInfo queryCrossProfileIntents( 4914 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4915 int flags, int sourceUserId) { 4916 if (matchingFilters != null) { 4917 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4918 // match the same intent. For performance reasons, it is better not to 4919 // run queryIntent twice for the same userId 4920 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4921 int size = matchingFilters.size(); 4922 for (int i = 0; i < size; i++) { 4923 CrossProfileIntentFilter filter = matchingFilters.get(i); 4924 int targetUserId = filter.getTargetUserId(); 4925 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4926 && !alreadyTriedUserIds.get(targetUserId)) { 4927 // Checking if there are activities in the target user that can handle the 4928 // intent. 4929 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4930 flags, sourceUserId); 4931 if (resolveInfo != null) return resolveInfo; 4932 alreadyTriedUserIds.put(targetUserId, true); 4933 } 4934 } 4935 } 4936 return null; 4937 } 4938 4939 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4940 String resolvedType, int flags, int sourceUserId) { 4941 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4942 resolvedType, flags, filter.getTargetUserId()); 4943 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4944 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4945 } 4946 return null; 4947 } 4948 4949 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4950 int sourceUserId, int targetUserId) { 4951 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4952 long ident = Binder.clearCallingIdentity(); 4953 boolean targetIsProfile; 4954 try { 4955 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4956 } finally { 4957 Binder.restoreCallingIdentity(ident); 4958 } 4959 String className; 4960 if (targetIsProfile) { 4961 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4962 } else { 4963 className = FORWARD_INTENT_TO_PARENT; 4964 } 4965 ComponentName forwardingActivityComponentName = new ComponentName( 4966 mAndroidApplication.packageName, className); 4967 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4968 sourceUserId); 4969 if (!targetIsProfile) { 4970 forwardingActivityInfo.showUserIcon = targetUserId; 4971 forwardingResolveInfo.noResourceId = true; 4972 } 4973 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4974 forwardingResolveInfo.priority = 0; 4975 forwardingResolveInfo.preferredOrder = 0; 4976 forwardingResolveInfo.match = 0; 4977 forwardingResolveInfo.isDefault = true; 4978 forwardingResolveInfo.filter = filter; 4979 forwardingResolveInfo.targetUserId = targetUserId; 4980 return forwardingResolveInfo; 4981 } 4982 4983 @Override 4984 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4985 Intent[] specifics, String[] specificTypes, Intent intent, 4986 String resolvedType, int flags, int userId) { 4987 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4988 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4989 false, "query intent activity options"); 4990 final String resultsAction = intent.getAction(); 4991 4992 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4993 | PackageManager.GET_RESOLVED_FILTER, userId); 4994 4995 if (DEBUG_INTENT_MATCHING) { 4996 Log.v(TAG, "Query " + intent + ": " + results); 4997 } 4998 4999 int specificsPos = 0; 5000 int N; 5001 5002 // todo: note that the algorithm used here is O(N^2). This 5003 // isn't a problem in our current environment, but if we start running 5004 // into situations where we have more than 5 or 10 matches then this 5005 // should probably be changed to something smarter... 5006 5007 // First we go through and resolve each of the specific items 5008 // that were supplied, taking care of removing any corresponding 5009 // duplicate items in the generic resolve list. 5010 if (specifics != null) { 5011 for (int i=0; i<specifics.length; i++) { 5012 final Intent sintent = specifics[i]; 5013 if (sintent == null) { 5014 continue; 5015 } 5016 5017 if (DEBUG_INTENT_MATCHING) { 5018 Log.v(TAG, "Specific #" + i + ": " + sintent); 5019 } 5020 5021 String action = sintent.getAction(); 5022 if (resultsAction != null && resultsAction.equals(action)) { 5023 // If this action was explicitly requested, then don't 5024 // remove things that have it. 5025 action = null; 5026 } 5027 5028 ResolveInfo ri = null; 5029 ActivityInfo ai = null; 5030 5031 ComponentName comp = sintent.getComponent(); 5032 if (comp == null) { 5033 ri = resolveIntent( 5034 sintent, 5035 specificTypes != null ? specificTypes[i] : null, 5036 flags, userId); 5037 if (ri == null) { 5038 continue; 5039 } 5040 if (ri == mResolveInfo) { 5041 // ACK! Must do something better with this. 5042 } 5043 ai = ri.activityInfo; 5044 comp = new ComponentName(ai.applicationInfo.packageName, 5045 ai.name); 5046 } else { 5047 ai = getActivityInfo(comp, flags, userId); 5048 if (ai == null) { 5049 continue; 5050 } 5051 } 5052 5053 // Look for any generic query activities that are duplicates 5054 // of this specific one, and remove them from the results. 5055 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5056 N = results.size(); 5057 int j; 5058 for (j=specificsPos; j<N; j++) { 5059 ResolveInfo sri = results.get(j); 5060 if ((sri.activityInfo.name.equals(comp.getClassName()) 5061 && sri.activityInfo.applicationInfo.packageName.equals( 5062 comp.getPackageName())) 5063 || (action != null && sri.filter.matchAction(action))) { 5064 results.remove(j); 5065 if (DEBUG_INTENT_MATCHING) Log.v( 5066 TAG, "Removing duplicate item from " + j 5067 + " due to specific " + specificsPos); 5068 if (ri == null) { 5069 ri = sri; 5070 } 5071 j--; 5072 N--; 5073 } 5074 } 5075 5076 // Add this specific item to its proper place. 5077 if (ri == null) { 5078 ri = new ResolveInfo(); 5079 ri.activityInfo = ai; 5080 } 5081 results.add(specificsPos, ri); 5082 ri.specificIndex = i; 5083 specificsPos++; 5084 } 5085 } 5086 5087 // Now we go through the remaining generic results and remove any 5088 // duplicate actions that are found here. 5089 N = results.size(); 5090 for (int i=specificsPos; i<N-1; i++) { 5091 final ResolveInfo rii = results.get(i); 5092 if (rii.filter == null) { 5093 continue; 5094 } 5095 5096 // Iterate over all of the actions of this result's intent 5097 // filter... typically this should be just one. 5098 final Iterator<String> it = rii.filter.actionsIterator(); 5099 if (it == null) { 5100 continue; 5101 } 5102 while (it.hasNext()) { 5103 final String action = it.next(); 5104 if (resultsAction != null && resultsAction.equals(action)) { 5105 // If this action was explicitly requested, then don't 5106 // remove things that have it. 5107 continue; 5108 } 5109 for (int j=i+1; j<N; j++) { 5110 final ResolveInfo rij = results.get(j); 5111 if (rij.filter != null && rij.filter.hasAction(action)) { 5112 results.remove(j); 5113 if (DEBUG_INTENT_MATCHING) Log.v( 5114 TAG, "Removing duplicate item from " + j 5115 + " due to action " + action + " at " + i); 5116 j--; 5117 N--; 5118 } 5119 } 5120 } 5121 5122 // If the caller didn't request filter information, drop it now 5123 // so we don't have to marshall/unmarshall it. 5124 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5125 rii.filter = null; 5126 } 5127 } 5128 5129 // Filter out the caller activity if so requested. 5130 if (caller != null) { 5131 N = results.size(); 5132 for (int i=0; i<N; i++) { 5133 ActivityInfo ainfo = results.get(i).activityInfo; 5134 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5135 && caller.getClassName().equals(ainfo.name)) { 5136 results.remove(i); 5137 break; 5138 } 5139 } 5140 } 5141 5142 // If the caller didn't request filter information, 5143 // drop them now so we don't have to 5144 // marshall/unmarshall it. 5145 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5146 N = results.size(); 5147 for (int i=0; i<N; i++) { 5148 results.get(i).filter = null; 5149 } 5150 } 5151 5152 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5153 return results; 5154 } 5155 5156 @Override 5157 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5158 int userId) { 5159 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5160 ComponentName comp = intent.getComponent(); 5161 if (comp == null) { 5162 if (intent.getSelector() != null) { 5163 intent = intent.getSelector(); 5164 comp = intent.getComponent(); 5165 } 5166 } 5167 if (comp != null) { 5168 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5169 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5170 if (ai != null) { 5171 ResolveInfo ri = new ResolveInfo(); 5172 ri.activityInfo = ai; 5173 list.add(ri); 5174 } 5175 return list; 5176 } 5177 5178 // reader 5179 synchronized (mPackages) { 5180 String pkgName = intent.getPackage(); 5181 if (pkgName == null) { 5182 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5183 } 5184 final PackageParser.Package pkg = mPackages.get(pkgName); 5185 if (pkg != null) { 5186 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5187 userId); 5188 } 5189 return null; 5190 } 5191 } 5192 5193 @Override 5194 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5195 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5196 if (!sUserManager.exists(userId)) return null; 5197 if (query != null) { 5198 if (query.size() >= 1) { 5199 // If there is more than one service with the same priority, 5200 // just arbitrarily pick the first one. 5201 return query.get(0); 5202 } 5203 } 5204 return null; 5205 } 5206 5207 @Override 5208 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5209 int userId) { 5210 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5211 ComponentName comp = intent.getComponent(); 5212 if (comp == null) { 5213 if (intent.getSelector() != null) { 5214 intent = intent.getSelector(); 5215 comp = intent.getComponent(); 5216 } 5217 } 5218 if (comp != null) { 5219 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5220 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5221 if (si != null) { 5222 final ResolveInfo ri = new ResolveInfo(); 5223 ri.serviceInfo = si; 5224 list.add(ri); 5225 } 5226 return list; 5227 } 5228 5229 // reader 5230 synchronized (mPackages) { 5231 String pkgName = intent.getPackage(); 5232 if (pkgName == null) { 5233 return mServices.queryIntent(intent, resolvedType, flags, userId); 5234 } 5235 final PackageParser.Package pkg = mPackages.get(pkgName); 5236 if (pkg != null) { 5237 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5238 userId); 5239 } 5240 return null; 5241 } 5242 } 5243 5244 @Override 5245 public List<ResolveInfo> queryIntentContentProviders( 5246 Intent intent, String resolvedType, int flags, int userId) { 5247 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5248 ComponentName comp = intent.getComponent(); 5249 if (comp == null) { 5250 if (intent.getSelector() != null) { 5251 intent = intent.getSelector(); 5252 comp = intent.getComponent(); 5253 } 5254 } 5255 if (comp != null) { 5256 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5257 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5258 if (pi != null) { 5259 final ResolveInfo ri = new ResolveInfo(); 5260 ri.providerInfo = pi; 5261 list.add(ri); 5262 } 5263 return list; 5264 } 5265 5266 // reader 5267 synchronized (mPackages) { 5268 String pkgName = intent.getPackage(); 5269 if (pkgName == null) { 5270 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5271 } 5272 final PackageParser.Package pkg = mPackages.get(pkgName); 5273 if (pkg != null) { 5274 return mProviders.queryIntentForPackage( 5275 intent, resolvedType, flags, pkg.providers, userId); 5276 } 5277 return null; 5278 } 5279 } 5280 5281 @Override 5282 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5283 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5284 5285 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5286 5287 // writer 5288 synchronized (mPackages) { 5289 ArrayList<PackageInfo> list; 5290 if (listUninstalled) { 5291 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5292 for (PackageSetting ps : mSettings.mPackages.values()) { 5293 PackageInfo pi; 5294 if (ps.pkg != null) { 5295 pi = generatePackageInfo(ps.pkg, flags, userId); 5296 } else { 5297 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5298 } 5299 if (pi != null) { 5300 list.add(pi); 5301 } 5302 } 5303 } else { 5304 list = new ArrayList<PackageInfo>(mPackages.size()); 5305 for (PackageParser.Package p : mPackages.values()) { 5306 PackageInfo pi = generatePackageInfo(p, flags, userId); 5307 if (pi != null) { 5308 list.add(pi); 5309 } 5310 } 5311 } 5312 5313 return new ParceledListSlice<PackageInfo>(list); 5314 } 5315 } 5316 5317 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5318 String[] permissions, boolean[] tmp, int flags, int userId) { 5319 int numMatch = 0; 5320 final PermissionsState permissionsState = ps.getPermissionsState(); 5321 for (int i=0; i<permissions.length; i++) { 5322 final String permission = permissions[i]; 5323 if (permissionsState.hasPermission(permission, userId)) { 5324 tmp[i] = true; 5325 numMatch++; 5326 } else { 5327 tmp[i] = false; 5328 } 5329 } 5330 if (numMatch == 0) { 5331 return; 5332 } 5333 PackageInfo pi; 5334 if (ps.pkg != null) { 5335 pi = generatePackageInfo(ps.pkg, flags, userId); 5336 } else { 5337 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5338 } 5339 // The above might return null in cases of uninstalled apps or install-state 5340 // skew across users/profiles. 5341 if (pi != null) { 5342 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5343 if (numMatch == permissions.length) { 5344 pi.requestedPermissions = permissions; 5345 } else { 5346 pi.requestedPermissions = new String[numMatch]; 5347 numMatch = 0; 5348 for (int i=0; i<permissions.length; i++) { 5349 if (tmp[i]) { 5350 pi.requestedPermissions[numMatch] = permissions[i]; 5351 numMatch++; 5352 } 5353 } 5354 } 5355 } 5356 list.add(pi); 5357 } 5358 } 5359 5360 @Override 5361 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5362 String[] permissions, int flags, int userId) { 5363 if (!sUserManager.exists(userId)) return null; 5364 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5365 5366 // writer 5367 synchronized (mPackages) { 5368 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5369 boolean[] tmpBools = new boolean[permissions.length]; 5370 if (listUninstalled) { 5371 for (PackageSetting ps : mSettings.mPackages.values()) { 5372 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5373 } 5374 } else { 5375 for (PackageParser.Package pkg : mPackages.values()) { 5376 PackageSetting ps = (PackageSetting)pkg.mExtras; 5377 if (ps != null) { 5378 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5379 userId); 5380 } 5381 } 5382 } 5383 5384 return new ParceledListSlice<PackageInfo>(list); 5385 } 5386 } 5387 5388 @Override 5389 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5390 if (!sUserManager.exists(userId)) return null; 5391 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5392 5393 // writer 5394 synchronized (mPackages) { 5395 ArrayList<ApplicationInfo> list; 5396 if (listUninstalled) { 5397 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5398 for (PackageSetting ps : mSettings.mPackages.values()) { 5399 ApplicationInfo ai; 5400 if (ps.pkg != null) { 5401 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5402 ps.readUserState(userId), userId); 5403 } else { 5404 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5405 } 5406 if (ai != null) { 5407 list.add(ai); 5408 } 5409 } 5410 } else { 5411 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5412 for (PackageParser.Package p : mPackages.values()) { 5413 if (p.mExtras != null) { 5414 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5415 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5416 if (ai != null) { 5417 list.add(ai); 5418 } 5419 } 5420 } 5421 } 5422 5423 return new ParceledListSlice<ApplicationInfo>(list); 5424 } 5425 } 5426 5427 public List<ApplicationInfo> getPersistentApplications(int flags) { 5428 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5429 5430 // reader 5431 synchronized (mPackages) { 5432 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5433 final int userId = UserHandle.getCallingUserId(); 5434 while (i.hasNext()) { 5435 final PackageParser.Package p = i.next(); 5436 if (p.applicationInfo != null 5437 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5438 && (!mSafeMode || isSystemApp(p))) { 5439 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5440 if (ps != null) { 5441 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5442 ps.readUserState(userId), userId); 5443 if (ai != null) { 5444 finalList.add(ai); 5445 } 5446 } 5447 } 5448 } 5449 } 5450 5451 return finalList; 5452 } 5453 5454 @Override 5455 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5456 if (!sUserManager.exists(userId)) return null; 5457 // reader 5458 synchronized (mPackages) { 5459 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5460 PackageSetting ps = provider != null 5461 ? mSettings.mPackages.get(provider.owner.packageName) 5462 : null; 5463 return ps != null 5464 && mSettings.isEnabledLPr(provider.info, flags, userId) 5465 && (!mSafeMode || (provider.info.applicationInfo.flags 5466 &ApplicationInfo.FLAG_SYSTEM) != 0) 5467 ? PackageParser.generateProviderInfo(provider, flags, 5468 ps.readUserState(userId), userId) 5469 : null; 5470 } 5471 } 5472 5473 /** 5474 * @deprecated 5475 */ 5476 @Deprecated 5477 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5478 // reader 5479 synchronized (mPackages) { 5480 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5481 .entrySet().iterator(); 5482 final int userId = UserHandle.getCallingUserId(); 5483 while (i.hasNext()) { 5484 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5485 PackageParser.Provider p = entry.getValue(); 5486 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5487 5488 if (ps != null && p.syncable 5489 && (!mSafeMode || (p.info.applicationInfo.flags 5490 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5491 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5492 ps.readUserState(userId), userId); 5493 if (info != null) { 5494 outNames.add(entry.getKey()); 5495 outInfo.add(info); 5496 } 5497 } 5498 } 5499 } 5500 } 5501 5502 @Override 5503 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5504 int uid, int flags) { 5505 ArrayList<ProviderInfo> finalList = null; 5506 // reader 5507 synchronized (mPackages) { 5508 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5509 final int userId = processName != null ? 5510 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5511 while (i.hasNext()) { 5512 final PackageParser.Provider p = i.next(); 5513 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5514 if (ps != null && p.info.authority != null 5515 && (processName == null 5516 || (p.info.processName.equals(processName) 5517 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5518 && mSettings.isEnabledLPr(p.info, flags, userId) 5519 && (!mSafeMode 5520 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5521 if (finalList == null) { 5522 finalList = new ArrayList<ProviderInfo>(3); 5523 } 5524 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5525 ps.readUserState(userId), userId); 5526 if (info != null) { 5527 finalList.add(info); 5528 } 5529 } 5530 } 5531 } 5532 5533 if (finalList != null) { 5534 Collections.sort(finalList, mProviderInitOrderSorter); 5535 return new ParceledListSlice<ProviderInfo>(finalList); 5536 } 5537 5538 return null; 5539 } 5540 5541 @Override 5542 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5543 int flags) { 5544 // reader 5545 synchronized (mPackages) { 5546 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5547 return PackageParser.generateInstrumentationInfo(i, flags); 5548 } 5549 } 5550 5551 @Override 5552 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5553 int flags) { 5554 ArrayList<InstrumentationInfo> finalList = 5555 new ArrayList<InstrumentationInfo>(); 5556 5557 // reader 5558 synchronized (mPackages) { 5559 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5560 while (i.hasNext()) { 5561 final PackageParser.Instrumentation p = i.next(); 5562 if (targetPackage == null 5563 || targetPackage.equals(p.info.targetPackage)) { 5564 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5565 flags); 5566 if (ii != null) { 5567 finalList.add(ii); 5568 } 5569 } 5570 } 5571 } 5572 5573 return finalList; 5574 } 5575 5576 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5577 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5578 if (overlays == null) { 5579 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5580 return; 5581 } 5582 for (PackageParser.Package opkg : overlays.values()) { 5583 // Not much to do if idmap fails: we already logged the error 5584 // and we certainly don't want to abort installation of pkg simply 5585 // because an overlay didn't fit properly. For these reasons, 5586 // ignore the return value of createIdmapForPackagePairLI. 5587 createIdmapForPackagePairLI(pkg, opkg); 5588 } 5589 } 5590 5591 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5592 PackageParser.Package opkg) { 5593 if (!opkg.mTrustedOverlay) { 5594 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5595 opkg.baseCodePath + ": overlay not trusted"); 5596 return false; 5597 } 5598 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5599 if (overlaySet == null) { 5600 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5601 opkg.baseCodePath + " but target package has no known overlays"); 5602 return false; 5603 } 5604 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5605 // TODO: generate idmap for split APKs 5606 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5607 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5608 + opkg.baseCodePath); 5609 return false; 5610 } 5611 PackageParser.Package[] overlayArray = 5612 overlaySet.values().toArray(new PackageParser.Package[0]); 5613 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5614 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5615 return p1.mOverlayPriority - p2.mOverlayPriority; 5616 } 5617 }; 5618 Arrays.sort(overlayArray, cmp); 5619 5620 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5621 int i = 0; 5622 for (PackageParser.Package p : overlayArray) { 5623 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5624 } 5625 return true; 5626 } 5627 5628 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5630 try { 5631 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5632 } finally { 5633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5634 } 5635 } 5636 5637 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5638 final File[] files = dir.listFiles(); 5639 if (ArrayUtils.isEmpty(files)) { 5640 Log.d(TAG, "No files in app dir " + dir); 5641 return; 5642 } 5643 5644 if (DEBUG_PACKAGE_SCANNING) { 5645 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5646 + " flags=0x" + Integer.toHexString(parseFlags)); 5647 } 5648 5649 for (File file : files) { 5650 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5651 && !PackageInstallerService.isStageName(file.getName()); 5652 if (!isPackage) { 5653 // Ignore entries which are not packages 5654 continue; 5655 } 5656 try { 5657 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5658 scanFlags, currentTime, null); 5659 } catch (PackageManagerException e) { 5660 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5661 5662 // Delete invalid userdata apps 5663 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5664 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5665 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5666 if (file.isDirectory()) { 5667 mInstaller.rmPackageDir(file.getAbsolutePath()); 5668 } else { 5669 file.delete(); 5670 } 5671 } 5672 } 5673 } 5674 } 5675 5676 private static File getSettingsProblemFile() { 5677 File dataDir = Environment.getDataDirectory(); 5678 File systemDir = new File(dataDir, "system"); 5679 File fname = new File(systemDir, "uiderrors.txt"); 5680 return fname; 5681 } 5682 5683 static void reportSettingsProblem(int priority, String msg) { 5684 logCriticalInfo(priority, msg); 5685 } 5686 5687 static void logCriticalInfo(int priority, String msg) { 5688 Slog.println(priority, TAG, msg); 5689 EventLogTags.writePmCriticalInfo(msg); 5690 try { 5691 File fname = getSettingsProblemFile(); 5692 FileOutputStream out = new FileOutputStream(fname, true); 5693 PrintWriter pw = new FastPrintWriter(out); 5694 SimpleDateFormat formatter = new SimpleDateFormat(); 5695 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5696 pw.println(dateString + ": " + msg); 5697 pw.close(); 5698 FileUtils.setPermissions( 5699 fname.toString(), 5700 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5701 -1, -1); 5702 } catch (java.io.IOException e) { 5703 } 5704 } 5705 5706 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5707 PackageParser.Package pkg, File srcFile, int parseFlags) 5708 throws PackageManagerException { 5709 if (ps != null 5710 && ps.codePath.equals(srcFile) 5711 && ps.timeStamp == srcFile.lastModified() 5712 && !isCompatSignatureUpdateNeeded(pkg) 5713 && !isRecoverSignatureUpdateNeeded(pkg)) { 5714 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5715 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5716 ArraySet<PublicKey> signingKs; 5717 synchronized (mPackages) { 5718 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5719 } 5720 if (ps.signatures.mSignatures != null 5721 && ps.signatures.mSignatures.length != 0 5722 && signingKs != null) { 5723 // Optimization: reuse the existing cached certificates 5724 // if the package appears to be unchanged. 5725 pkg.mSignatures = ps.signatures.mSignatures; 5726 pkg.mSigningKeys = signingKs; 5727 return; 5728 } 5729 5730 Slog.w(TAG, "PackageSetting for " + ps.name 5731 + " is missing signatures. Collecting certs again to recover them."); 5732 } else { 5733 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5734 } 5735 5736 try { 5737 pp.collectCertificates(pkg, parseFlags); 5738 pp.collectManifestDigest(pkg); 5739 } catch (PackageParserException e) { 5740 throw PackageManagerException.from(e); 5741 } 5742 } 5743 5744 /** 5745 * Traces a package scan. 5746 * @see #scanPackageLI(File, int, int, long, UserHandle) 5747 */ 5748 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5749 long currentTime, UserHandle user) throws PackageManagerException { 5750 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5751 try { 5752 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5753 } finally { 5754 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5755 } 5756 } 5757 5758 /** 5759 * Scans a package and returns the newly parsed package. 5760 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5761 */ 5762 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5763 long currentTime, UserHandle user) throws PackageManagerException { 5764 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5765 parseFlags |= mDefParseFlags; 5766 PackageParser pp = new PackageParser(); 5767 pp.setSeparateProcesses(mSeparateProcesses); 5768 pp.setOnlyCoreApps(mOnlyCore); 5769 pp.setDisplayMetrics(mMetrics); 5770 5771 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5772 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5773 } 5774 5775 final PackageParser.Package pkg; 5776 try { 5777 pkg = pp.parsePackage(scanFile, parseFlags); 5778 } catch (PackageParserException e) { 5779 throw PackageManagerException.from(e); 5780 } 5781 5782 PackageSetting ps = null; 5783 PackageSetting updatedPkg; 5784 // reader 5785 synchronized (mPackages) { 5786 // Look to see if we already know about this package. 5787 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5788 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5789 // This package has been renamed to its original name. Let's 5790 // use that. 5791 ps = mSettings.peekPackageLPr(oldName); 5792 } 5793 // If there was no original package, see one for the real package name. 5794 if (ps == null) { 5795 ps = mSettings.peekPackageLPr(pkg.packageName); 5796 } 5797 // Check to see if this package could be hiding/updating a system 5798 // package. Must look for it either under the original or real 5799 // package name depending on our state. 5800 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5801 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5802 } 5803 boolean updatedPkgBetter = false; 5804 // First check if this is a system package that may involve an update 5805 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5806 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5807 // it needs to drop FLAG_PRIVILEGED. 5808 if (locationIsPrivileged(scanFile)) { 5809 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5810 } else { 5811 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5812 } 5813 5814 if (ps != null && !ps.codePath.equals(scanFile)) { 5815 // The path has changed from what was last scanned... check the 5816 // version of the new path against what we have stored to determine 5817 // what to do. 5818 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5819 if (pkg.mVersionCode <= ps.versionCode) { 5820 // The system package has been updated and the code path does not match 5821 // Ignore entry. Skip it. 5822 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5823 + " ignored: updated version " + ps.versionCode 5824 + " better than this " + pkg.mVersionCode); 5825 if (!updatedPkg.codePath.equals(scanFile)) { 5826 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5827 + ps.name + " changing from " + updatedPkg.codePathString 5828 + " to " + scanFile); 5829 updatedPkg.codePath = scanFile; 5830 updatedPkg.codePathString = scanFile.toString(); 5831 updatedPkg.resourcePath = scanFile; 5832 updatedPkg.resourcePathString = scanFile.toString(); 5833 } 5834 updatedPkg.pkg = pkg; 5835 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5836 "Package " + ps.name + " at " + scanFile 5837 + " ignored: updated version " + ps.versionCode 5838 + " better than this " + pkg.mVersionCode); 5839 } else { 5840 // The current app on the system partition is better than 5841 // what we have updated to on the data partition; switch 5842 // back to the system partition version. 5843 // At this point, its safely assumed that package installation for 5844 // apps in system partition will go through. If not there won't be a working 5845 // version of the app 5846 // writer 5847 synchronized (mPackages) { 5848 // Just remove the loaded entries from package lists. 5849 mPackages.remove(ps.name); 5850 } 5851 5852 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5853 + " reverting from " + ps.codePathString 5854 + ": new version " + pkg.mVersionCode 5855 + " better than installed " + ps.versionCode); 5856 5857 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5858 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5859 synchronized (mInstallLock) { 5860 args.cleanUpResourcesLI(); 5861 } 5862 synchronized (mPackages) { 5863 mSettings.enableSystemPackageLPw(ps.name); 5864 } 5865 updatedPkgBetter = true; 5866 } 5867 } 5868 } 5869 5870 if (updatedPkg != null) { 5871 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5872 // initially 5873 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5874 5875 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5876 // flag set initially 5877 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5878 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5879 } 5880 } 5881 5882 // Verify certificates against what was last scanned 5883 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5884 5885 /* 5886 * A new system app appeared, but we already had a non-system one of the 5887 * same name installed earlier. 5888 */ 5889 boolean shouldHideSystemApp = false; 5890 if (updatedPkg == null && ps != null 5891 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5892 /* 5893 * Check to make sure the signatures match first. If they don't, 5894 * wipe the installed application and its data. 5895 */ 5896 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5897 != PackageManager.SIGNATURE_MATCH) { 5898 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5899 + " signatures don't match existing userdata copy; removing"); 5900 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5901 ps = null; 5902 } else { 5903 /* 5904 * If the newly-added system app is an older version than the 5905 * already installed version, hide it. It will be scanned later 5906 * and re-added like an update. 5907 */ 5908 if (pkg.mVersionCode <= ps.versionCode) { 5909 shouldHideSystemApp = true; 5910 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5911 + " but new version " + pkg.mVersionCode + " better than installed " 5912 + ps.versionCode + "; hiding system"); 5913 } else { 5914 /* 5915 * The newly found system app is a newer version that the 5916 * one previously installed. Simply remove the 5917 * already-installed application and replace it with our own 5918 * while keeping the application data. 5919 */ 5920 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5921 + " reverting from " + ps.codePathString + ": new version " 5922 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5923 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5924 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5925 synchronized (mInstallLock) { 5926 args.cleanUpResourcesLI(); 5927 } 5928 } 5929 } 5930 } 5931 5932 // The apk is forward locked (not public) if its code and resources 5933 // are kept in different files. (except for app in either system or 5934 // vendor path). 5935 // TODO grab this value from PackageSettings 5936 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5937 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5938 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5939 } 5940 } 5941 5942 // TODO: extend to support forward-locked splits 5943 String resourcePath = null; 5944 String baseResourcePath = null; 5945 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5946 if (ps != null && ps.resourcePathString != null) { 5947 resourcePath = ps.resourcePathString; 5948 baseResourcePath = ps.resourcePathString; 5949 } else { 5950 // Should not happen at all. Just log an error. 5951 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5952 } 5953 } else { 5954 resourcePath = pkg.codePath; 5955 baseResourcePath = pkg.baseCodePath; 5956 } 5957 5958 // Set application objects path explicitly. 5959 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5960 pkg.applicationInfo.setCodePath(pkg.codePath); 5961 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5962 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5963 pkg.applicationInfo.setResourcePath(resourcePath); 5964 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5965 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5966 5967 // Note that we invoke the following method only if we are about to unpack an application 5968 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5969 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5970 5971 /* 5972 * If the system app should be overridden by a previously installed 5973 * data, hide the system app now and let the /data/app scan pick it up 5974 * again. 5975 */ 5976 if (shouldHideSystemApp) { 5977 synchronized (mPackages) { 5978 /* 5979 * We have to grant systems permissions before we hide, because 5980 * grantPermissions will assume the package update is trying to 5981 * expand its permissions. 5982 */ 5983 grantPermissionsLPw(pkg, true, pkg.packageName); 5984 mSettings.disableSystemPackageLPw(pkg.packageName); 5985 } 5986 } 5987 5988 return scannedPkg; 5989 } 5990 5991 private static String fixProcessName(String defProcessName, 5992 String processName, int uid) { 5993 if (processName == null) { 5994 return defProcessName; 5995 } 5996 return processName; 5997 } 5998 5999 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6000 throws PackageManagerException { 6001 if (pkgSetting.signatures.mSignatures != null) { 6002 // Already existing package. Make sure signatures match 6003 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6004 == PackageManager.SIGNATURE_MATCH; 6005 if (!match) { 6006 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6007 == PackageManager.SIGNATURE_MATCH; 6008 } 6009 if (!match) { 6010 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6011 == PackageManager.SIGNATURE_MATCH; 6012 } 6013 if (!match) { 6014 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6015 + pkg.packageName + " signatures do not match the " 6016 + "previously installed version; ignoring!"); 6017 } 6018 } 6019 6020 // Check for shared user signatures 6021 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6022 // Already existing package. Make sure signatures match 6023 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6024 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6025 if (!match) { 6026 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6027 == PackageManager.SIGNATURE_MATCH; 6028 } 6029 if (!match) { 6030 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6031 == PackageManager.SIGNATURE_MATCH; 6032 } 6033 if (!match) { 6034 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6035 "Package " + pkg.packageName 6036 + " has no signatures that match those in shared user " 6037 + pkgSetting.sharedUser.name + "; ignoring!"); 6038 } 6039 } 6040 } 6041 6042 /** 6043 * Enforces that only the system UID or root's UID can call a method exposed 6044 * via Binder. 6045 * 6046 * @param message used as message if SecurityException is thrown 6047 * @throws SecurityException if the caller is not system or root 6048 */ 6049 private static final void enforceSystemOrRoot(String message) { 6050 final int uid = Binder.getCallingUid(); 6051 if (uid != Process.SYSTEM_UID && uid != 0) { 6052 throw new SecurityException(message); 6053 } 6054 } 6055 6056 @Override 6057 public void performBootDexOpt() { 6058 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6059 6060 // Before everything else, see whether we need to fstrim. 6061 try { 6062 IMountService ms = PackageHelper.getMountService(); 6063 if (ms != null) { 6064 final boolean isUpgrade = isUpgrade(); 6065 boolean doTrim = isUpgrade; 6066 if (doTrim) { 6067 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6068 } else { 6069 final long interval = android.provider.Settings.Global.getLong( 6070 mContext.getContentResolver(), 6071 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6072 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6073 if (interval > 0) { 6074 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6075 if (timeSinceLast > interval) { 6076 doTrim = true; 6077 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6078 + "; running immediately"); 6079 } 6080 } 6081 } 6082 if (doTrim) { 6083 if (!isFirstBoot()) { 6084 try { 6085 ActivityManagerNative.getDefault().showBootMessage( 6086 mContext.getResources().getString( 6087 R.string.android_upgrading_fstrim), true); 6088 } catch (RemoteException e) { 6089 } 6090 } 6091 ms.runMaintenance(); 6092 } 6093 } else { 6094 Slog.e(TAG, "Mount service unavailable!"); 6095 } 6096 } catch (RemoteException e) { 6097 // Can't happen; MountService is local 6098 } 6099 6100 final ArraySet<PackageParser.Package> pkgs; 6101 synchronized (mPackages) { 6102 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6103 } 6104 6105 if (pkgs != null) { 6106 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6107 // in case the device runs out of space. 6108 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6109 // Give priority to core apps. 6110 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6111 PackageParser.Package pkg = it.next(); 6112 if (pkg.coreApp) { 6113 if (DEBUG_DEXOPT) { 6114 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6115 } 6116 sortedPkgs.add(pkg); 6117 it.remove(); 6118 } 6119 } 6120 // Give priority to system apps that listen for pre boot complete. 6121 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6122 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6123 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6124 PackageParser.Package pkg = it.next(); 6125 if (pkgNames.contains(pkg.packageName)) { 6126 if (DEBUG_DEXOPT) { 6127 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6128 } 6129 sortedPkgs.add(pkg); 6130 it.remove(); 6131 } 6132 } 6133 // Give priority to system apps. 6134 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6135 PackageParser.Package pkg = it.next(); 6136 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6137 if (DEBUG_DEXOPT) { 6138 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6139 } 6140 sortedPkgs.add(pkg); 6141 it.remove(); 6142 } 6143 } 6144 // Give priority to updated system apps. 6145 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6146 PackageParser.Package pkg = it.next(); 6147 if (pkg.isUpdatedSystemApp()) { 6148 if (DEBUG_DEXOPT) { 6149 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6150 } 6151 sortedPkgs.add(pkg); 6152 it.remove(); 6153 } 6154 } 6155 // Give priority to apps that listen for boot complete. 6156 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6157 pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6158 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6159 PackageParser.Package pkg = it.next(); 6160 if (pkgNames.contains(pkg.packageName)) { 6161 if (DEBUG_DEXOPT) { 6162 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6163 } 6164 sortedPkgs.add(pkg); 6165 it.remove(); 6166 } 6167 } 6168 // Filter out packages that aren't recently used. 6169 filterRecentlyUsedApps(pkgs); 6170 // Add all remaining apps. 6171 for (PackageParser.Package pkg : pkgs) { 6172 if (DEBUG_DEXOPT) { 6173 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6174 } 6175 sortedPkgs.add(pkg); 6176 } 6177 6178 // If we want to be lazy, filter everything that wasn't recently used. 6179 if (mLazyDexOpt) { 6180 filterRecentlyUsedApps(sortedPkgs); 6181 } 6182 6183 int i = 0; 6184 int total = sortedPkgs.size(); 6185 File dataDir = Environment.getDataDirectory(); 6186 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6187 if (lowThreshold == 0) { 6188 throw new IllegalStateException("Invalid low memory threshold"); 6189 } 6190 for (PackageParser.Package pkg : sortedPkgs) { 6191 long usableSpace = dataDir.getUsableSpace(); 6192 if (usableSpace < lowThreshold) { 6193 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6194 break; 6195 } 6196 performBootDexOpt(pkg, ++i, total); 6197 } 6198 } 6199 } 6200 6201 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6202 // Filter out packages that aren't recently used. 6203 // 6204 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6205 // should do a full dexopt. 6206 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6207 int total = pkgs.size(); 6208 int skipped = 0; 6209 long now = System.currentTimeMillis(); 6210 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6211 PackageParser.Package pkg = i.next(); 6212 long then = pkg.mLastPackageUsageTimeInMills; 6213 if (then + mDexOptLRUThresholdInMills < now) { 6214 if (DEBUG_DEXOPT) { 6215 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6216 ((then == 0) ? "never" : new Date(then))); 6217 } 6218 i.remove(); 6219 skipped++; 6220 } 6221 } 6222 if (DEBUG_DEXOPT) { 6223 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6224 } 6225 } 6226 } 6227 6228 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6229 List<ResolveInfo> ris = null; 6230 try { 6231 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6232 intent, null, 0, userId); 6233 } catch (RemoteException e) { 6234 } 6235 ArraySet<String> pkgNames = new ArraySet<String>(); 6236 if (ris != null) { 6237 for (ResolveInfo ri : ris) { 6238 pkgNames.add(ri.activityInfo.packageName); 6239 } 6240 } 6241 return pkgNames; 6242 } 6243 6244 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6245 if (DEBUG_DEXOPT) { 6246 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6247 } 6248 if (!isFirstBoot()) { 6249 try { 6250 ActivityManagerNative.getDefault().showBootMessage( 6251 mContext.getResources().getString(R.string.android_upgrading_apk, 6252 curr, total), true); 6253 } catch (RemoteException e) { 6254 } 6255 } 6256 PackageParser.Package p = pkg; 6257 synchronized (mInstallLock) { 6258 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6259 false /* force dex */, false /* defer */, true /* include dependencies */); 6260 } 6261 } 6262 6263 @Override 6264 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6265 return performDexOpt(packageName, instructionSet, false); 6266 } 6267 6268 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6269 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6270 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6271 if (!dexopt && !updateUsage) { 6272 // We aren't going to dexopt or update usage, so bail early. 6273 return false; 6274 } 6275 PackageParser.Package p; 6276 final String targetInstructionSet; 6277 synchronized (mPackages) { 6278 p = mPackages.get(packageName); 6279 if (p == null) { 6280 return false; 6281 } 6282 if (updateUsage) { 6283 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6284 } 6285 mPackageUsage.write(false); 6286 if (!dexopt) { 6287 // We aren't going to dexopt, so bail early. 6288 return false; 6289 } 6290 6291 targetInstructionSet = instructionSet != null ? instructionSet : 6292 getPrimaryInstructionSet(p.applicationInfo); 6293 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6294 return false; 6295 } 6296 } 6297 long callingId = Binder.clearCallingIdentity(); 6298 try { 6299 synchronized (mInstallLock) { 6300 final String[] instructionSets = new String[] { targetInstructionSet }; 6301 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6302 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6303 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6304 } 6305 } finally { 6306 Binder.restoreCallingIdentity(callingId); 6307 } 6308 } 6309 6310 public ArraySet<String> getPackagesThatNeedDexOpt() { 6311 ArraySet<String> pkgs = null; 6312 synchronized (mPackages) { 6313 for (PackageParser.Package p : mPackages.values()) { 6314 if (DEBUG_DEXOPT) { 6315 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6316 } 6317 if (!p.mDexOptPerformed.isEmpty()) { 6318 continue; 6319 } 6320 if (pkgs == null) { 6321 pkgs = new ArraySet<String>(); 6322 } 6323 pkgs.add(p.packageName); 6324 } 6325 } 6326 return pkgs; 6327 } 6328 6329 public void shutdown() { 6330 mPackageUsage.write(true); 6331 } 6332 6333 @Override 6334 public void forceDexOpt(String packageName) { 6335 enforceSystemOrRoot("forceDexOpt"); 6336 6337 PackageParser.Package pkg; 6338 synchronized (mPackages) { 6339 pkg = mPackages.get(packageName); 6340 if (pkg == null) { 6341 throw new IllegalArgumentException("Missing package: " + packageName); 6342 } 6343 } 6344 6345 synchronized (mInstallLock) { 6346 final String[] instructionSets = new String[] { 6347 getPrimaryInstructionSet(pkg.applicationInfo) }; 6348 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6349 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6350 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6351 throw new IllegalStateException("Failed to dexopt: " + res); 6352 } 6353 } 6354 } 6355 6356 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6357 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6358 Slog.w(TAG, "Unable to update from " + oldPkg.name 6359 + " to " + newPkg.packageName 6360 + ": old package not in system partition"); 6361 return false; 6362 } else if (mPackages.get(oldPkg.name) != null) { 6363 Slog.w(TAG, "Unable to update from " + oldPkg.name 6364 + " to " + newPkg.packageName 6365 + ": old package still exists"); 6366 return false; 6367 } 6368 return true; 6369 } 6370 6371 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6372 int[] users = sUserManager.getUserIds(); 6373 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6374 if (res < 0) { 6375 return res; 6376 } 6377 for (int user : users) { 6378 if (user != 0) { 6379 res = mInstaller.createUserData(volumeUuid, packageName, 6380 UserHandle.getUid(user, uid), user, seinfo); 6381 if (res < 0) { 6382 return res; 6383 } 6384 } 6385 } 6386 return res; 6387 } 6388 6389 private int removeDataDirsLI(String volumeUuid, String packageName) { 6390 int[] users = sUserManager.getUserIds(); 6391 int res = 0; 6392 for (int user : users) { 6393 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6394 if (resInner < 0) { 6395 res = resInner; 6396 } 6397 } 6398 6399 return res; 6400 } 6401 6402 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6403 int[] users = sUserManager.getUserIds(); 6404 int res = 0; 6405 for (int user : users) { 6406 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6407 if (resInner < 0) { 6408 res = resInner; 6409 } 6410 } 6411 return res; 6412 } 6413 6414 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6415 PackageParser.Package changingLib) { 6416 if (file.path != null) { 6417 usesLibraryFiles.add(file.path); 6418 return; 6419 } 6420 PackageParser.Package p = mPackages.get(file.apk); 6421 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6422 // If we are doing this while in the middle of updating a library apk, 6423 // then we need to make sure to use that new apk for determining the 6424 // dependencies here. (We haven't yet finished committing the new apk 6425 // to the package manager state.) 6426 if (p == null || p.packageName.equals(changingLib.packageName)) { 6427 p = changingLib; 6428 } 6429 } 6430 if (p != null) { 6431 usesLibraryFiles.addAll(p.getAllCodePaths()); 6432 } 6433 } 6434 6435 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6436 PackageParser.Package changingLib) throws PackageManagerException { 6437 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6438 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6439 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6440 for (int i=0; i<N; i++) { 6441 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6442 if (file == null) { 6443 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6444 "Package " + pkg.packageName + " requires unavailable shared library " 6445 + pkg.usesLibraries.get(i) + "; failing!"); 6446 } 6447 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6448 } 6449 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6450 for (int i=0; i<N; i++) { 6451 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6452 if (file == null) { 6453 Slog.w(TAG, "Package " + pkg.packageName 6454 + " desires unavailable shared library " 6455 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6456 } else { 6457 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6458 } 6459 } 6460 N = usesLibraryFiles.size(); 6461 if (N > 0) { 6462 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6463 } else { 6464 pkg.usesLibraryFiles = null; 6465 } 6466 } 6467 } 6468 6469 private static boolean hasString(List<String> list, List<String> which) { 6470 if (list == null) { 6471 return false; 6472 } 6473 for (int i=list.size()-1; i>=0; i--) { 6474 for (int j=which.size()-1; j>=0; j--) { 6475 if (which.get(j).equals(list.get(i))) { 6476 return true; 6477 } 6478 } 6479 } 6480 return false; 6481 } 6482 6483 private void updateAllSharedLibrariesLPw() { 6484 for (PackageParser.Package pkg : mPackages.values()) { 6485 try { 6486 updateSharedLibrariesLPw(pkg, null); 6487 } catch (PackageManagerException e) { 6488 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6489 } 6490 } 6491 } 6492 6493 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6494 PackageParser.Package changingPkg) { 6495 ArrayList<PackageParser.Package> res = null; 6496 for (PackageParser.Package pkg : mPackages.values()) { 6497 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6498 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6499 if (res == null) { 6500 res = new ArrayList<PackageParser.Package>(); 6501 } 6502 res.add(pkg); 6503 try { 6504 updateSharedLibrariesLPw(pkg, changingPkg); 6505 } catch (PackageManagerException e) { 6506 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6507 } 6508 } 6509 } 6510 return res; 6511 } 6512 6513 /** 6514 * Derive the value of the {@code cpuAbiOverride} based on the provided 6515 * value and an optional stored value from the package settings. 6516 */ 6517 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6518 String cpuAbiOverride = null; 6519 6520 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6521 cpuAbiOverride = null; 6522 } else if (abiOverride != null) { 6523 cpuAbiOverride = abiOverride; 6524 } else if (settings != null) { 6525 cpuAbiOverride = settings.cpuAbiOverrideString; 6526 } 6527 6528 return cpuAbiOverride; 6529 } 6530 6531 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6532 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6533 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6534 try { 6535 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6536 } finally { 6537 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6538 } 6539 } 6540 6541 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6542 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6543 boolean success = false; 6544 try { 6545 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6546 currentTime, user); 6547 success = true; 6548 return res; 6549 } finally { 6550 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6551 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6552 } 6553 } 6554 } 6555 6556 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6557 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6558 final File scanFile = new File(pkg.codePath); 6559 if (pkg.applicationInfo.getCodePath() == null || 6560 pkg.applicationInfo.getResourcePath() == null) { 6561 // Bail out. The resource and code paths haven't been set. 6562 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6563 "Code and resource paths haven't been set correctly"); 6564 } 6565 6566 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6567 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6568 } else { 6569 // Only allow system apps to be flagged as core apps. 6570 pkg.coreApp = false; 6571 } 6572 6573 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6574 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6575 } 6576 6577 if (mCustomResolverComponentName != null && 6578 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6579 setUpCustomResolverActivity(pkg); 6580 } 6581 6582 if (pkg.packageName.equals("android")) { 6583 synchronized (mPackages) { 6584 if (mAndroidApplication != null) { 6585 Slog.w(TAG, "*************************************************"); 6586 Slog.w(TAG, "Core android package being redefined. Skipping."); 6587 Slog.w(TAG, " file=" + scanFile); 6588 Slog.w(TAG, "*************************************************"); 6589 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6590 "Core android package being redefined. Skipping."); 6591 } 6592 6593 // Set up information for our fall-back user intent resolution activity. 6594 mPlatformPackage = pkg; 6595 pkg.mVersionCode = mSdkVersion; 6596 mAndroidApplication = pkg.applicationInfo; 6597 6598 if (!mResolverReplaced) { 6599 mResolveActivity.applicationInfo = mAndroidApplication; 6600 mResolveActivity.name = ResolverActivity.class.getName(); 6601 mResolveActivity.packageName = mAndroidApplication.packageName; 6602 mResolveActivity.processName = "system:ui"; 6603 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6604 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6605 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6606 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6607 mResolveActivity.exported = true; 6608 mResolveActivity.enabled = true; 6609 mResolveInfo.activityInfo = mResolveActivity; 6610 mResolveInfo.priority = 0; 6611 mResolveInfo.preferredOrder = 0; 6612 mResolveInfo.match = 0; 6613 mResolveComponentName = new ComponentName( 6614 mAndroidApplication.packageName, mResolveActivity.name); 6615 } 6616 } 6617 } 6618 6619 if (DEBUG_PACKAGE_SCANNING) { 6620 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6621 Log.d(TAG, "Scanning package " + pkg.packageName); 6622 } 6623 6624 if (mPackages.containsKey(pkg.packageName) 6625 || mSharedLibraries.containsKey(pkg.packageName)) { 6626 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6627 "Application package " + pkg.packageName 6628 + " already installed. Skipping duplicate."); 6629 } 6630 6631 // If we're only installing presumed-existing packages, require that the 6632 // scanned APK is both already known and at the path previously established 6633 // for it. Previously unknown packages we pick up normally, but if we have an 6634 // a priori expectation about this package's install presence, enforce it. 6635 // With a singular exception for new system packages. When an OTA contains 6636 // a new system package, we allow the codepath to change from a system location 6637 // to the user-installed location. If we don't allow this change, any newer, 6638 // user-installed version of the application will be ignored. 6639 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6640 if (mExpectingBetter.containsKey(pkg.packageName)) { 6641 logCriticalInfo(Log.WARN, 6642 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6643 } else { 6644 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6645 if (known != null) { 6646 if (DEBUG_PACKAGE_SCANNING) { 6647 Log.d(TAG, "Examining " + pkg.codePath 6648 + " and requiring known paths " + known.codePathString 6649 + " & " + known.resourcePathString); 6650 } 6651 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6652 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6653 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6654 "Application package " + pkg.packageName 6655 + " found at " + pkg.applicationInfo.getCodePath() 6656 + " but expected at " + known.codePathString + "; ignoring."); 6657 } 6658 } 6659 } 6660 } 6661 6662 // Initialize package source and resource directories 6663 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6664 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6665 6666 SharedUserSetting suid = null; 6667 PackageSetting pkgSetting = null; 6668 6669 if (!isSystemApp(pkg)) { 6670 // Only system apps can use these features. 6671 pkg.mOriginalPackages = null; 6672 pkg.mRealPackage = null; 6673 pkg.mAdoptPermissions = null; 6674 } 6675 6676 // writer 6677 synchronized (mPackages) { 6678 if (pkg.mSharedUserId != null) { 6679 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6680 if (suid == null) { 6681 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6682 "Creating application package " + pkg.packageName 6683 + " for shared user failed"); 6684 } 6685 if (DEBUG_PACKAGE_SCANNING) { 6686 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6687 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6688 + "): packages=" + suid.packages); 6689 } 6690 } 6691 6692 // Check if we are renaming from an original package name. 6693 PackageSetting origPackage = null; 6694 String realName = null; 6695 if (pkg.mOriginalPackages != null) { 6696 // This package may need to be renamed to a previously 6697 // installed name. Let's check on that... 6698 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6699 if (pkg.mOriginalPackages.contains(renamed)) { 6700 // This package had originally been installed as the 6701 // original name, and we have already taken care of 6702 // transitioning to the new one. Just update the new 6703 // one to continue using the old name. 6704 realName = pkg.mRealPackage; 6705 if (!pkg.packageName.equals(renamed)) { 6706 // Callers into this function may have already taken 6707 // care of renaming the package; only do it here if 6708 // it is not already done. 6709 pkg.setPackageName(renamed); 6710 } 6711 6712 } else { 6713 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6714 if ((origPackage = mSettings.peekPackageLPr( 6715 pkg.mOriginalPackages.get(i))) != null) { 6716 // We do have the package already installed under its 6717 // original name... should we use it? 6718 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6719 // New package is not compatible with original. 6720 origPackage = null; 6721 continue; 6722 } else if (origPackage.sharedUser != null) { 6723 // Make sure uid is compatible between packages. 6724 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6725 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6726 + " to " + pkg.packageName + ": old uid " 6727 + origPackage.sharedUser.name 6728 + " differs from " + pkg.mSharedUserId); 6729 origPackage = null; 6730 continue; 6731 } 6732 } else { 6733 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6734 + pkg.packageName + " to old name " + origPackage.name); 6735 } 6736 break; 6737 } 6738 } 6739 } 6740 } 6741 6742 if (mTransferedPackages.contains(pkg.packageName)) { 6743 Slog.w(TAG, "Package " + pkg.packageName 6744 + " was transferred to another, but its .apk remains"); 6745 } 6746 6747 // Just create the setting, don't add it yet. For already existing packages 6748 // the PkgSetting exists already and doesn't have to be created. 6749 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6750 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6751 pkg.applicationInfo.primaryCpuAbi, 6752 pkg.applicationInfo.secondaryCpuAbi, 6753 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6754 user, false); 6755 if (pkgSetting == null) { 6756 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6757 "Creating application package " + pkg.packageName + " failed"); 6758 } 6759 6760 if (pkgSetting.origPackage != null) { 6761 // If we are first transitioning from an original package, 6762 // fix up the new package's name now. We need to do this after 6763 // looking up the package under its new name, so getPackageLP 6764 // can take care of fiddling things correctly. 6765 pkg.setPackageName(origPackage.name); 6766 6767 // File a report about this. 6768 String msg = "New package " + pkgSetting.realName 6769 + " renamed to replace old package " + pkgSetting.name; 6770 reportSettingsProblem(Log.WARN, msg); 6771 6772 // Make a note of it. 6773 mTransferedPackages.add(origPackage.name); 6774 6775 // No longer need to retain this. 6776 pkgSetting.origPackage = null; 6777 } 6778 6779 if (realName != null) { 6780 // Make a note of it. 6781 mTransferedPackages.add(pkg.packageName); 6782 } 6783 6784 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6785 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6786 } 6787 6788 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6789 // Check all shared libraries and map to their actual file path. 6790 // We only do this here for apps not on a system dir, because those 6791 // are the only ones that can fail an install due to this. We 6792 // will take care of the system apps by updating all of their 6793 // library paths after the scan is done. 6794 updateSharedLibrariesLPw(pkg, null); 6795 } 6796 6797 if (mFoundPolicyFile) { 6798 SELinuxMMAC.assignSeinfoValue(pkg); 6799 } 6800 6801 pkg.applicationInfo.uid = pkgSetting.appId; 6802 pkg.mExtras = pkgSetting; 6803 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6804 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6805 // We just determined the app is signed correctly, so bring 6806 // over the latest parsed certs. 6807 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6808 } else { 6809 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6810 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6811 "Package " + pkg.packageName + " upgrade keys do not match the " 6812 + "previously installed version"); 6813 } else { 6814 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6815 String msg = "System package " + pkg.packageName 6816 + " signature changed; retaining data."; 6817 reportSettingsProblem(Log.WARN, msg); 6818 } 6819 } 6820 } else { 6821 try { 6822 verifySignaturesLP(pkgSetting, pkg); 6823 // We just determined the app is signed correctly, so bring 6824 // over the latest parsed certs. 6825 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6826 } catch (PackageManagerException e) { 6827 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6828 throw e; 6829 } 6830 // The signature has changed, but this package is in the system 6831 // image... let's recover! 6832 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6833 // However... if this package is part of a shared user, but it 6834 // doesn't match the signature of the shared user, let's fail. 6835 // What this means is that you can't change the signatures 6836 // associated with an overall shared user, which doesn't seem all 6837 // that unreasonable. 6838 if (pkgSetting.sharedUser != null) { 6839 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6840 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6841 throw new PackageManagerException( 6842 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6843 "Signature mismatch for shared user : " 6844 + pkgSetting.sharedUser); 6845 } 6846 } 6847 // File a report about this. 6848 String msg = "System package " + pkg.packageName 6849 + " signature changed; retaining data."; 6850 reportSettingsProblem(Log.WARN, msg); 6851 } 6852 } 6853 // Verify that this new package doesn't have any content providers 6854 // that conflict with existing packages. Only do this if the 6855 // package isn't already installed, since we don't want to break 6856 // things that are installed. 6857 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6858 final int N = pkg.providers.size(); 6859 int i; 6860 for (i=0; i<N; i++) { 6861 PackageParser.Provider p = pkg.providers.get(i); 6862 if (p.info.authority != null) { 6863 String names[] = p.info.authority.split(";"); 6864 for (int j = 0; j < names.length; j++) { 6865 if (mProvidersByAuthority.containsKey(names[j])) { 6866 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6867 final String otherPackageName = 6868 ((other != null && other.getComponentName() != null) ? 6869 other.getComponentName().getPackageName() : "?"); 6870 throw new PackageManagerException( 6871 INSTALL_FAILED_CONFLICTING_PROVIDER, 6872 "Can't install because provider name " + names[j] 6873 + " (in package " + pkg.applicationInfo.packageName 6874 + ") is already used by " + otherPackageName); 6875 } 6876 } 6877 } 6878 } 6879 } 6880 6881 if (pkg.mAdoptPermissions != null) { 6882 // This package wants to adopt ownership of permissions from 6883 // another package. 6884 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6885 final String origName = pkg.mAdoptPermissions.get(i); 6886 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6887 if (orig != null) { 6888 if (verifyPackageUpdateLPr(orig, pkg)) { 6889 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6890 + pkg.packageName); 6891 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6892 } 6893 } 6894 } 6895 } 6896 } 6897 6898 final String pkgName = pkg.packageName; 6899 6900 final long scanFileTime = scanFile.lastModified(); 6901 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6902 pkg.applicationInfo.processName = fixProcessName( 6903 pkg.applicationInfo.packageName, 6904 pkg.applicationInfo.processName, 6905 pkg.applicationInfo.uid); 6906 6907 File dataPath; 6908 if (mPlatformPackage == pkg) { 6909 // The system package is special. 6910 dataPath = new File(Environment.getDataDirectory(), "system"); 6911 6912 pkg.applicationInfo.dataDir = dataPath.getPath(); 6913 6914 } else { 6915 // This is a normal package, need to make its data directory. 6916 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6917 UserHandle.USER_OWNER, pkg.packageName); 6918 6919 boolean uidError = false; 6920 if (dataPath.exists()) { 6921 int currentUid = 0; 6922 try { 6923 StructStat stat = Os.stat(dataPath.getPath()); 6924 currentUid = stat.st_uid; 6925 } catch (ErrnoException e) { 6926 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6927 } 6928 6929 // If we have mismatched owners for the data path, we have a problem. 6930 if (currentUid != pkg.applicationInfo.uid) { 6931 boolean recovered = false; 6932 if (currentUid == 0) { 6933 // The directory somehow became owned by root. Wow. 6934 // This is probably because the system was stopped while 6935 // installd was in the middle of messing with its libs 6936 // directory. Ask installd to fix that. 6937 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6938 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6939 if (ret >= 0) { 6940 recovered = true; 6941 String msg = "Package " + pkg.packageName 6942 + " unexpectedly changed to uid 0; recovered to " + 6943 + pkg.applicationInfo.uid; 6944 reportSettingsProblem(Log.WARN, msg); 6945 } 6946 } 6947 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6948 || (scanFlags&SCAN_BOOTING) != 0)) { 6949 // If this is a system app, we can at least delete its 6950 // current data so the application will still work. 6951 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6952 if (ret >= 0) { 6953 // TODO: Kill the processes first 6954 // Old data gone! 6955 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6956 ? "System package " : "Third party package "; 6957 String msg = prefix + pkg.packageName 6958 + " has changed from uid: " 6959 + currentUid + " to " 6960 + pkg.applicationInfo.uid + "; old data erased"; 6961 reportSettingsProblem(Log.WARN, msg); 6962 recovered = true; 6963 6964 // And now re-install the app. 6965 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6966 pkg.applicationInfo.seinfo); 6967 if (ret == -1) { 6968 // Ack should not happen! 6969 msg = prefix + pkg.packageName 6970 + " could not have data directory re-created after delete."; 6971 reportSettingsProblem(Log.WARN, msg); 6972 throw new PackageManagerException( 6973 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6974 } 6975 } 6976 if (!recovered) { 6977 mHasSystemUidErrors = true; 6978 } 6979 } else if (!recovered) { 6980 // If we allow this install to proceed, we will be broken. 6981 // Abort, abort! 6982 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6983 "scanPackageLI"); 6984 } 6985 if (!recovered) { 6986 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6987 + pkg.applicationInfo.uid + "/fs_" 6988 + currentUid; 6989 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6990 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6991 String msg = "Package " + pkg.packageName 6992 + " has mismatched uid: " 6993 + currentUid + " on disk, " 6994 + pkg.applicationInfo.uid + " in settings"; 6995 // writer 6996 synchronized (mPackages) { 6997 mSettings.mReadMessages.append(msg); 6998 mSettings.mReadMessages.append('\n'); 6999 uidError = true; 7000 if (!pkgSetting.uidError) { 7001 reportSettingsProblem(Log.ERROR, msg); 7002 } 7003 } 7004 } 7005 } 7006 pkg.applicationInfo.dataDir = dataPath.getPath(); 7007 if (mShouldRestoreconData) { 7008 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7009 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7010 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7011 } 7012 } else { 7013 if (DEBUG_PACKAGE_SCANNING) { 7014 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7015 Log.v(TAG, "Want this data dir: " + dataPath); 7016 } 7017 //invoke installer to do the actual installation 7018 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7019 pkg.applicationInfo.seinfo); 7020 if (ret < 0) { 7021 // Error from installer 7022 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7023 "Unable to create data dirs [errorCode=" + ret + "]"); 7024 } 7025 7026 if (dataPath.exists()) { 7027 pkg.applicationInfo.dataDir = dataPath.getPath(); 7028 } else { 7029 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7030 pkg.applicationInfo.dataDir = null; 7031 } 7032 } 7033 7034 pkgSetting.uidError = uidError; 7035 } 7036 7037 final String path = scanFile.getPath(); 7038 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7039 7040 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7041 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7042 7043 // Some system apps still use directory structure for native libraries 7044 // in which case we might end up not detecting abi solely based on apk 7045 // structure. Try to detect abi based on directory structure. 7046 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7047 pkg.applicationInfo.primaryCpuAbi == null) { 7048 setBundledAppAbisAndRoots(pkg, pkgSetting); 7049 setNativeLibraryPaths(pkg); 7050 } 7051 7052 } else { 7053 if ((scanFlags & SCAN_MOVE) != 0) { 7054 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7055 // but we already have this packages package info in the PackageSetting. We just 7056 // use that and derive the native library path based on the new codepath. 7057 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7058 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7059 } 7060 7061 // Set native library paths again. For moves, the path will be updated based on the 7062 // ABIs we've determined above. For non-moves, the path will be updated based on the 7063 // ABIs we determined during compilation, but the path will depend on the final 7064 // package path (after the rename away from the stage path). 7065 setNativeLibraryPaths(pkg); 7066 } 7067 7068 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7069 final int[] userIds = sUserManager.getUserIds(); 7070 synchronized (mInstallLock) { 7071 // Make sure all user data directories are ready to roll; we're okay 7072 // if they already exist 7073 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7074 for (int userId : userIds) { 7075 if (userId != 0) { 7076 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7077 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7078 pkg.applicationInfo.seinfo); 7079 } 7080 } 7081 } 7082 7083 // Create a native library symlink only if we have native libraries 7084 // and if the native libraries are 32 bit libraries. We do not provide 7085 // this symlink for 64 bit libraries. 7086 if (pkg.applicationInfo.primaryCpuAbi != null && 7087 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7088 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7089 try { 7090 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7091 for (int userId : userIds) { 7092 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7093 nativeLibPath, userId) < 0) { 7094 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7095 "Failed linking native library dir (user=" + userId + ")"); 7096 } 7097 } 7098 } finally { 7099 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7100 } 7101 } 7102 } 7103 7104 // This is a special case for the "system" package, where the ABI is 7105 // dictated by the zygote configuration (and init.rc). We should keep track 7106 // of this ABI so that we can deal with "normal" applications that run under 7107 // the same UID correctly. 7108 if (mPlatformPackage == pkg) { 7109 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7110 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7111 } 7112 7113 // If there's a mismatch between the abi-override in the package setting 7114 // and the abiOverride specified for the install. Warn about this because we 7115 // would've already compiled the app without taking the package setting into 7116 // account. 7117 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7118 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7119 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7120 " for package: " + pkg.packageName); 7121 } 7122 } 7123 7124 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7125 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7126 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7127 7128 // Copy the derived override back to the parsed package, so that we can 7129 // update the package settings accordingly. 7130 pkg.cpuAbiOverride = cpuAbiOverride; 7131 7132 if (DEBUG_ABI_SELECTION) { 7133 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7134 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7135 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7136 } 7137 7138 // Push the derived path down into PackageSettings so we know what to 7139 // clean up at uninstall time. 7140 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7141 7142 if (DEBUG_ABI_SELECTION) { 7143 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7144 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7145 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7146 } 7147 7148 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7149 // We don't do this here during boot because we can do it all 7150 // at once after scanning all existing packages. 7151 // 7152 // We also do this *before* we perform dexopt on this package, so that 7153 // we can avoid redundant dexopts, and also to make sure we've got the 7154 // code and package path correct. 7155 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7156 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7157 } 7158 7159 if ((scanFlags & SCAN_NO_DEX) == 0) { 7160 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7161 7162 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7163 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7164 7165 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7166 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7167 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7168 } 7169 } 7170 if (mFactoryTest && pkg.requestedPermissions.contains( 7171 android.Manifest.permission.FACTORY_TEST)) { 7172 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7173 } 7174 7175 ArrayList<PackageParser.Package> clientLibPkgs = null; 7176 7177 // writer 7178 synchronized (mPackages) { 7179 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7180 // Only system apps can add new shared libraries. 7181 if (pkg.libraryNames != null) { 7182 for (int i=0; i<pkg.libraryNames.size(); i++) { 7183 String name = pkg.libraryNames.get(i); 7184 boolean allowed = false; 7185 if (pkg.isUpdatedSystemApp()) { 7186 // New library entries can only be added through the 7187 // system image. This is important to get rid of a lot 7188 // of nasty edge cases: for example if we allowed a non- 7189 // system update of the app to add a library, then uninstalling 7190 // the update would make the library go away, and assumptions 7191 // we made such as through app install filtering would now 7192 // have allowed apps on the device which aren't compatible 7193 // with it. Better to just have the restriction here, be 7194 // conservative, and create many fewer cases that can negatively 7195 // impact the user experience. 7196 final PackageSetting sysPs = mSettings 7197 .getDisabledSystemPkgLPr(pkg.packageName); 7198 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7199 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7200 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7201 allowed = true; 7202 allowed = true; 7203 break; 7204 } 7205 } 7206 } 7207 } else { 7208 allowed = true; 7209 } 7210 if (allowed) { 7211 if (!mSharedLibraries.containsKey(name)) { 7212 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7213 } else if (!name.equals(pkg.packageName)) { 7214 Slog.w(TAG, "Package " + pkg.packageName + " library " 7215 + name + " already exists; skipping"); 7216 } 7217 } else { 7218 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7219 + name + " that is not declared on system image; skipping"); 7220 } 7221 } 7222 if ((scanFlags&SCAN_BOOTING) == 0) { 7223 // If we are not booting, we need to update any applications 7224 // that are clients of our shared library. If we are booting, 7225 // this will all be done once the scan is complete. 7226 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7227 } 7228 } 7229 } 7230 } 7231 7232 // We also need to dexopt any apps that are dependent on this library. Note that 7233 // if these fail, we should abort the install since installing the library will 7234 // result in some apps being broken. 7235 if (clientLibPkgs != null) { 7236 if ((scanFlags & SCAN_NO_DEX) == 0) { 7237 for (int i = 0; i < clientLibPkgs.size(); i++) { 7238 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7239 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7240 null /* instruction sets */, forceDex, 7241 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7242 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7243 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7244 "scanPackageLI failed to dexopt clientLibPkgs"); 7245 } 7246 } 7247 } 7248 } 7249 7250 // Request the ActivityManager to kill the process(only for existing packages) 7251 // so that we do not end up in a confused state while the user is still using the older 7252 // version of the application while the new one gets installed. 7253 if ((scanFlags & SCAN_REPLACING) != 0) { 7254 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7255 7256 killApplication(pkg.applicationInfo.packageName, 7257 pkg.applicationInfo.uid, "replace pkg"); 7258 7259 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7260 } 7261 7262 // Also need to kill any apps that are dependent on the library. 7263 if (clientLibPkgs != null) { 7264 for (int i=0; i<clientLibPkgs.size(); i++) { 7265 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7266 killApplication(clientPkg.applicationInfo.packageName, 7267 clientPkg.applicationInfo.uid, "update lib"); 7268 } 7269 } 7270 7271 // Make sure we're not adding any bogus keyset info 7272 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7273 ksms.assertScannedPackageValid(pkg); 7274 7275 // writer 7276 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7277 7278 boolean createIdmapFailed = false; 7279 synchronized (mPackages) { 7280 // We don't expect installation to fail beyond this point 7281 7282 // Add the new setting to mSettings 7283 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7284 // Add the new setting to mPackages 7285 mPackages.put(pkg.applicationInfo.packageName, pkg); 7286 // Make sure we don't accidentally delete its data. 7287 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7288 while (iter.hasNext()) { 7289 PackageCleanItem item = iter.next(); 7290 if (pkgName.equals(item.packageName)) { 7291 iter.remove(); 7292 } 7293 } 7294 7295 // Take care of first install / last update times. 7296 if (currentTime != 0) { 7297 if (pkgSetting.firstInstallTime == 0) { 7298 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7299 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7300 pkgSetting.lastUpdateTime = currentTime; 7301 } 7302 } else if (pkgSetting.firstInstallTime == 0) { 7303 // We need *something*. Take time time stamp of the file. 7304 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7305 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7306 if (scanFileTime != pkgSetting.timeStamp) { 7307 // A package on the system image has changed; consider this 7308 // to be an update. 7309 pkgSetting.lastUpdateTime = scanFileTime; 7310 } 7311 } 7312 7313 // Add the package's KeySets to the global KeySetManagerService 7314 ksms.addScannedPackageLPw(pkg); 7315 7316 int N = pkg.providers.size(); 7317 StringBuilder r = null; 7318 int i; 7319 for (i=0; i<N; i++) { 7320 PackageParser.Provider p = pkg.providers.get(i); 7321 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7322 p.info.processName, pkg.applicationInfo.uid); 7323 mProviders.addProvider(p); 7324 p.syncable = p.info.isSyncable; 7325 if (p.info.authority != null) { 7326 String names[] = p.info.authority.split(";"); 7327 p.info.authority = null; 7328 for (int j = 0; j < names.length; j++) { 7329 if (j == 1 && p.syncable) { 7330 // We only want the first authority for a provider to possibly be 7331 // syncable, so if we already added this provider using a different 7332 // authority clear the syncable flag. We copy the provider before 7333 // changing it because the mProviders object contains a reference 7334 // to a provider that we don't want to change. 7335 // Only do this for the second authority since the resulting provider 7336 // object can be the same for all future authorities for this provider. 7337 p = new PackageParser.Provider(p); 7338 p.syncable = false; 7339 } 7340 if (!mProvidersByAuthority.containsKey(names[j])) { 7341 mProvidersByAuthority.put(names[j], p); 7342 if (p.info.authority == null) { 7343 p.info.authority = names[j]; 7344 } else { 7345 p.info.authority = p.info.authority + ";" + names[j]; 7346 } 7347 if (DEBUG_PACKAGE_SCANNING) { 7348 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7349 Log.d(TAG, "Registered content provider: " + names[j] 7350 + ", className = " + p.info.name + ", isSyncable = " 7351 + p.info.isSyncable); 7352 } 7353 } else { 7354 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7355 Slog.w(TAG, "Skipping provider name " + names[j] + 7356 " (in package " + pkg.applicationInfo.packageName + 7357 "): name already used by " 7358 + ((other != null && other.getComponentName() != null) 7359 ? other.getComponentName().getPackageName() : "?")); 7360 } 7361 } 7362 } 7363 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7364 if (r == null) { 7365 r = new StringBuilder(256); 7366 } else { 7367 r.append(' '); 7368 } 7369 r.append(p.info.name); 7370 } 7371 } 7372 if (r != null) { 7373 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7374 } 7375 7376 N = pkg.services.size(); 7377 r = null; 7378 for (i=0; i<N; i++) { 7379 PackageParser.Service s = pkg.services.get(i); 7380 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7381 s.info.processName, pkg.applicationInfo.uid); 7382 mServices.addService(s); 7383 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7384 if (r == null) { 7385 r = new StringBuilder(256); 7386 } else { 7387 r.append(' '); 7388 } 7389 r.append(s.info.name); 7390 } 7391 } 7392 if (r != null) { 7393 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7394 } 7395 7396 N = pkg.receivers.size(); 7397 r = null; 7398 for (i=0; i<N; i++) { 7399 PackageParser.Activity a = pkg.receivers.get(i); 7400 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7401 a.info.processName, pkg.applicationInfo.uid); 7402 mReceivers.addActivity(a, "receiver"); 7403 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7404 if (r == null) { 7405 r = new StringBuilder(256); 7406 } else { 7407 r.append(' '); 7408 } 7409 r.append(a.info.name); 7410 } 7411 } 7412 if (r != null) { 7413 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7414 } 7415 7416 N = pkg.activities.size(); 7417 r = null; 7418 for (i=0; i<N; i++) { 7419 PackageParser.Activity a = pkg.activities.get(i); 7420 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7421 a.info.processName, pkg.applicationInfo.uid); 7422 mActivities.addActivity(a, "activity"); 7423 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7424 if (r == null) { 7425 r = new StringBuilder(256); 7426 } else { 7427 r.append(' '); 7428 } 7429 r.append(a.info.name); 7430 } 7431 } 7432 if (r != null) { 7433 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7434 } 7435 7436 N = pkg.permissionGroups.size(); 7437 r = null; 7438 for (i=0; i<N; i++) { 7439 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7440 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7441 if (cur == null) { 7442 mPermissionGroups.put(pg.info.name, pg); 7443 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7444 if (r == null) { 7445 r = new StringBuilder(256); 7446 } else { 7447 r.append(' '); 7448 } 7449 r.append(pg.info.name); 7450 } 7451 } else { 7452 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7453 + pg.info.packageName + " ignored: original from " 7454 + cur.info.packageName); 7455 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7456 if (r == null) { 7457 r = new StringBuilder(256); 7458 } else { 7459 r.append(' '); 7460 } 7461 r.append("DUP:"); 7462 r.append(pg.info.name); 7463 } 7464 } 7465 } 7466 if (r != null) { 7467 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7468 } 7469 7470 N = pkg.permissions.size(); 7471 r = null; 7472 for (i=0; i<N; i++) { 7473 PackageParser.Permission p = pkg.permissions.get(i); 7474 7475 // Assume by default that we did not install this permission into the system. 7476 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7477 7478 // Now that permission groups have a special meaning, we ignore permission 7479 // groups for legacy apps to prevent unexpected behavior. In particular, 7480 // permissions for one app being granted to someone just becuase they happen 7481 // to be in a group defined by another app (before this had no implications). 7482 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7483 p.group = mPermissionGroups.get(p.info.group); 7484 // Warn for a permission in an unknown group. 7485 if (p.info.group != null && p.group == null) { 7486 Slog.w(TAG, "Permission " + p.info.name + " from package " 7487 + p.info.packageName + " in an unknown group " + p.info.group); 7488 } 7489 } 7490 7491 ArrayMap<String, BasePermission> permissionMap = 7492 p.tree ? mSettings.mPermissionTrees 7493 : mSettings.mPermissions; 7494 BasePermission bp = permissionMap.get(p.info.name); 7495 7496 // Allow system apps to redefine non-system permissions 7497 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7498 final boolean currentOwnerIsSystem = (bp.perm != null 7499 && isSystemApp(bp.perm.owner)); 7500 if (isSystemApp(p.owner)) { 7501 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7502 // It's a built-in permission and no owner, take ownership now 7503 bp.packageSetting = pkgSetting; 7504 bp.perm = p; 7505 bp.uid = pkg.applicationInfo.uid; 7506 bp.sourcePackage = p.info.packageName; 7507 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7508 } else if (!currentOwnerIsSystem) { 7509 String msg = "New decl " + p.owner + " of permission " 7510 + p.info.name + " is system; overriding " + bp.sourcePackage; 7511 reportSettingsProblem(Log.WARN, msg); 7512 bp = null; 7513 } 7514 } 7515 } 7516 7517 if (bp == null) { 7518 bp = new BasePermission(p.info.name, p.info.packageName, 7519 BasePermission.TYPE_NORMAL); 7520 permissionMap.put(p.info.name, bp); 7521 } 7522 7523 if (bp.perm == null) { 7524 if (bp.sourcePackage == null 7525 || bp.sourcePackage.equals(p.info.packageName)) { 7526 BasePermission tree = findPermissionTreeLP(p.info.name); 7527 if (tree == null 7528 || tree.sourcePackage.equals(p.info.packageName)) { 7529 bp.packageSetting = pkgSetting; 7530 bp.perm = p; 7531 bp.uid = pkg.applicationInfo.uid; 7532 bp.sourcePackage = p.info.packageName; 7533 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7534 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7535 if (r == null) { 7536 r = new StringBuilder(256); 7537 } else { 7538 r.append(' '); 7539 } 7540 r.append(p.info.name); 7541 } 7542 } else { 7543 Slog.w(TAG, "Permission " + p.info.name + " from package " 7544 + p.info.packageName + " ignored: base tree " 7545 + tree.name + " is from package " 7546 + tree.sourcePackage); 7547 } 7548 } else { 7549 Slog.w(TAG, "Permission " + p.info.name + " from package " 7550 + p.info.packageName + " ignored: original from " 7551 + bp.sourcePackage); 7552 } 7553 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7554 if (r == null) { 7555 r = new StringBuilder(256); 7556 } else { 7557 r.append(' '); 7558 } 7559 r.append("DUP:"); 7560 r.append(p.info.name); 7561 } 7562 if (bp.perm == p) { 7563 bp.protectionLevel = p.info.protectionLevel; 7564 } 7565 } 7566 7567 if (r != null) { 7568 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7569 } 7570 7571 N = pkg.instrumentation.size(); 7572 r = null; 7573 for (i=0; i<N; i++) { 7574 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7575 a.info.packageName = pkg.applicationInfo.packageName; 7576 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7577 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7578 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7579 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7580 a.info.dataDir = pkg.applicationInfo.dataDir; 7581 7582 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7583 // need other information about the application, like the ABI and what not ? 7584 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7585 mInstrumentation.put(a.getComponentName(), a); 7586 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7587 if (r == null) { 7588 r = new StringBuilder(256); 7589 } else { 7590 r.append(' '); 7591 } 7592 r.append(a.info.name); 7593 } 7594 } 7595 if (r != null) { 7596 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7597 } 7598 7599 if (pkg.protectedBroadcasts != null) { 7600 N = pkg.protectedBroadcasts.size(); 7601 for (i=0; i<N; i++) { 7602 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7603 } 7604 } 7605 7606 pkgSetting.setTimeStamp(scanFileTime); 7607 7608 // Create idmap files for pairs of (packages, overlay packages). 7609 // Note: "android", ie framework-res.apk, is handled by native layers. 7610 if (pkg.mOverlayTarget != null) { 7611 // This is an overlay package. 7612 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7613 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7614 mOverlays.put(pkg.mOverlayTarget, 7615 new ArrayMap<String, PackageParser.Package>()); 7616 } 7617 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7618 map.put(pkg.packageName, pkg); 7619 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7620 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7621 createIdmapFailed = true; 7622 } 7623 } 7624 } else if (mOverlays.containsKey(pkg.packageName) && 7625 !pkg.packageName.equals("android")) { 7626 // This is a regular package, with one or more known overlay packages. 7627 createIdmapsForPackageLI(pkg); 7628 } 7629 } 7630 7631 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7632 7633 if (createIdmapFailed) { 7634 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7635 "scanPackageLI failed to createIdmap"); 7636 } 7637 return pkg; 7638 } 7639 7640 /** 7641 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7642 * is derived purely on the basis of the contents of {@code scanFile} and 7643 * {@code cpuAbiOverride}. 7644 * 7645 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7646 */ 7647 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7648 String cpuAbiOverride, boolean extractLibs) 7649 throws PackageManagerException { 7650 // TODO: We can probably be smarter about this stuff. For installed apps, 7651 // we can calculate this information at install time once and for all. For 7652 // system apps, we can probably assume that this information doesn't change 7653 // after the first boot scan. As things stand, we do lots of unnecessary work. 7654 7655 // Give ourselves some initial paths; we'll come back for another 7656 // pass once we've determined ABI below. 7657 setNativeLibraryPaths(pkg); 7658 7659 // We would never need to extract libs for forward-locked and external packages, 7660 // since the container service will do it for us. We shouldn't attempt to 7661 // extract libs from system app when it was not updated. 7662 if (pkg.isForwardLocked() || isExternal(pkg) || 7663 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7664 extractLibs = false; 7665 } 7666 7667 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7668 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7669 7670 NativeLibraryHelper.Handle handle = null; 7671 try { 7672 handle = NativeLibraryHelper.Handle.create(pkg); 7673 // TODO(multiArch): This can be null for apps that didn't go through the 7674 // usual installation process. We can calculate it again, like we 7675 // do during install time. 7676 // 7677 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7678 // unnecessary. 7679 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7680 7681 // Null out the abis so that they can be recalculated. 7682 pkg.applicationInfo.primaryCpuAbi = null; 7683 pkg.applicationInfo.secondaryCpuAbi = null; 7684 if (isMultiArch(pkg.applicationInfo)) { 7685 // Warn if we've set an abiOverride for multi-lib packages.. 7686 // By definition, we need to copy both 32 and 64 bit libraries for 7687 // such packages. 7688 if (pkg.cpuAbiOverride != null 7689 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7690 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7691 } 7692 7693 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7694 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7695 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7696 if (extractLibs) { 7697 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7698 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7699 useIsaSpecificSubdirs); 7700 } else { 7701 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7702 } 7703 } 7704 7705 maybeThrowExceptionForMultiArchCopy( 7706 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7707 7708 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7709 if (extractLibs) { 7710 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7711 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7712 useIsaSpecificSubdirs); 7713 } else { 7714 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7715 } 7716 } 7717 7718 maybeThrowExceptionForMultiArchCopy( 7719 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7720 7721 if (abi64 >= 0) { 7722 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7723 } 7724 7725 if (abi32 >= 0) { 7726 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7727 if (abi64 >= 0) { 7728 pkg.applicationInfo.secondaryCpuAbi = abi; 7729 } else { 7730 pkg.applicationInfo.primaryCpuAbi = abi; 7731 } 7732 } 7733 } else { 7734 String[] abiList = (cpuAbiOverride != null) ? 7735 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7736 7737 // Enable gross and lame hacks for apps that are built with old 7738 // SDK tools. We must scan their APKs for renderscript bitcode and 7739 // not launch them if it's present. Don't bother checking on devices 7740 // that don't have 64 bit support. 7741 boolean needsRenderScriptOverride = false; 7742 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7743 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7744 abiList = Build.SUPPORTED_32_BIT_ABIS; 7745 needsRenderScriptOverride = true; 7746 } 7747 7748 final int copyRet; 7749 if (extractLibs) { 7750 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7751 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7752 } else { 7753 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7754 } 7755 7756 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7757 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7758 "Error unpackaging native libs for app, errorCode=" + copyRet); 7759 } 7760 7761 if (copyRet >= 0) { 7762 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7763 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7764 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7765 } else if (needsRenderScriptOverride) { 7766 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7767 } 7768 } 7769 } catch (IOException ioe) { 7770 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7771 } finally { 7772 IoUtils.closeQuietly(handle); 7773 } 7774 7775 // Now that we've calculated the ABIs and determined if it's an internal app, 7776 // we will go ahead and populate the nativeLibraryPath. 7777 setNativeLibraryPaths(pkg); 7778 } 7779 7780 /** 7781 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7782 * i.e, so that all packages can be run inside a single process if required. 7783 * 7784 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7785 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7786 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7787 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7788 * updating a package that belongs to a shared user. 7789 * 7790 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7791 * adds unnecessary complexity. 7792 */ 7793 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7794 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7795 String requiredInstructionSet = null; 7796 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7797 requiredInstructionSet = VMRuntime.getInstructionSet( 7798 scannedPackage.applicationInfo.primaryCpuAbi); 7799 } 7800 7801 PackageSetting requirer = null; 7802 for (PackageSetting ps : packagesForUser) { 7803 // If packagesForUser contains scannedPackage, we skip it. This will happen 7804 // when scannedPackage is an update of an existing package. Without this check, 7805 // we will never be able to change the ABI of any package belonging to a shared 7806 // user, even if it's compatible with other packages. 7807 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7808 if (ps.primaryCpuAbiString == null) { 7809 continue; 7810 } 7811 7812 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7813 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7814 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7815 // this but there's not much we can do. 7816 String errorMessage = "Instruction set mismatch, " 7817 + ((requirer == null) ? "[caller]" : requirer) 7818 + " requires " + requiredInstructionSet + " whereas " + ps 7819 + " requires " + instructionSet; 7820 Slog.w(TAG, errorMessage); 7821 } 7822 7823 if (requiredInstructionSet == null) { 7824 requiredInstructionSet = instructionSet; 7825 requirer = ps; 7826 } 7827 } 7828 } 7829 7830 if (requiredInstructionSet != null) { 7831 String adjustedAbi; 7832 if (requirer != null) { 7833 // requirer != null implies that either scannedPackage was null or that scannedPackage 7834 // did not require an ABI, in which case we have to adjust scannedPackage to match 7835 // the ABI of the set (which is the same as requirer's ABI) 7836 adjustedAbi = requirer.primaryCpuAbiString; 7837 if (scannedPackage != null) { 7838 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7839 } 7840 } else { 7841 // requirer == null implies that we're updating all ABIs in the set to 7842 // match scannedPackage. 7843 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7844 } 7845 7846 for (PackageSetting ps : packagesForUser) { 7847 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7848 if (ps.primaryCpuAbiString != null) { 7849 continue; 7850 } 7851 7852 ps.primaryCpuAbiString = adjustedAbi; 7853 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7854 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7855 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7856 7857 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7858 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7859 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7860 ps.primaryCpuAbiString = null; 7861 ps.pkg.applicationInfo.primaryCpuAbi = null; 7862 return; 7863 } else { 7864 mInstaller.rmdex(ps.codePathString, 7865 getDexCodeInstructionSet(getPreferredInstructionSet())); 7866 } 7867 } 7868 } 7869 } 7870 } 7871 } 7872 7873 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7874 synchronized (mPackages) { 7875 mResolverReplaced = true; 7876 // Set up information for custom user intent resolution activity. 7877 mResolveActivity.applicationInfo = pkg.applicationInfo; 7878 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7879 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7880 mResolveActivity.processName = pkg.applicationInfo.packageName; 7881 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7882 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7883 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7884 mResolveActivity.theme = 0; 7885 mResolveActivity.exported = true; 7886 mResolveActivity.enabled = true; 7887 mResolveInfo.activityInfo = mResolveActivity; 7888 mResolveInfo.priority = 0; 7889 mResolveInfo.preferredOrder = 0; 7890 mResolveInfo.match = 0; 7891 mResolveComponentName = mCustomResolverComponentName; 7892 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7893 mResolveComponentName); 7894 } 7895 } 7896 7897 private static String calculateBundledApkRoot(final String codePathString) { 7898 final File codePath = new File(codePathString); 7899 final File codeRoot; 7900 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7901 codeRoot = Environment.getRootDirectory(); 7902 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7903 codeRoot = Environment.getOemDirectory(); 7904 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7905 codeRoot = Environment.getVendorDirectory(); 7906 } else { 7907 // Unrecognized code path; take its top real segment as the apk root: 7908 // e.g. /something/app/blah.apk => /something 7909 try { 7910 File f = codePath.getCanonicalFile(); 7911 File parent = f.getParentFile(); // non-null because codePath is a file 7912 File tmp; 7913 while ((tmp = parent.getParentFile()) != null) { 7914 f = parent; 7915 parent = tmp; 7916 } 7917 codeRoot = f; 7918 Slog.w(TAG, "Unrecognized code path " 7919 + codePath + " - using " + codeRoot); 7920 } catch (IOException e) { 7921 // Can't canonicalize the code path -- shenanigans? 7922 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7923 return Environment.getRootDirectory().getPath(); 7924 } 7925 } 7926 return codeRoot.getPath(); 7927 } 7928 7929 /** 7930 * Derive and set the location of native libraries for the given package, 7931 * which varies depending on where and how the package was installed. 7932 */ 7933 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7934 final ApplicationInfo info = pkg.applicationInfo; 7935 final String codePath = pkg.codePath; 7936 final File codeFile = new File(codePath); 7937 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7938 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7939 7940 info.nativeLibraryRootDir = null; 7941 info.nativeLibraryRootRequiresIsa = false; 7942 info.nativeLibraryDir = null; 7943 info.secondaryNativeLibraryDir = null; 7944 7945 if (isApkFile(codeFile)) { 7946 // Monolithic install 7947 if (bundledApp) { 7948 // If "/system/lib64/apkname" exists, assume that is the per-package 7949 // native library directory to use; otherwise use "/system/lib/apkname". 7950 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7951 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7952 getPrimaryInstructionSet(info)); 7953 7954 // This is a bundled system app so choose the path based on the ABI. 7955 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7956 // is just the default path. 7957 final String apkName = deriveCodePathName(codePath); 7958 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7959 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7960 apkName).getAbsolutePath(); 7961 7962 if (info.secondaryCpuAbi != null) { 7963 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7964 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7965 secondaryLibDir, apkName).getAbsolutePath(); 7966 } 7967 } else if (asecApp) { 7968 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7969 .getAbsolutePath(); 7970 } else { 7971 final String apkName = deriveCodePathName(codePath); 7972 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7973 .getAbsolutePath(); 7974 } 7975 7976 info.nativeLibraryRootRequiresIsa = false; 7977 info.nativeLibraryDir = info.nativeLibraryRootDir; 7978 } else { 7979 // Cluster install 7980 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7981 info.nativeLibraryRootRequiresIsa = true; 7982 7983 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7984 getPrimaryInstructionSet(info)).getAbsolutePath(); 7985 7986 if (info.secondaryCpuAbi != null) { 7987 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7988 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7989 } 7990 } 7991 } 7992 7993 /** 7994 * Calculate the abis and roots for a bundled app. These can uniquely 7995 * be determined from the contents of the system partition, i.e whether 7996 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7997 * of this information, and instead assume that the system was built 7998 * sensibly. 7999 */ 8000 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8001 PackageSetting pkgSetting) { 8002 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8003 8004 // If "/system/lib64/apkname" exists, assume that is the per-package 8005 // native library directory to use; otherwise use "/system/lib/apkname". 8006 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8007 setBundledAppAbi(pkg, apkRoot, apkName); 8008 // pkgSetting might be null during rescan following uninstall of updates 8009 // to a bundled app, so accommodate that possibility. The settings in 8010 // that case will be established later from the parsed package. 8011 // 8012 // If the settings aren't null, sync them up with what we've just derived. 8013 // note that apkRoot isn't stored in the package settings. 8014 if (pkgSetting != null) { 8015 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8016 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8017 } 8018 } 8019 8020 /** 8021 * Deduces the ABI of a bundled app and sets the relevant fields on the 8022 * parsed pkg object. 8023 * 8024 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8025 * under which system libraries are installed. 8026 * @param apkName the name of the installed package. 8027 */ 8028 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8029 final File codeFile = new File(pkg.codePath); 8030 8031 final boolean has64BitLibs; 8032 final boolean has32BitLibs; 8033 if (isApkFile(codeFile)) { 8034 // Monolithic install 8035 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8036 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8037 } else { 8038 // Cluster install 8039 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8040 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8041 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8042 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8043 has64BitLibs = (new File(rootDir, isa)).exists(); 8044 } else { 8045 has64BitLibs = false; 8046 } 8047 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8048 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8049 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8050 has32BitLibs = (new File(rootDir, isa)).exists(); 8051 } else { 8052 has32BitLibs = false; 8053 } 8054 } 8055 8056 if (has64BitLibs && !has32BitLibs) { 8057 // The package has 64 bit libs, but not 32 bit libs. Its primary 8058 // ABI should be 64 bit. We can safely assume here that the bundled 8059 // native libraries correspond to the most preferred ABI in the list. 8060 8061 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8062 pkg.applicationInfo.secondaryCpuAbi = null; 8063 } else if (has32BitLibs && !has64BitLibs) { 8064 // The package has 32 bit libs but not 64 bit libs. Its primary 8065 // ABI should be 32 bit. 8066 8067 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8068 pkg.applicationInfo.secondaryCpuAbi = null; 8069 } else if (has32BitLibs && has64BitLibs) { 8070 // The application has both 64 and 32 bit bundled libraries. We check 8071 // here that the app declares multiArch support, and warn if it doesn't. 8072 // 8073 // We will be lenient here and record both ABIs. The primary will be the 8074 // ABI that's higher on the list, i.e, a device that's configured to prefer 8075 // 64 bit apps will see a 64 bit primary ABI, 8076 8077 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8078 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8079 } 8080 8081 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8082 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8083 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8084 } else { 8085 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8086 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8087 } 8088 } else { 8089 pkg.applicationInfo.primaryCpuAbi = null; 8090 pkg.applicationInfo.secondaryCpuAbi = null; 8091 } 8092 } 8093 8094 private void killApplication(String pkgName, int appId, String reason) { 8095 // Request the ActivityManager to kill the process(only for existing packages) 8096 // so that we do not end up in a confused state while the user is still using the older 8097 // version of the application while the new one gets installed. 8098 IActivityManager am = ActivityManagerNative.getDefault(); 8099 if (am != null) { 8100 try { 8101 am.killApplicationWithAppId(pkgName, appId, reason); 8102 } catch (RemoteException e) { 8103 } 8104 } 8105 } 8106 8107 void removePackageLI(PackageSetting ps, boolean chatty) { 8108 if (DEBUG_INSTALL) { 8109 if (chatty) 8110 Log.d(TAG, "Removing package " + ps.name); 8111 } 8112 8113 // writer 8114 synchronized (mPackages) { 8115 mPackages.remove(ps.name); 8116 final PackageParser.Package pkg = ps.pkg; 8117 if (pkg != null) { 8118 cleanPackageDataStructuresLILPw(pkg, chatty); 8119 } 8120 } 8121 } 8122 8123 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8124 if (DEBUG_INSTALL) { 8125 if (chatty) 8126 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8127 } 8128 8129 // writer 8130 synchronized (mPackages) { 8131 mPackages.remove(pkg.applicationInfo.packageName); 8132 cleanPackageDataStructuresLILPw(pkg, chatty); 8133 } 8134 } 8135 8136 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8137 int N = pkg.providers.size(); 8138 StringBuilder r = null; 8139 int i; 8140 for (i=0; i<N; i++) { 8141 PackageParser.Provider p = pkg.providers.get(i); 8142 mProviders.removeProvider(p); 8143 if (p.info.authority == null) { 8144 8145 /* There was another ContentProvider with this authority when 8146 * this app was installed so this authority is null, 8147 * Ignore it as we don't have to unregister the provider. 8148 */ 8149 continue; 8150 } 8151 String names[] = p.info.authority.split(";"); 8152 for (int j = 0; j < names.length; j++) { 8153 if (mProvidersByAuthority.get(names[j]) == p) { 8154 mProvidersByAuthority.remove(names[j]); 8155 if (DEBUG_REMOVE) { 8156 if (chatty) 8157 Log.d(TAG, "Unregistered content provider: " + names[j] 8158 + ", className = " + p.info.name + ", isSyncable = " 8159 + p.info.isSyncable); 8160 } 8161 } 8162 } 8163 if (DEBUG_REMOVE && chatty) { 8164 if (r == null) { 8165 r = new StringBuilder(256); 8166 } else { 8167 r.append(' '); 8168 } 8169 r.append(p.info.name); 8170 } 8171 } 8172 if (r != null) { 8173 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8174 } 8175 8176 N = pkg.services.size(); 8177 r = null; 8178 for (i=0; i<N; i++) { 8179 PackageParser.Service s = pkg.services.get(i); 8180 mServices.removeService(s); 8181 if (chatty) { 8182 if (r == null) { 8183 r = new StringBuilder(256); 8184 } else { 8185 r.append(' '); 8186 } 8187 r.append(s.info.name); 8188 } 8189 } 8190 if (r != null) { 8191 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8192 } 8193 8194 N = pkg.receivers.size(); 8195 r = null; 8196 for (i=0; i<N; i++) { 8197 PackageParser.Activity a = pkg.receivers.get(i); 8198 mReceivers.removeActivity(a, "receiver"); 8199 if (DEBUG_REMOVE && chatty) { 8200 if (r == null) { 8201 r = new StringBuilder(256); 8202 } else { 8203 r.append(' '); 8204 } 8205 r.append(a.info.name); 8206 } 8207 } 8208 if (r != null) { 8209 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8210 } 8211 8212 N = pkg.activities.size(); 8213 r = null; 8214 for (i=0; i<N; i++) { 8215 PackageParser.Activity a = pkg.activities.get(i); 8216 mActivities.removeActivity(a, "activity"); 8217 if (DEBUG_REMOVE && chatty) { 8218 if (r == null) { 8219 r = new StringBuilder(256); 8220 } else { 8221 r.append(' '); 8222 } 8223 r.append(a.info.name); 8224 } 8225 } 8226 if (r != null) { 8227 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8228 } 8229 8230 N = pkg.permissions.size(); 8231 r = null; 8232 for (i=0; i<N; i++) { 8233 PackageParser.Permission p = pkg.permissions.get(i); 8234 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8235 if (bp == null) { 8236 bp = mSettings.mPermissionTrees.get(p.info.name); 8237 } 8238 if (bp != null && bp.perm == p) { 8239 bp.perm = null; 8240 if (DEBUG_REMOVE && chatty) { 8241 if (r == null) { 8242 r = new StringBuilder(256); 8243 } else { 8244 r.append(' '); 8245 } 8246 r.append(p.info.name); 8247 } 8248 } 8249 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8250 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8251 if (appOpPerms != null) { 8252 appOpPerms.remove(pkg.packageName); 8253 } 8254 } 8255 } 8256 if (r != null) { 8257 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8258 } 8259 8260 N = pkg.requestedPermissions.size(); 8261 r = null; 8262 for (i=0; i<N; i++) { 8263 String perm = pkg.requestedPermissions.get(i); 8264 BasePermission bp = mSettings.mPermissions.get(perm); 8265 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8266 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8267 if (appOpPerms != null) { 8268 appOpPerms.remove(pkg.packageName); 8269 if (appOpPerms.isEmpty()) { 8270 mAppOpPermissionPackages.remove(perm); 8271 } 8272 } 8273 } 8274 } 8275 if (r != null) { 8276 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8277 } 8278 8279 N = pkg.instrumentation.size(); 8280 r = null; 8281 for (i=0; i<N; i++) { 8282 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8283 mInstrumentation.remove(a.getComponentName()); 8284 if (DEBUG_REMOVE && chatty) { 8285 if (r == null) { 8286 r = new StringBuilder(256); 8287 } else { 8288 r.append(' '); 8289 } 8290 r.append(a.info.name); 8291 } 8292 } 8293 if (r != null) { 8294 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8295 } 8296 8297 r = null; 8298 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8299 // Only system apps can hold shared libraries. 8300 if (pkg.libraryNames != null) { 8301 for (i=0; i<pkg.libraryNames.size(); i++) { 8302 String name = pkg.libraryNames.get(i); 8303 SharedLibraryEntry cur = mSharedLibraries.get(name); 8304 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8305 mSharedLibraries.remove(name); 8306 if (DEBUG_REMOVE && chatty) { 8307 if (r == null) { 8308 r = new StringBuilder(256); 8309 } else { 8310 r.append(' '); 8311 } 8312 r.append(name); 8313 } 8314 } 8315 } 8316 } 8317 } 8318 if (r != null) { 8319 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8320 } 8321 } 8322 8323 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8324 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8325 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8326 return true; 8327 } 8328 } 8329 return false; 8330 } 8331 8332 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8333 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8334 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8335 8336 private void updatePermissionsLPw(String changingPkg, 8337 PackageParser.Package pkgInfo, int flags) { 8338 // Make sure there are no dangling permission trees. 8339 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8340 while (it.hasNext()) { 8341 final BasePermission bp = it.next(); 8342 if (bp.packageSetting == null) { 8343 // We may not yet have parsed the package, so just see if 8344 // we still know about its settings. 8345 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8346 } 8347 if (bp.packageSetting == null) { 8348 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8349 + " from package " + bp.sourcePackage); 8350 it.remove(); 8351 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8352 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8353 Slog.i(TAG, "Removing old permission tree: " + bp.name 8354 + " from package " + bp.sourcePackage); 8355 flags |= UPDATE_PERMISSIONS_ALL; 8356 it.remove(); 8357 } 8358 } 8359 } 8360 8361 // Make sure all dynamic permissions have been assigned to a package, 8362 // and make sure there are no dangling permissions. 8363 it = mSettings.mPermissions.values().iterator(); 8364 while (it.hasNext()) { 8365 final BasePermission bp = it.next(); 8366 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8367 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8368 + bp.name + " pkg=" + bp.sourcePackage 8369 + " info=" + bp.pendingInfo); 8370 if (bp.packageSetting == null && bp.pendingInfo != null) { 8371 final BasePermission tree = findPermissionTreeLP(bp.name); 8372 if (tree != null && tree.perm != null) { 8373 bp.packageSetting = tree.packageSetting; 8374 bp.perm = new PackageParser.Permission(tree.perm.owner, 8375 new PermissionInfo(bp.pendingInfo)); 8376 bp.perm.info.packageName = tree.perm.info.packageName; 8377 bp.perm.info.name = bp.name; 8378 bp.uid = tree.uid; 8379 } 8380 } 8381 } 8382 if (bp.packageSetting == null) { 8383 // We may not yet have parsed the package, so just see if 8384 // we still know about its settings. 8385 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8386 } 8387 if (bp.packageSetting == null) { 8388 Slog.w(TAG, "Removing dangling permission: " + bp.name 8389 + " from package " + bp.sourcePackage); 8390 it.remove(); 8391 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8392 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8393 Slog.i(TAG, "Removing old permission: " + bp.name 8394 + " from package " + bp.sourcePackage); 8395 flags |= UPDATE_PERMISSIONS_ALL; 8396 it.remove(); 8397 } 8398 } 8399 } 8400 8401 // Now update the permissions for all packages, in particular 8402 // replace the granted permissions of the system packages. 8403 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8404 for (PackageParser.Package pkg : mPackages.values()) { 8405 if (pkg != pkgInfo) { 8406 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8407 changingPkg); 8408 } 8409 } 8410 } 8411 8412 if (pkgInfo != null) { 8413 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8414 } 8415 } 8416 8417 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8418 String packageOfInterest) { 8419 // IMPORTANT: There are two types of permissions: install and runtime. 8420 // Install time permissions are granted when the app is installed to 8421 // all device users and users added in the future. Runtime permissions 8422 // are granted at runtime explicitly to specific users. Normal and signature 8423 // protected permissions are install time permissions. Dangerous permissions 8424 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8425 // otherwise they are runtime permissions. This function does not manage 8426 // runtime permissions except for the case an app targeting Lollipop MR1 8427 // being upgraded to target a newer SDK, in which case dangerous permissions 8428 // are transformed from install time to runtime ones. 8429 8430 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8431 if (ps == null) { 8432 return; 8433 } 8434 8435 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8436 8437 PermissionsState permissionsState = ps.getPermissionsState(); 8438 PermissionsState origPermissions = permissionsState; 8439 8440 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8441 8442 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8443 8444 boolean changedInstallPermission = false; 8445 8446 if (replace) { 8447 ps.installPermissionsFixed = false; 8448 if (!ps.isSharedUser()) { 8449 origPermissions = new PermissionsState(permissionsState); 8450 permissionsState.reset(); 8451 } 8452 } 8453 8454 permissionsState.setGlobalGids(mGlobalGids); 8455 8456 final int N = pkg.requestedPermissions.size(); 8457 for (int i=0; i<N; i++) { 8458 final String name = pkg.requestedPermissions.get(i); 8459 final BasePermission bp = mSettings.mPermissions.get(name); 8460 8461 if (DEBUG_INSTALL) { 8462 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8463 } 8464 8465 if (bp == null || bp.packageSetting == null) { 8466 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8467 Slog.w(TAG, "Unknown permission " + name 8468 + " in package " + pkg.packageName); 8469 } 8470 continue; 8471 } 8472 8473 final String perm = bp.name; 8474 boolean allowedSig = false; 8475 int grant = GRANT_DENIED; 8476 8477 // Keep track of app op permissions. 8478 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8479 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8480 if (pkgs == null) { 8481 pkgs = new ArraySet<>(); 8482 mAppOpPermissionPackages.put(bp.name, pkgs); 8483 } 8484 pkgs.add(pkg.packageName); 8485 } 8486 8487 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8488 switch (level) { 8489 case PermissionInfo.PROTECTION_NORMAL: { 8490 // For all apps normal permissions are install time ones. 8491 grant = GRANT_INSTALL; 8492 } break; 8493 8494 case PermissionInfo.PROTECTION_DANGEROUS: { 8495 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8496 // For legacy apps dangerous permissions are install time ones. 8497 grant = GRANT_INSTALL_LEGACY; 8498 } else if (origPermissions.hasInstallPermission(bp.name)) { 8499 // For legacy apps that became modern, install becomes runtime. 8500 grant = GRANT_UPGRADE; 8501 } else if (mPromoteSystemApps 8502 && isSystemApp(ps) 8503 && mExistingSystemPackages.contains(ps.name)) { 8504 // For legacy system apps, install becomes runtime. 8505 // We cannot check hasInstallPermission() for system apps since those 8506 // permissions were granted implicitly and not persisted pre-M. 8507 grant = GRANT_UPGRADE; 8508 } else { 8509 // For modern apps keep runtime permissions unchanged. 8510 grant = GRANT_RUNTIME; 8511 } 8512 } break; 8513 8514 case PermissionInfo.PROTECTION_SIGNATURE: { 8515 // For all apps signature permissions are install time ones. 8516 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8517 if (allowedSig) { 8518 grant = GRANT_INSTALL; 8519 } 8520 } break; 8521 } 8522 8523 if (DEBUG_INSTALL) { 8524 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8525 } 8526 8527 if (grant != GRANT_DENIED) { 8528 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8529 // If this is an existing, non-system package, then 8530 // we can't add any new permissions to it. 8531 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8532 // Except... if this is a permission that was added 8533 // to the platform (note: need to only do this when 8534 // updating the platform). 8535 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8536 grant = GRANT_DENIED; 8537 } 8538 } 8539 } 8540 8541 switch (grant) { 8542 case GRANT_INSTALL: { 8543 // Revoke this as runtime permission to handle the case of 8544 // a runtime permission being downgraded to an install one. 8545 for (int userId : UserManagerService.getInstance().getUserIds()) { 8546 if (origPermissions.getRuntimePermissionState( 8547 bp.name, userId) != null) { 8548 // Revoke the runtime permission and clear the flags. 8549 origPermissions.revokeRuntimePermission(bp, userId); 8550 origPermissions.updatePermissionFlags(bp, userId, 8551 PackageManager.MASK_PERMISSION_FLAGS, 0); 8552 // If we revoked a permission permission, we have to write. 8553 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8554 changedRuntimePermissionUserIds, userId); 8555 } 8556 } 8557 // Grant an install permission. 8558 if (permissionsState.grantInstallPermission(bp) != 8559 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8560 changedInstallPermission = true; 8561 } 8562 } break; 8563 8564 case GRANT_INSTALL_LEGACY: { 8565 // Grant an install permission. 8566 if (permissionsState.grantInstallPermission(bp) != 8567 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8568 changedInstallPermission = true; 8569 } 8570 } break; 8571 8572 case GRANT_RUNTIME: { 8573 // Grant previously granted runtime permissions. 8574 for (int userId : UserManagerService.getInstance().getUserIds()) { 8575 PermissionState permissionState = origPermissions 8576 .getRuntimePermissionState(bp.name, userId); 8577 final int flags = permissionState != null 8578 ? permissionState.getFlags() : 0; 8579 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8580 if (permissionsState.grantRuntimePermission(bp, userId) == 8581 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8582 // If we cannot put the permission as it was, we have to write. 8583 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8584 changedRuntimePermissionUserIds, userId); 8585 } 8586 } 8587 // Propagate the permission flags. 8588 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8589 } 8590 } break; 8591 8592 case GRANT_UPGRADE: { 8593 // Grant runtime permissions for a previously held install permission. 8594 PermissionState permissionState = origPermissions 8595 .getInstallPermissionState(bp.name); 8596 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8597 8598 if (origPermissions.revokeInstallPermission(bp) 8599 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8600 // We will be transferring the permission flags, so clear them. 8601 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8602 PackageManager.MASK_PERMISSION_FLAGS, 0); 8603 changedInstallPermission = true; 8604 } 8605 8606 // If the permission is not to be promoted to runtime we ignore it and 8607 // also its other flags as they are not applicable to install permissions. 8608 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8609 for (int userId : currentUserIds) { 8610 if (permissionsState.grantRuntimePermission(bp, userId) != 8611 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8612 // Transfer the permission flags. 8613 permissionsState.updatePermissionFlags(bp, userId, 8614 flags, flags); 8615 // If we granted the permission, we have to write. 8616 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8617 changedRuntimePermissionUserIds, userId); 8618 } 8619 } 8620 } 8621 } break; 8622 8623 default: { 8624 if (packageOfInterest == null 8625 || packageOfInterest.equals(pkg.packageName)) { 8626 Slog.w(TAG, "Not granting permission " + perm 8627 + " to package " + pkg.packageName 8628 + " because it was previously installed without"); 8629 } 8630 } break; 8631 } 8632 } else { 8633 if (permissionsState.revokeInstallPermission(bp) != 8634 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8635 // Also drop the permission flags. 8636 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8637 PackageManager.MASK_PERMISSION_FLAGS, 0); 8638 changedInstallPermission = true; 8639 Slog.i(TAG, "Un-granting permission " + perm 8640 + " from package " + pkg.packageName 8641 + " (protectionLevel=" + bp.protectionLevel 8642 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8643 + ")"); 8644 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8645 // Don't print warning for app op permissions, since it is fine for them 8646 // not to be granted, there is a UI for the user to decide. 8647 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8648 Slog.w(TAG, "Not granting permission " + perm 8649 + " to package " + pkg.packageName 8650 + " (protectionLevel=" + bp.protectionLevel 8651 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8652 + ")"); 8653 } 8654 } 8655 } 8656 } 8657 8658 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8659 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8660 // This is the first that we have heard about this package, so the 8661 // permissions we have now selected are fixed until explicitly 8662 // changed. 8663 ps.installPermissionsFixed = true; 8664 } 8665 8666 // Persist the runtime permissions state for users with changes. 8667 for (int userId : changedRuntimePermissionUserIds) { 8668 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8669 } 8670 8671 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8672 } 8673 8674 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8675 boolean allowed = false; 8676 final int NP = PackageParser.NEW_PERMISSIONS.length; 8677 for (int ip=0; ip<NP; ip++) { 8678 final PackageParser.NewPermissionInfo npi 8679 = PackageParser.NEW_PERMISSIONS[ip]; 8680 if (npi.name.equals(perm) 8681 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8682 allowed = true; 8683 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8684 + pkg.packageName); 8685 break; 8686 } 8687 } 8688 return allowed; 8689 } 8690 8691 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8692 BasePermission bp, PermissionsState origPermissions) { 8693 boolean allowed; 8694 allowed = (compareSignatures( 8695 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8696 == PackageManager.SIGNATURE_MATCH) 8697 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8698 == PackageManager.SIGNATURE_MATCH); 8699 if (!allowed && (bp.protectionLevel 8700 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8701 if (isSystemApp(pkg)) { 8702 // For updated system applications, a system permission 8703 // is granted only if it had been defined by the original application. 8704 if (pkg.isUpdatedSystemApp()) { 8705 final PackageSetting sysPs = mSettings 8706 .getDisabledSystemPkgLPr(pkg.packageName); 8707 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8708 // If the original was granted this permission, we take 8709 // that grant decision as read and propagate it to the 8710 // update. 8711 if (sysPs.isPrivileged()) { 8712 allowed = true; 8713 } 8714 } else { 8715 // The system apk may have been updated with an older 8716 // version of the one on the data partition, but which 8717 // granted a new system permission that it didn't have 8718 // before. In this case we do want to allow the app to 8719 // now get the new permission if the ancestral apk is 8720 // privileged to get it. 8721 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8722 for (int j=0; 8723 j<sysPs.pkg.requestedPermissions.size(); j++) { 8724 if (perm.equals( 8725 sysPs.pkg.requestedPermissions.get(j))) { 8726 allowed = true; 8727 break; 8728 } 8729 } 8730 } 8731 } 8732 } else { 8733 allowed = isPrivilegedApp(pkg); 8734 } 8735 } 8736 } 8737 if (!allowed) { 8738 if (!allowed && (bp.protectionLevel 8739 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8740 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8741 // If this was a previously normal/dangerous permission that got moved 8742 // to a system permission as part of the runtime permission redesign, then 8743 // we still want to blindly grant it to old apps. 8744 allowed = true; 8745 } 8746 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8747 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8748 // If this permission is to be granted to the system installer and 8749 // this app is an installer, then it gets the permission. 8750 allowed = true; 8751 } 8752 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8753 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8754 // If this permission is to be granted to the system verifier and 8755 // this app is a verifier, then it gets the permission. 8756 allowed = true; 8757 } 8758 if (!allowed && (bp.protectionLevel 8759 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8760 && isSystemApp(pkg)) { 8761 // Any pre-installed system app is allowed to get this permission. 8762 allowed = true; 8763 } 8764 if (!allowed && (bp.protectionLevel 8765 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8766 // For development permissions, a development permission 8767 // is granted only if it was already granted. 8768 allowed = origPermissions.hasInstallPermission(perm); 8769 } 8770 } 8771 return allowed; 8772 } 8773 8774 final class ActivityIntentResolver 8775 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8776 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8777 boolean defaultOnly, int userId) { 8778 if (!sUserManager.exists(userId)) return null; 8779 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8780 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8781 } 8782 8783 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8784 int userId) { 8785 if (!sUserManager.exists(userId)) return null; 8786 mFlags = flags; 8787 return super.queryIntent(intent, resolvedType, 8788 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8789 } 8790 8791 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8792 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8793 if (!sUserManager.exists(userId)) return null; 8794 if (packageActivities == null) { 8795 return null; 8796 } 8797 mFlags = flags; 8798 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8799 final int N = packageActivities.size(); 8800 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8801 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8802 8803 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8804 for (int i = 0; i < N; ++i) { 8805 intentFilters = packageActivities.get(i).intents; 8806 if (intentFilters != null && intentFilters.size() > 0) { 8807 PackageParser.ActivityIntentInfo[] array = 8808 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8809 intentFilters.toArray(array); 8810 listCut.add(array); 8811 } 8812 } 8813 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8814 } 8815 8816 public final void addActivity(PackageParser.Activity a, String type) { 8817 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8818 mActivities.put(a.getComponentName(), a); 8819 if (DEBUG_SHOW_INFO) 8820 Log.v( 8821 TAG, " " + type + " " + 8822 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8823 if (DEBUG_SHOW_INFO) 8824 Log.v(TAG, " Class=" + a.info.name); 8825 final int NI = a.intents.size(); 8826 for (int j=0; j<NI; j++) { 8827 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8828 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8829 intent.setPriority(0); 8830 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8831 + a.className + " with priority > 0, forcing to 0"); 8832 } 8833 if (DEBUG_SHOW_INFO) { 8834 Log.v(TAG, " IntentFilter:"); 8835 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8836 } 8837 if (!intent.debugCheck()) { 8838 Log.w(TAG, "==> For Activity " + a.info.name); 8839 } 8840 addFilter(intent); 8841 } 8842 } 8843 8844 public final void removeActivity(PackageParser.Activity a, String type) { 8845 mActivities.remove(a.getComponentName()); 8846 if (DEBUG_SHOW_INFO) { 8847 Log.v(TAG, " " + type + " " 8848 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8849 : a.info.name) + ":"); 8850 Log.v(TAG, " Class=" + a.info.name); 8851 } 8852 final int NI = a.intents.size(); 8853 for (int j=0; j<NI; j++) { 8854 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8855 if (DEBUG_SHOW_INFO) { 8856 Log.v(TAG, " IntentFilter:"); 8857 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8858 } 8859 removeFilter(intent); 8860 } 8861 } 8862 8863 @Override 8864 protected boolean allowFilterResult( 8865 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8866 ActivityInfo filterAi = filter.activity.info; 8867 for (int i=dest.size()-1; i>=0; i--) { 8868 ActivityInfo destAi = dest.get(i).activityInfo; 8869 if (destAi.name == filterAi.name 8870 && destAi.packageName == filterAi.packageName) { 8871 return false; 8872 } 8873 } 8874 return true; 8875 } 8876 8877 @Override 8878 protected ActivityIntentInfo[] newArray(int size) { 8879 return new ActivityIntentInfo[size]; 8880 } 8881 8882 @Override 8883 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8884 if (!sUserManager.exists(userId)) return true; 8885 PackageParser.Package p = filter.activity.owner; 8886 if (p != null) { 8887 PackageSetting ps = (PackageSetting)p.mExtras; 8888 if (ps != null) { 8889 // System apps are never considered stopped for purposes of 8890 // filtering, because there may be no way for the user to 8891 // actually re-launch them. 8892 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8893 && ps.getStopped(userId); 8894 } 8895 } 8896 return false; 8897 } 8898 8899 @Override 8900 protected boolean isPackageForFilter(String packageName, 8901 PackageParser.ActivityIntentInfo info) { 8902 return packageName.equals(info.activity.owner.packageName); 8903 } 8904 8905 @Override 8906 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8907 int match, int userId) { 8908 if (!sUserManager.exists(userId)) return null; 8909 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8910 return null; 8911 } 8912 final PackageParser.Activity activity = info.activity; 8913 if (mSafeMode && (activity.info.applicationInfo.flags 8914 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8915 return null; 8916 } 8917 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8918 if (ps == null) { 8919 return null; 8920 } 8921 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8922 ps.readUserState(userId), userId); 8923 if (ai == null) { 8924 return null; 8925 } 8926 final ResolveInfo res = new ResolveInfo(); 8927 res.activityInfo = ai; 8928 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8929 res.filter = info; 8930 } 8931 if (info != null) { 8932 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8933 } 8934 res.priority = info.getPriority(); 8935 res.preferredOrder = activity.owner.mPreferredOrder; 8936 //System.out.println("Result: " + res.activityInfo.className + 8937 // " = " + res.priority); 8938 res.match = match; 8939 res.isDefault = info.hasDefault; 8940 res.labelRes = info.labelRes; 8941 res.nonLocalizedLabel = info.nonLocalizedLabel; 8942 if (userNeedsBadging(userId)) { 8943 res.noResourceId = true; 8944 } else { 8945 res.icon = info.icon; 8946 } 8947 res.iconResourceId = info.icon; 8948 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8949 return res; 8950 } 8951 8952 @Override 8953 protected void sortResults(List<ResolveInfo> results) { 8954 Collections.sort(results, mResolvePrioritySorter); 8955 } 8956 8957 @Override 8958 protected void dumpFilter(PrintWriter out, String prefix, 8959 PackageParser.ActivityIntentInfo filter) { 8960 out.print(prefix); out.print( 8961 Integer.toHexString(System.identityHashCode(filter.activity))); 8962 out.print(' '); 8963 filter.activity.printComponentShortName(out); 8964 out.print(" filter "); 8965 out.println(Integer.toHexString(System.identityHashCode(filter))); 8966 } 8967 8968 @Override 8969 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8970 return filter.activity; 8971 } 8972 8973 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8974 PackageParser.Activity activity = (PackageParser.Activity)label; 8975 out.print(prefix); out.print( 8976 Integer.toHexString(System.identityHashCode(activity))); 8977 out.print(' '); 8978 activity.printComponentShortName(out); 8979 if (count > 1) { 8980 out.print(" ("); out.print(count); out.print(" filters)"); 8981 } 8982 out.println(); 8983 } 8984 8985// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8986// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8987// final List<ResolveInfo> retList = Lists.newArrayList(); 8988// while (i.hasNext()) { 8989// final ResolveInfo resolveInfo = i.next(); 8990// if (isEnabledLP(resolveInfo.activityInfo)) { 8991// retList.add(resolveInfo); 8992// } 8993// } 8994// return retList; 8995// } 8996 8997 // Keys are String (activity class name), values are Activity. 8998 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8999 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9000 private int mFlags; 9001 } 9002 9003 private final class ServiceIntentResolver 9004 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9005 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9006 boolean defaultOnly, int userId) { 9007 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9008 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9009 } 9010 9011 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9012 int userId) { 9013 if (!sUserManager.exists(userId)) return null; 9014 mFlags = flags; 9015 return super.queryIntent(intent, resolvedType, 9016 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9017 } 9018 9019 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9020 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9021 if (!sUserManager.exists(userId)) return null; 9022 if (packageServices == null) { 9023 return null; 9024 } 9025 mFlags = flags; 9026 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9027 final int N = packageServices.size(); 9028 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9029 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9030 9031 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9032 for (int i = 0; i < N; ++i) { 9033 intentFilters = packageServices.get(i).intents; 9034 if (intentFilters != null && intentFilters.size() > 0) { 9035 PackageParser.ServiceIntentInfo[] array = 9036 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9037 intentFilters.toArray(array); 9038 listCut.add(array); 9039 } 9040 } 9041 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9042 } 9043 9044 public final void addService(PackageParser.Service s) { 9045 mServices.put(s.getComponentName(), s); 9046 if (DEBUG_SHOW_INFO) { 9047 Log.v(TAG, " " 9048 + (s.info.nonLocalizedLabel != null 9049 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9050 Log.v(TAG, " Class=" + s.info.name); 9051 } 9052 final int NI = s.intents.size(); 9053 int j; 9054 for (j=0; j<NI; j++) { 9055 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9056 if (DEBUG_SHOW_INFO) { 9057 Log.v(TAG, " IntentFilter:"); 9058 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9059 } 9060 if (!intent.debugCheck()) { 9061 Log.w(TAG, "==> For Service " + s.info.name); 9062 } 9063 addFilter(intent); 9064 } 9065 } 9066 9067 public final void removeService(PackageParser.Service s) { 9068 mServices.remove(s.getComponentName()); 9069 if (DEBUG_SHOW_INFO) { 9070 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9071 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9072 Log.v(TAG, " Class=" + s.info.name); 9073 } 9074 final int NI = s.intents.size(); 9075 int j; 9076 for (j=0; j<NI; j++) { 9077 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9078 if (DEBUG_SHOW_INFO) { 9079 Log.v(TAG, " IntentFilter:"); 9080 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9081 } 9082 removeFilter(intent); 9083 } 9084 } 9085 9086 @Override 9087 protected boolean allowFilterResult( 9088 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9089 ServiceInfo filterSi = filter.service.info; 9090 for (int i=dest.size()-1; i>=0; i--) { 9091 ServiceInfo destAi = dest.get(i).serviceInfo; 9092 if (destAi.name == filterSi.name 9093 && destAi.packageName == filterSi.packageName) { 9094 return false; 9095 } 9096 } 9097 return true; 9098 } 9099 9100 @Override 9101 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9102 return new PackageParser.ServiceIntentInfo[size]; 9103 } 9104 9105 @Override 9106 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9107 if (!sUserManager.exists(userId)) return true; 9108 PackageParser.Package p = filter.service.owner; 9109 if (p != null) { 9110 PackageSetting ps = (PackageSetting)p.mExtras; 9111 if (ps != null) { 9112 // System apps are never considered stopped for purposes of 9113 // filtering, because there may be no way for the user to 9114 // actually re-launch them. 9115 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9116 && ps.getStopped(userId); 9117 } 9118 } 9119 return false; 9120 } 9121 9122 @Override 9123 protected boolean isPackageForFilter(String packageName, 9124 PackageParser.ServiceIntentInfo info) { 9125 return packageName.equals(info.service.owner.packageName); 9126 } 9127 9128 @Override 9129 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9130 int match, int userId) { 9131 if (!sUserManager.exists(userId)) return null; 9132 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9133 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9134 return null; 9135 } 9136 final PackageParser.Service service = info.service; 9137 if (mSafeMode && (service.info.applicationInfo.flags 9138 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9139 return null; 9140 } 9141 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9142 if (ps == null) { 9143 return null; 9144 } 9145 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9146 ps.readUserState(userId), userId); 9147 if (si == null) { 9148 return null; 9149 } 9150 final ResolveInfo res = new ResolveInfo(); 9151 res.serviceInfo = si; 9152 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9153 res.filter = filter; 9154 } 9155 res.priority = info.getPriority(); 9156 res.preferredOrder = service.owner.mPreferredOrder; 9157 res.match = match; 9158 res.isDefault = info.hasDefault; 9159 res.labelRes = info.labelRes; 9160 res.nonLocalizedLabel = info.nonLocalizedLabel; 9161 res.icon = info.icon; 9162 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9163 return res; 9164 } 9165 9166 @Override 9167 protected void sortResults(List<ResolveInfo> results) { 9168 Collections.sort(results, mResolvePrioritySorter); 9169 } 9170 9171 @Override 9172 protected void dumpFilter(PrintWriter out, String prefix, 9173 PackageParser.ServiceIntentInfo filter) { 9174 out.print(prefix); out.print( 9175 Integer.toHexString(System.identityHashCode(filter.service))); 9176 out.print(' '); 9177 filter.service.printComponentShortName(out); 9178 out.print(" filter "); 9179 out.println(Integer.toHexString(System.identityHashCode(filter))); 9180 } 9181 9182 @Override 9183 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9184 return filter.service; 9185 } 9186 9187 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9188 PackageParser.Service service = (PackageParser.Service)label; 9189 out.print(prefix); out.print( 9190 Integer.toHexString(System.identityHashCode(service))); 9191 out.print(' '); 9192 service.printComponentShortName(out); 9193 if (count > 1) { 9194 out.print(" ("); out.print(count); out.print(" filters)"); 9195 } 9196 out.println(); 9197 } 9198 9199// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9200// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9201// final List<ResolveInfo> retList = Lists.newArrayList(); 9202// while (i.hasNext()) { 9203// final ResolveInfo resolveInfo = (ResolveInfo) i; 9204// if (isEnabledLP(resolveInfo.serviceInfo)) { 9205// retList.add(resolveInfo); 9206// } 9207// } 9208// return retList; 9209// } 9210 9211 // Keys are String (activity class name), values are Activity. 9212 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9213 = new ArrayMap<ComponentName, PackageParser.Service>(); 9214 private int mFlags; 9215 }; 9216 9217 private final class ProviderIntentResolver 9218 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9219 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9220 boolean defaultOnly, int userId) { 9221 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9222 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9223 } 9224 9225 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9226 int userId) { 9227 if (!sUserManager.exists(userId)) 9228 return null; 9229 mFlags = flags; 9230 return super.queryIntent(intent, resolvedType, 9231 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9232 } 9233 9234 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9235 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9236 if (!sUserManager.exists(userId)) 9237 return null; 9238 if (packageProviders == null) { 9239 return null; 9240 } 9241 mFlags = flags; 9242 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9243 final int N = packageProviders.size(); 9244 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9245 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9246 9247 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9248 for (int i = 0; i < N; ++i) { 9249 intentFilters = packageProviders.get(i).intents; 9250 if (intentFilters != null && intentFilters.size() > 0) { 9251 PackageParser.ProviderIntentInfo[] array = 9252 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9253 intentFilters.toArray(array); 9254 listCut.add(array); 9255 } 9256 } 9257 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9258 } 9259 9260 public final void addProvider(PackageParser.Provider p) { 9261 if (mProviders.containsKey(p.getComponentName())) { 9262 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9263 return; 9264 } 9265 9266 mProviders.put(p.getComponentName(), p); 9267 if (DEBUG_SHOW_INFO) { 9268 Log.v(TAG, " " 9269 + (p.info.nonLocalizedLabel != null 9270 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9271 Log.v(TAG, " Class=" + p.info.name); 9272 } 9273 final int NI = p.intents.size(); 9274 int j; 9275 for (j = 0; j < NI; j++) { 9276 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9277 if (DEBUG_SHOW_INFO) { 9278 Log.v(TAG, " IntentFilter:"); 9279 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9280 } 9281 if (!intent.debugCheck()) { 9282 Log.w(TAG, "==> For Provider " + p.info.name); 9283 } 9284 addFilter(intent); 9285 } 9286 } 9287 9288 public final void removeProvider(PackageParser.Provider p) { 9289 mProviders.remove(p.getComponentName()); 9290 if (DEBUG_SHOW_INFO) { 9291 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9292 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9293 Log.v(TAG, " Class=" + p.info.name); 9294 } 9295 final int NI = p.intents.size(); 9296 int j; 9297 for (j = 0; j < NI; j++) { 9298 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9299 if (DEBUG_SHOW_INFO) { 9300 Log.v(TAG, " IntentFilter:"); 9301 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9302 } 9303 removeFilter(intent); 9304 } 9305 } 9306 9307 @Override 9308 protected boolean allowFilterResult( 9309 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9310 ProviderInfo filterPi = filter.provider.info; 9311 for (int i = dest.size() - 1; i >= 0; i--) { 9312 ProviderInfo destPi = dest.get(i).providerInfo; 9313 if (destPi.name == filterPi.name 9314 && destPi.packageName == filterPi.packageName) { 9315 return false; 9316 } 9317 } 9318 return true; 9319 } 9320 9321 @Override 9322 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9323 return new PackageParser.ProviderIntentInfo[size]; 9324 } 9325 9326 @Override 9327 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9328 if (!sUserManager.exists(userId)) 9329 return true; 9330 PackageParser.Package p = filter.provider.owner; 9331 if (p != null) { 9332 PackageSetting ps = (PackageSetting) p.mExtras; 9333 if (ps != null) { 9334 // System apps are never considered stopped for purposes of 9335 // filtering, because there may be no way for the user to 9336 // actually re-launch them. 9337 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9338 && ps.getStopped(userId); 9339 } 9340 } 9341 return false; 9342 } 9343 9344 @Override 9345 protected boolean isPackageForFilter(String packageName, 9346 PackageParser.ProviderIntentInfo info) { 9347 return packageName.equals(info.provider.owner.packageName); 9348 } 9349 9350 @Override 9351 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9352 int match, int userId) { 9353 if (!sUserManager.exists(userId)) 9354 return null; 9355 final PackageParser.ProviderIntentInfo info = filter; 9356 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9357 return null; 9358 } 9359 final PackageParser.Provider provider = info.provider; 9360 if (mSafeMode && (provider.info.applicationInfo.flags 9361 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9362 return null; 9363 } 9364 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9365 if (ps == null) { 9366 return null; 9367 } 9368 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9369 ps.readUserState(userId), userId); 9370 if (pi == null) { 9371 return null; 9372 } 9373 final ResolveInfo res = new ResolveInfo(); 9374 res.providerInfo = pi; 9375 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9376 res.filter = filter; 9377 } 9378 res.priority = info.getPriority(); 9379 res.preferredOrder = provider.owner.mPreferredOrder; 9380 res.match = match; 9381 res.isDefault = info.hasDefault; 9382 res.labelRes = info.labelRes; 9383 res.nonLocalizedLabel = info.nonLocalizedLabel; 9384 res.icon = info.icon; 9385 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9386 return res; 9387 } 9388 9389 @Override 9390 protected void sortResults(List<ResolveInfo> results) { 9391 Collections.sort(results, mResolvePrioritySorter); 9392 } 9393 9394 @Override 9395 protected void dumpFilter(PrintWriter out, String prefix, 9396 PackageParser.ProviderIntentInfo filter) { 9397 out.print(prefix); 9398 out.print( 9399 Integer.toHexString(System.identityHashCode(filter.provider))); 9400 out.print(' '); 9401 filter.provider.printComponentShortName(out); 9402 out.print(" filter "); 9403 out.println(Integer.toHexString(System.identityHashCode(filter))); 9404 } 9405 9406 @Override 9407 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9408 return filter.provider; 9409 } 9410 9411 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9412 PackageParser.Provider provider = (PackageParser.Provider)label; 9413 out.print(prefix); out.print( 9414 Integer.toHexString(System.identityHashCode(provider))); 9415 out.print(' '); 9416 provider.printComponentShortName(out); 9417 if (count > 1) { 9418 out.print(" ("); out.print(count); out.print(" filters)"); 9419 } 9420 out.println(); 9421 } 9422 9423 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9424 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9425 private int mFlags; 9426 }; 9427 9428 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9429 new Comparator<ResolveInfo>() { 9430 public int compare(ResolveInfo r1, ResolveInfo r2) { 9431 int v1 = r1.priority; 9432 int v2 = r2.priority; 9433 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9434 if (v1 != v2) { 9435 return (v1 > v2) ? -1 : 1; 9436 } 9437 v1 = r1.preferredOrder; 9438 v2 = r2.preferredOrder; 9439 if (v1 != v2) { 9440 return (v1 > v2) ? -1 : 1; 9441 } 9442 if (r1.isDefault != r2.isDefault) { 9443 return r1.isDefault ? -1 : 1; 9444 } 9445 v1 = r1.match; 9446 v2 = r2.match; 9447 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9448 if (v1 != v2) { 9449 return (v1 > v2) ? -1 : 1; 9450 } 9451 if (r1.system != r2.system) { 9452 return r1.system ? -1 : 1; 9453 } 9454 return 0; 9455 } 9456 }; 9457 9458 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9459 new Comparator<ProviderInfo>() { 9460 public int compare(ProviderInfo p1, ProviderInfo p2) { 9461 final int v1 = p1.initOrder; 9462 final int v2 = p2.initOrder; 9463 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9464 } 9465 }; 9466 9467 final void sendPackageBroadcast(final String action, final String pkg, 9468 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9469 final int[] userIds) { 9470 mHandler.post(new Runnable() { 9471 @Override 9472 public void run() { 9473 try { 9474 final IActivityManager am = ActivityManagerNative.getDefault(); 9475 if (am == null) return; 9476 final int[] resolvedUserIds; 9477 if (userIds == null) { 9478 resolvedUserIds = am.getRunningUserIds(); 9479 } else { 9480 resolvedUserIds = userIds; 9481 } 9482 for (int id : resolvedUserIds) { 9483 final Intent intent = new Intent(action, 9484 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9485 if (extras != null) { 9486 intent.putExtras(extras); 9487 } 9488 if (targetPkg != null) { 9489 intent.setPackage(targetPkg); 9490 } 9491 // Modify the UID when posting to other users 9492 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9493 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9494 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9495 intent.putExtra(Intent.EXTRA_UID, uid); 9496 } 9497 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9498 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9499 if (DEBUG_BROADCASTS) { 9500 RuntimeException here = new RuntimeException("here"); 9501 here.fillInStackTrace(); 9502 Slog.d(TAG, "Sending to user " + id + ": " 9503 + intent.toShortString(false, true, false, false) 9504 + " " + intent.getExtras(), here); 9505 } 9506 am.broadcastIntent(null, intent, null, finishedReceiver, 9507 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9508 null, finishedReceiver != null, false, id); 9509 } 9510 } catch (RemoteException ex) { 9511 } 9512 } 9513 }); 9514 } 9515 9516 /** 9517 * Check if the external storage media is available. This is true if there 9518 * is a mounted external storage medium or if the external storage is 9519 * emulated. 9520 */ 9521 private boolean isExternalMediaAvailable() { 9522 return mMediaMounted || Environment.isExternalStorageEmulated(); 9523 } 9524 9525 @Override 9526 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9527 // writer 9528 synchronized (mPackages) { 9529 if (!isExternalMediaAvailable()) { 9530 // If the external storage is no longer mounted at this point, 9531 // the caller may not have been able to delete all of this 9532 // packages files and can not delete any more. Bail. 9533 return null; 9534 } 9535 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9536 if (lastPackage != null) { 9537 pkgs.remove(lastPackage); 9538 } 9539 if (pkgs.size() > 0) { 9540 return pkgs.get(0); 9541 } 9542 } 9543 return null; 9544 } 9545 9546 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9547 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9548 userId, andCode ? 1 : 0, packageName); 9549 if (mSystemReady) { 9550 msg.sendToTarget(); 9551 } else { 9552 if (mPostSystemReadyMessages == null) { 9553 mPostSystemReadyMessages = new ArrayList<>(); 9554 } 9555 mPostSystemReadyMessages.add(msg); 9556 } 9557 } 9558 9559 void startCleaningPackages() { 9560 // reader 9561 synchronized (mPackages) { 9562 if (!isExternalMediaAvailable()) { 9563 return; 9564 } 9565 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9566 return; 9567 } 9568 } 9569 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9570 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9571 IActivityManager am = ActivityManagerNative.getDefault(); 9572 if (am != null) { 9573 try { 9574 am.startService(null, intent, null, mContext.getOpPackageName(), 9575 UserHandle.USER_OWNER); 9576 } catch (RemoteException e) { 9577 } 9578 } 9579 } 9580 9581 @Override 9582 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9583 int installFlags, String installerPackageName, VerificationParams verificationParams, 9584 String packageAbiOverride) { 9585 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9586 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9587 } 9588 9589 @Override 9590 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9591 int installFlags, String installerPackageName, VerificationParams verificationParams, 9592 String packageAbiOverride, int userId) { 9593 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9594 9595 final int callingUid = Binder.getCallingUid(); 9596 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9597 9598 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9599 try { 9600 if (observer != null) { 9601 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9602 } 9603 } catch (RemoteException re) { 9604 } 9605 return; 9606 } 9607 9608 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9609 installFlags |= PackageManager.INSTALL_FROM_ADB; 9610 9611 } else { 9612 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9613 // about installerPackageName. 9614 9615 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9616 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9617 } 9618 9619 UserHandle user; 9620 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9621 user = UserHandle.ALL; 9622 } else { 9623 user = new UserHandle(userId); 9624 } 9625 9626 // Only system components can circumvent runtime permissions when installing. 9627 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9628 && mContext.checkCallingOrSelfPermission(Manifest.permission 9629 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9630 throw new SecurityException("You need the " 9631 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9632 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9633 } 9634 9635 verificationParams.setInstallerUid(callingUid); 9636 9637 final File originFile = new File(originPath); 9638 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9639 9640 final Message msg = mHandler.obtainMessage(INIT_COPY); 9641 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9642 null, verificationParams, user, packageAbiOverride, null); 9643 mHandler.sendMessage(msg); 9644 } 9645 9646 void installStage(String packageName, File stagedDir, String stagedCid, 9647 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9648 String installerPackageName, int installerUid, UserHandle user) { 9649 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9650 params.referrerUri, installerUid, null); 9651 verifParams.setInstallerUid(installerUid); 9652 9653 final OriginInfo origin; 9654 if (stagedDir != null) { 9655 origin = OriginInfo.fromStagedFile(stagedDir); 9656 } else { 9657 origin = OriginInfo.fromStagedContainer(stagedCid); 9658 } 9659 9660 final Message msg = mHandler.obtainMessage(INIT_COPY); 9661 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9662 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9663 params.grantedRuntimePermissions); 9664 9665 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9666 System.identityHashCode(msg.obj)); 9667 9668 mHandler.sendMessage(msg); 9669 } 9670 9671 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9672 Bundle extras = new Bundle(1); 9673 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9674 9675 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9676 packageName, extras, null, null, new int[] {userId}); 9677 try { 9678 IActivityManager am = ActivityManagerNative.getDefault(); 9679 final boolean isSystem = 9680 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9681 if (isSystem && am.isUserRunning(userId, false)) { 9682 // The just-installed/enabled app is bundled on the system, so presumed 9683 // to be able to run automatically without needing an explicit launch. 9684 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9685 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9686 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9687 .setPackage(packageName); 9688 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9689 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9690 } 9691 } catch (RemoteException e) { 9692 // shouldn't happen 9693 Slog.w(TAG, "Unable to bootstrap installed package", e); 9694 } 9695 } 9696 9697 @Override 9698 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9699 int userId) { 9700 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9701 PackageSetting pkgSetting; 9702 final int uid = Binder.getCallingUid(); 9703 enforceCrossUserPermission(uid, userId, true, true, 9704 "setApplicationHiddenSetting for user " + userId); 9705 9706 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9707 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9708 return false; 9709 } 9710 9711 long callingId = Binder.clearCallingIdentity(); 9712 try { 9713 boolean sendAdded = false; 9714 boolean sendRemoved = false; 9715 // writer 9716 synchronized (mPackages) { 9717 pkgSetting = mSettings.mPackages.get(packageName); 9718 if (pkgSetting == null) { 9719 return false; 9720 } 9721 if (pkgSetting.getHidden(userId) != hidden) { 9722 pkgSetting.setHidden(hidden, userId); 9723 mSettings.writePackageRestrictionsLPr(userId); 9724 if (hidden) { 9725 sendRemoved = true; 9726 } else { 9727 sendAdded = true; 9728 } 9729 } 9730 } 9731 if (sendAdded) { 9732 sendPackageAddedForUser(packageName, pkgSetting, userId); 9733 return true; 9734 } 9735 if (sendRemoved) { 9736 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9737 "hiding pkg"); 9738 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9739 return true; 9740 } 9741 } finally { 9742 Binder.restoreCallingIdentity(callingId); 9743 } 9744 return false; 9745 } 9746 9747 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9748 int userId) { 9749 final PackageRemovedInfo info = new PackageRemovedInfo(); 9750 info.removedPackage = packageName; 9751 info.removedUsers = new int[] {userId}; 9752 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9753 info.sendBroadcast(false, false, false); 9754 } 9755 9756 /** 9757 * Returns true if application is not found or there was an error. Otherwise it returns 9758 * the hidden state of the package for the given user. 9759 */ 9760 @Override 9761 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9762 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9763 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9764 false, "getApplicationHidden for user " + userId); 9765 PackageSetting pkgSetting; 9766 long callingId = Binder.clearCallingIdentity(); 9767 try { 9768 // writer 9769 synchronized (mPackages) { 9770 pkgSetting = mSettings.mPackages.get(packageName); 9771 if (pkgSetting == null) { 9772 return true; 9773 } 9774 return pkgSetting.getHidden(userId); 9775 } 9776 } finally { 9777 Binder.restoreCallingIdentity(callingId); 9778 } 9779 } 9780 9781 /** 9782 * @hide 9783 */ 9784 @Override 9785 public int installExistingPackageAsUser(String packageName, int userId) { 9786 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9787 null); 9788 PackageSetting pkgSetting; 9789 final int uid = Binder.getCallingUid(); 9790 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9791 + userId); 9792 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9793 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9794 } 9795 9796 long callingId = Binder.clearCallingIdentity(); 9797 try { 9798 boolean sendAdded = false; 9799 9800 // writer 9801 synchronized (mPackages) { 9802 pkgSetting = mSettings.mPackages.get(packageName); 9803 if (pkgSetting == null) { 9804 return PackageManager.INSTALL_FAILED_INVALID_URI; 9805 } 9806 if (!pkgSetting.getInstalled(userId)) { 9807 pkgSetting.setInstalled(true, userId); 9808 pkgSetting.setHidden(false, userId); 9809 mSettings.writePackageRestrictionsLPr(userId); 9810 sendAdded = true; 9811 } 9812 } 9813 9814 if (sendAdded) { 9815 sendPackageAddedForUser(packageName, pkgSetting, userId); 9816 } 9817 } finally { 9818 Binder.restoreCallingIdentity(callingId); 9819 } 9820 9821 return PackageManager.INSTALL_SUCCEEDED; 9822 } 9823 9824 boolean isUserRestricted(int userId, String restrictionKey) { 9825 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9826 if (restrictions.getBoolean(restrictionKey, false)) { 9827 Log.w(TAG, "User is restricted: " + restrictionKey); 9828 return true; 9829 } 9830 return false; 9831 } 9832 9833 @Override 9834 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9835 mContext.enforceCallingOrSelfPermission( 9836 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9837 "Only package verification agents can verify applications"); 9838 9839 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9840 final PackageVerificationResponse response = new PackageVerificationResponse( 9841 verificationCode, Binder.getCallingUid()); 9842 msg.arg1 = id; 9843 msg.obj = response; 9844 mHandler.sendMessage(msg); 9845 } 9846 9847 @Override 9848 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9849 long millisecondsToDelay) { 9850 mContext.enforceCallingOrSelfPermission( 9851 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9852 "Only package verification agents can extend verification timeouts"); 9853 9854 final PackageVerificationState state = mPendingVerification.get(id); 9855 final PackageVerificationResponse response = new PackageVerificationResponse( 9856 verificationCodeAtTimeout, Binder.getCallingUid()); 9857 9858 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9859 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9860 } 9861 if (millisecondsToDelay < 0) { 9862 millisecondsToDelay = 0; 9863 } 9864 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9865 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9866 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9867 } 9868 9869 if ((state != null) && !state.timeoutExtended()) { 9870 state.extendTimeout(); 9871 9872 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9873 msg.arg1 = id; 9874 msg.obj = response; 9875 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9876 } 9877 } 9878 9879 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9880 int verificationCode, UserHandle user) { 9881 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9882 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9883 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9884 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9885 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9886 9887 mContext.sendBroadcastAsUser(intent, user, 9888 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9889 } 9890 9891 private ComponentName matchComponentForVerifier(String packageName, 9892 List<ResolveInfo> receivers) { 9893 ActivityInfo targetReceiver = null; 9894 9895 final int NR = receivers.size(); 9896 for (int i = 0; i < NR; i++) { 9897 final ResolveInfo info = receivers.get(i); 9898 if (info.activityInfo == null) { 9899 continue; 9900 } 9901 9902 if (packageName.equals(info.activityInfo.packageName)) { 9903 targetReceiver = info.activityInfo; 9904 break; 9905 } 9906 } 9907 9908 if (targetReceiver == null) { 9909 return null; 9910 } 9911 9912 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9913 } 9914 9915 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9916 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9917 if (pkgInfo.verifiers.length == 0) { 9918 return null; 9919 } 9920 9921 final int N = pkgInfo.verifiers.length; 9922 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9923 for (int i = 0; i < N; i++) { 9924 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9925 9926 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9927 receivers); 9928 if (comp == null) { 9929 continue; 9930 } 9931 9932 final int verifierUid = getUidForVerifier(verifierInfo); 9933 if (verifierUid == -1) { 9934 continue; 9935 } 9936 9937 if (DEBUG_VERIFY) { 9938 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9939 + " with the correct signature"); 9940 } 9941 sufficientVerifiers.add(comp); 9942 verificationState.addSufficientVerifier(verifierUid); 9943 } 9944 9945 return sufficientVerifiers; 9946 } 9947 9948 private int getUidForVerifier(VerifierInfo verifierInfo) { 9949 synchronized (mPackages) { 9950 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9951 if (pkg == null) { 9952 return -1; 9953 } else if (pkg.mSignatures.length != 1) { 9954 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9955 + " has more than one signature; ignoring"); 9956 return -1; 9957 } 9958 9959 /* 9960 * If the public key of the package's signature does not match 9961 * our expected public key, then this is a different package and 9962 * we should skip. 9963 */ 9964 9965 final byte[] expectedPublicKey; 9966 try { 9967 final Signature verifierSig = pkg.mSignatures[0]; 9968 final PublicKey publicKey = verifierSig.getPublicKey(); 9969 expectedPublicKey = publicKey.getEncoded(); 9970 } catch (CertificateException e) { 9971 return -1; 9972 } 9973 9974 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9975 9976 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9977 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9978 + " does not have the expected public key; ignoring"); 9979 return -1; 9980 } 9981 9982 return pkg.applicationInfo.uid; 9983 } 9984 } 9985 9986 @Override 9987 public void finishPackageInstall(int token) { 9988 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9989 9990 if (DEBUG_INSTALL) { 9991 Slog.v(TAG, "BM finishing package install for " + token); 9992 } 9993 9994 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9995 mHandler.sendMessage(msg); 9996 } 9997 9998 /** 9999 * Get the verification agent timeout. 10000 * 10001 * @return verification timeout in milliseconds 10002 */ 10003 private long getVerificationTimeout() { 10004 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10005 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10006 DEFAULT_VERIFICATION_TIMEOUT); 10007 } 10008 10009 /** 10010 * Get the default verification agent response code. 10011 * 10012 * @return default verification response code 10013 */ 10014 private int getDefaultVerificationResponse() { 10015 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10016 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10017 DEFAULT_VERIFICATION_RESPONSE); 10018 } 10019 10020 /** 10021 * Check whether or not package verification has been enabled. 10022 * 10023 * @return true if verification should be performed 10024 */ 10025 private boolean isVerificationEnabled(int userId, int installFlags) { 10026 if (!DEFAULT_VERIFY_ENABLE) { 10027 return false; 10028 } 10029 10030 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10031 10032 // Check if installing from ADB 10033 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10034 // Do not run verification in a test harness environment 10035 if (ActivityManager.isRunningInTestHarness()) { 10036 return false; 10037 } 10038 if (ensureVerifyAppsEnabled) { 10039 return true; 10040 } 10041 // Check if the developer does not want package verification for ADB installs 10042 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10043 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10044 return false; 10045 } 10046 } 10047 10048 if (ensureVerifyAppsEnabled) { 10049 return true; 10050 } 10051 10052 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10053 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10054 } 10055 10056 @Override 10057 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10058 throws RemoteException { 10059 mContext.enforceCallingOrSelfPermission( 10060 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10061 "Only intentfilter verification agents can verify applications"); 10062 10063 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10064 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10065 Binder.getCallingUid(), verificationCode, failedDomains); 10066 msg.arg1 = id; 10067 msg.obj = response; 10068 mHandler.sendMessage(msg); 10069 } 10070 10071 @Override 10072 public int getIntentVerificationStatus(String packageName, int userId) { 10073 synchronized (mPackages) { 10074 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10075 } 10076 } 10077 10078 @Override 10079 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10080 mContext.enforceCallingOrSelfPermission( 10081 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10082 10083 boolean result = false; 10084 synchronized (mPackages) { 10085 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10086 } 10087 if (result) { 10088 scheduleWritePackageRestrictionsLocked(userId); 10089 } 10090 return result; 10091 } 10092 10093 @Override 10094 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10095 synchronized (mPackages) { 10096 return mSettings.getIntentFilterVerificationsLPr(packageName); 10097 } 10098 } 10099 10100 @Override 10101 public List<IntentFilter> getAllIntentFilters(String packageName) { 10102 if (TextUtils.isEmpty(packageName)) { 10103 return Collections.<IntentFilter>emptyList(); 10104 } 10105 synchronized (mPackages) { 10106 PackageParser.Package pkg = mPackages.get(packageName); 10107 if (pkg == null || pkg.activities == null) { 10108 return Collections.<IntentFilter>emptyList(); 10109 } 10110 final int count = pkg.activities.size(); 10111 ArrayList<IntentFilter> result = new ArrayList<>(); 10112 for (int n=0; n<count; n++) { 10113 PackageParser.Activity activity = pkg.activities.get(n); 10114 if (activity.intents != null || activity.intents.size() > 0) { 10115 result.addAll(activity.intents); 10116 } 10117 } 10118 return result; 10119 } 10120 } 10121 10122 @Override 10123 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10124 mContext.enforceCallingOrSelfPermission( 10125 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10126 10127 synchronized (mPackages) { 10128 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10129 if (packageName != null) { 10130 result |= updateIntentVerificationStatus(packageName, 10131 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10132 userId); 10133 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10134 packageName, userId); 10135 } 10136 return result; 10137 } 10138 } 10139 10140 @Override 10141 public String getDefaultBrowserPackageName(int userId) { 10142 synchronized (mPackages) { 10143 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10144 } 10145 } 10146 10147 /** 10148 * Get the "allow unknown sources" setting. 10149 * 10150 * @return the current "allow unknown sources" setting 10151 */ 10152 private int getUnknownSourcesSettings() { 10153 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10154 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10155 -1); 10156 } 10157 10158 @Override 10159 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10160 final int uid = Binder.getCallingUid(); 10161 // writer 10162 synchronized (mPackages) { 10163 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10164 if (targetPackageSetting == null) { 10165 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10166 } 10167 10168 PackageSetting installerPackageSetting; 10169 if (installerPackageName != null) { 10170 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10171 if (installerPackageSetting == null) { 10172 throw new IllegalArgumentException("Unknown installer package: " 10173 + installerPackageName); 10174 } 10175 } else { 10176 installerPackageSetting = null; 10177 } 10178 10179 Signature[] callerSignature; 10180 Object obj = mSettings.getUserIdLPr(uid); 10181 if (obj != null) { 10182 if (obj instanceof SharedUserSetting) { 10183 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10184 } else if (obj instanceof PackageSetting) { 10185 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10186 } else { 10187 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10188 } 10189 } else { 10190 throw new SecurityException("Unknown calling uid " + uid); 10191 } 10192 10193 // Verify: can't set installerPackageName to a package that is 10194 // not signed with the same cert as the caller. 10195 if (installerPackageSetting != null) { 10196 if (compareSignatures(callerSignature, 10197 installerPackageSetting.signatures.mSignatures) 10198 != PackageManager.SIGNATURE_MATCH) { 10199 throw new SecurityException( 10200 "Caller does not have same cert as new installer package " 10201 + installerPackageName); 10202 } 10203 } 10204 10205 // Verify: if target already has an installer package, it must 10206 // be signed with the same cert as the caller. 10207 if (targetPackageSetting.installerPackageName != null) { 10208 PackageSetting setting = mSettings.mPackages.get( 10209 targetPackageSetting.installerPackageName); 10210 // If the currently set package isn't valid, then it's always 10211 // okay to change it. 10212 if (setting != null) { 10213 if (compareSignatures(callerSignature, 10214 setting.signatures.mSignatures) 10215 != PackageManager.SIGNATURE_MATCH) { 10216 throw new SecurityException( 10217 "Caller does not have same cert as old installer package " 10218 + targetPackageSetting.installerPackageName); 10219 } 10220 } 10221 } 10222 10223 // Okay! 10224 targetPackageSetting.installerPackageName = installerPackageName; 10225 scheduleWriteSettingsLocked(); 10226 } 10227 } 10228 10229 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10230 // Queue up an async operation since the package installation may take a little while. 10231 mHandler.post(new Runnable() { 10232 public void run() { 10233 mHandler.removeCallbacks(this); 10234 // Result object to be returned 10235 PackageInstalledInfo res = new PackageInstalledInfo(); 10236 res.returnCode = currentStatus; 10237 res.uid = -1; 10238 res.pkg = null; 10239 res.removedInfo = new PackageRemovedInfo(); 10240 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10241 args.doPreInstall(res.returnCode); 10242 synchronized (mInstallLock) { 10243 installPackageTracedLI(args, res); 10244 } 10245 args.doPostInstall(res.returnCode, res.uid); 10246 } 10247 10248 // A restore should be performed at this point if (a) the install 10249 // succeeded, (b) the operation is not an update, and (c) the new 10250 // package has not opted out of backup participation. 10251 final boolean update = res.removedInfo.removedPackage != null; 10252 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10253 boolean doRestore = !update 10254 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10255 10256 // Set up the post-install work request bookkeeping. This will be used 10257 // and cleaned up by the post-install event handling regardless of whether 10258 // there's a restore pass performed. Token values are >= 1. 10259 int token; 10260 if (mNextInstallToken < 0) mNextInstallToken = 1; 10261 token = mNextInstallToken++; 10262 10263 PostInstallData data = new PostInstallData(args, res); 10264 mRunningInstalls.put(token, data); 10265 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10266 10267 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10268 // Pass responsibility to the Backup Manager. It will perform a 10269 // restore if appropriate, then pass responsibility back to the 10270 // Package Manager to run the post-install observer callbacks 10271 // and broadcasts. 10272 IBackupManager bm = IBackupManager.Stub.asInterface( 10273 ServiceManager.getService(Context.BACKUP_SERVICE)); 10274 if (bm != null) { 10275 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10276 + " to BM for possible restore"); 10277 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10278 try { 10279 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10280 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10281 } else { 10282 doRestore = false; 10283 } 10284 } catch (RemoteException e) { 10285 // can't happen; the backup manager is local 10286 } catch (Exception e) { 10287 Slog.e(TAG, "Exception trying to enqueue restore", e); 10288 doRestore = false; 10289 } finally { 10290 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10291 } 10292 } else { 10293 Slog.e(TAG, "Backup Manager not found!"); 10294 doRestore = false; 10295 } 10296 } 10297 10298 if (!doRestore) { 10299 // No restore possible, or the Backup Manager was mysteriously not 10300 // available -- just fire the post-install work request directly. 10301 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10302 10303 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10304 10305 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10306 mHandler.sendMessage(msg); 10307 } 10308 } 10309 }); 10310 } 10311 10312 private abstract class HandlerParams { 10313 private static final int MAX_RETRIES = 4; 10314 10315 /** 10316 * Number of times startCopy() has been attempted and had a non-fatal 10317 * error. 10318 */ 10319 private int mRetries = 0; 10320 10321 /** User handle for the user requesting the information or installation. */ 10322 private final UserHandle mUser; 10323 10324 HandlerParams(UserHandle user) { 10325 mUser = user; 10326 } 10327 10328 UserHandle getUser() { 10329 return mUser; 10330 } 10331 10332 final boolean startCopy() { 10333 boolean res; 10334 try { 10335 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10336 10337 if (++mRetries > MAX_RETRIES) { 10338 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10339 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10340 handleServiceError(); 10341 return false; 10342 } else { 10343 handleStartCopy(); 10344 res = true; 10345 } 10346 } catch (RemoteException e) { 10347 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10348 mHandler.sendEmptyMessage(MCS_RECONNECT); 10349 res = false; 10350 } 10351 handleReturnCode(); 10352 return res; 10353 } 10354 10355 final void serviceError() { 10356 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10357 handleServiceError(); 10358 handleReturnCode(); 10359 } 10360 10361 abstract void handleStartCopy() throws RemoteException; 10362 abstract void handleServiceError(); 10363 abstract void handleReturnCode(); 10364 } 10365 10366 class MeasureParams extends HandlerParams { 10367 private final PackageStats mStats; 10368 private boolean mSuccess; 10369 10370 private final IPackageStatsObserver mObserver; 10371 10372 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10373 super(new UserHandle(stats.userHandle)); 10374 mObserver = observer; 10375 mStats = stats; 10376 } 10377 10378 @Override 10379 public String toString() { 10380 return "MeasureParams{" 10381 + Integer.toHexString(System.identityHashCode(this)) 10382 + " " + mStats.packageName + "}"; 10383 } 10384 10385 @Override 10386 void handleStartCopy() throws RemoteException { 10387 synchronized (mInstallLock) { 10388 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10389 } 10390 10391 if (mSuccess) { 10392 final boolean mounted; 10393 if (Environment.isExternalStorageEmulated()) { 10394 mounted = true; 10395 } else { 10396 final String status = Environment.getExternalStorageState(); 10397 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10398 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10399 } 10400 10401 if (mounted) { 10402 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10403 10404 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10405 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10406 10407 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10408 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10409 10410 // Always subtract cache size, since it's a subdirectory 10411 mStats.externalDataSize -= mStats.externalCacheSize; 10412 10413 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10414 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10415 10416 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10417 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10418 } 10419 } 10420 } 10421 10422 @Override 10423 void handleReturnCode() { 10424 if (mObserver != null) { 10425 try { 10426 mObserver.onGetStatsCompleted(mStats, mSuccess); 10427 } catch (RemoteException e) { 10428 Slog.i(TAG, "Observer no longer exists."); 10429 } 10430 } 10431 } 10432 10433 @Override 10434 void handleServiceError() { 10435 Slog.e(TAG, "Could not measure application " + mStats.packageName 10436 + " external storage"); 10437 } 10438 } 10439 10440 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10441 throws RemoteException { 10442 long result = 0; 10443 for (File path : paths) { 10444 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10445 } 10446 return result; 10447 } 10448 10449 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10450 for (File path : paths) { 10451 try { 10452 mcs.clearDirectory(path.getAbsolutePath()); 10453 } catch (RemoteException e) { 10454 } 10455 } 10456 } 10457 10458 static class OriginInfo { 10459 /** 10460 * Location where install is coming from, before it has been 10461 * copied/renamed into place. This could be a single monolithic APK 10462 * file, or a cluster directory. This location may be untrusted. 10463 */ 10464 final File file; 10465 final String cid; 10466 10467 /** 10468 * Flag indicating that {@link #file} or {@link #cid} has already been 10469 * staged, meaning downstream users don't need to defensively copy the 10470 * contents. 10471 */ 10472 final boolean staged; 10473 10474 /** 10475 * Flag indicating that {@link #file} or {@link #cid} is an already 10476 * installed app that is being moved. 10477 */ 10478 final boolean existing; 10479 10480 final String resolvedPath; 10481 final File resolvedFile; 10482 10483 static OriginInfo fromNothing() { 10484 return new OriginInfo(null, null, false, false); 10485 } 10486 10487 static OriginInfo fromUntrustedFile(File file) { 10488 return new OriginInfo(file, null, false, false); 10489 } 10490 10491 static OriginInfo fromExistingFile(File file) { 10492 return new OriginInfo(file, null, false, true); 10493 } 10494 10495 static OriginInfo fromStagedFile(File file) { 10496 return new OriginInfo(file, null, true, false); 10497 } 10498 10499 static OriginInfo fromStagedContainer(String cid) { 10500 return new OriginInfo(null, cid, true, false); 10501 } 10502 10503 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10504 this.file = file; 10505 this.cid = cid; 10506 this.staged = staged; 10507 this.existing = existing; 10508 10509 if (cid != null) { 10510 resolvedPath = PackageHelper.getSdDir(cid); 10511 resolvedFile = new File(resolvedPath); 10512 } else if (file != null) { 10513 resolvedPath = file.getAbsolutePath(); 10514 resolvedFile = file; 10515 } else { 10516 resolvedPath = null; 10517 resolvedFile = null; 10518 } 10519 } 10520 } 10521 10522 class MoveInfo { 10523 final int moveId; 10524 final String fromUuid; 10525 final String toUuid; 10526 final String packageName; 10527 final String dataAppName; 10528 final int appId; 10529 final String seinfo; 10530 10531 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10532 String dataAppName, int appId, String seinfo) { 10533 this.moveId = moveId; 10534 this.fromUuid = fromUuid; 10535 this.toUuid = toUuid; 10536 this.packageName = packageName; 10537 this.dataAppName = dataAppName; 10538 this.appId = appId; 10539 this.seinfo = seinfo; 10540 } 10541 } 10542 10543 class InstallParams extends HandlerParams { 10544 final OriginInfo origin; 10545 final MoveInfo move; 10546 final IPackageInstallObserver2 observer; 10547 int installFlags; 10548 final String installerPackageName; 10549 final String volumeUuid; 10550 final VerificationParams verificationParams; 10551 private InstallArgs mArgs; 10552 private int mRet; 10553 final String packageAbiOverride; 10554 final String[] grantedRuntimePermissions; 10555 10556 10557 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10558 int installFlags, String installerPackageName, String volumeUuid, 10559 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10560 String[] grantedPermissions) { 10561 super(user); 10562 this.origin = origin; 10563 this.move = move; 10564 this.observer = observer; 10565 this.installFlags = installFlags; 10566 this.installerPackageName = installerPackageName; 10567 this.volumeUuid = volumeUuid; 10568 this.verificationParams = verificationParams; 10569 this.packageAbiOverride = packageAbiOverride; 10570 this.grantedRuntimePermissions = grantedPermissions; 10571 } 10572 10573 @Override 10574 public String toString() { 10575 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10576 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10577 } 10578 10579 public ManifestDigest getManifestDigest() { 10580 if (verificationParams == null) { 10581 return null; 10582 } 10583 return verificationParams.getManifestDigest(); 10584 } 10585 10586 private int installLocationPolicy(PackageInfoLite pkgLite) { 10587 String packageName = pkgLite.packageName; 10588 int installLocation = pkgLite.installLocation; 10589 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10590 // reader 10591 synchronized (mPackages) { 10592 PackageParser.Package pkg = mPackages.get(packageName); 10593 if (pkg != null) { 10594 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10595 // Check for downgrading. 10596 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10597 try { 10598 checkDowngrade(pkg, pkgLite); 10599 } catch (PackageManagerException e) { 10600 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10601 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10602 } 10603 } 10604 // Check for updated system application. 10605 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10606 if (onSd) { 10607 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10608 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10609 } 10610 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10611 } else { 10612 if (onSd) { 10613 // Install flag overrides everything. 10614 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10615 } 10616 // If current upgrade specifies particular preference 10617 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10618 // Application explicitly specified internal. 10619 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10620 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10621 // App explictly prefers external. Let policy decide 10622 } else { 10623 // Prefer previous location 10624 if (isExternal(pkg)) { 10625 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10626 } 10627 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10628 } 10629 } 10630 } else { 10631 // Invalid install. Return error code 10632 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10633 } 10634 } 10635 } 10636 // All the special cases have been taken care of. 10637 // Return result based on recommended install location. 10638 if (onSd) { 10639 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10640 } 10641 return pkgLite.recommendedInstallLocation; 10642 } 10643 10644 /* 10645 * Invoke remote method to get package information and install 10646 * location values. Override install location based on default 10647 * policy if needed and then create install arguments based 10648 * on the install location. 10649 */ 10650 public void handleStartCopy() throws RemoteException { 10651 int ret = PackageManager.INSTALL_SUCCEEDED; 10652 10653 // If we're already staged, we've firmly committed to an install location 10654 if (origin.staged) { 10655 if (origin.file != null) { 10656 installFlags |= PackageManager.INSTALL_INTERNAL; 10657 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10658 } else if (origin.cid != null) { 10659 installFlags |= PackageManager.INSTALL_EXTERNAL; 10660 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10661 } else { 10662 throw new IllegalStateException("Invalid stage location"); 10663 } 10664 } 10665 10666 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10667 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10668 PackageInfoLite pkgLite = null; 10669 10670 if (onInt && onSd) { 10671 // Check if both bits are set. 10672 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10673 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10674 } else { 10675 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10676 packageAbiOverride); 10677 10678 /* 10679 * If we have too little free space, try to free cache 10680 * before giving up. 10681 */ 10682 if (!origin.staged && pkgLite.recommendedInstallLocation 10683 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10684 // TODO: focus freeing disk space on the target device 10685 final StorageManager storage = StorageManager.from(mContext); 10686 final long lowThreshold = storage.getStorageLowBytes( 10687 Environment.getDataDirectory()); 10688 10689 final long sizeBytes = mContainerService.calculateInstalledSize( 10690 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10691 10692 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10693 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10694 installFlags, packageAbiOverride); 10695 } 10696 10697 /* 10698 * The cache free must have deleted the file we 10699 * downloaded to install. 10700 * 10701 * TODO: fix the "freeCache" call to not delete 10702 * the file we care about. 10703 */ 10704 if (pkgLite.recommendedInstallLocation 10705 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10706 pkgLite.recommendedInstallLocation 10707 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10708 } 10709 } 10710 } 10711 10712 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10713 int loc = pkgLite.recommendedInstallLocation; 10714 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10715 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10716 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10717 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10718 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10719 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10720 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10721 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10722 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10723 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10724 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10725 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10726 } else { 10727 // Override with defaults if needed. 10728 loc = installLocationPolicy(pkgLite); 10729 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10730 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10731 } else if (!onSd && !onInt) { 10732 // Override install location with flags 10733 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10734 // Set the flag to install on external media. 10735 installFlags |= PackageManager.INSTALL_EXTERNAL; 10736 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10737 } else { 10738 // Make sure the flag for installing on external 10739 // media is unset 10740 installFlags |= PackageManager.INSTALL_INTERNAL; 10741 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10742 } 10743 } 10744 } 10745 } 10746 10747 final InstallArgs args = createInstallArgs(this); 10748 mArgs = args; 10749 10750 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10751 /* 10752 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10753 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10754 */ 10755 int userIdentifier = getUser().getIdentifier(); 10756 if (userIdentifier == UserHandle.USER_ALL 10757 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10758 userIdentifier = UserHandle.USER_OWNER; 10759 } 10760 10761 /* 10762 * Determine if we have any installed package verifiers. If we 10763 * do, then we'll defer to them to verify the packages. 10764 */ 10765 final int requiredUid = mRequiredVerifierPackage == null ? -1 10766 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10767 if (!origin.existing && requiredUid != -1 10768 && isVerificationEnabled(userIdentifier, installFlags)) { 10769 final Intent verification = new Intent( 10770 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10771 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10772 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10773 PACKAGE_MIME_TYPE); 10774 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10775 10776 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10777 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10778 0 /* TODO: Which userId? */); 10779 10780 if (DEBUG_VERIFY) { 10781 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10782 + verification.toString() + " with " + pkgLite.verifiers.length 10783 + " optional verifiers"); 10784 } 10785 10786 final int verificationId = mPendingVerificationToken++; 10787 10788 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10789 10790 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10791 installerPackageName); 10792 10793 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10794 installFlags); 10795 10796 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10797 pkgLite.packageName); 10798 10799 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10800 pkgLite.versionCode); 10801 10802 if (verificationParams != null) { 10803 if (verificationParams.getVerificationURI() != null) { 10804 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10805 verificationParams.getVerificationURI()); 10806 } 10807 if (verificationParams.getOriginatingURI() != null) { 10808 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10809 verificationParams.getOriginatingURI()); 10810 } 10811 if (verificationParams.getReferrer() != null) { 10812 verification.putExtra(Intent.EXTRA_REFERRER, 10813 verificationParams.getReferrer()); 10814 } 10815 if (verificationParams.getOriginatingUid() >= 0) { 10816 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10817 verificationParams.getOriginatingUid()); 10818 } 10819 if (verificationParams.getInstallerUid() >= 0) { 10820 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10821 verificationParams.getInstallerUid()); 10822 } 10823 } 10824 10825 final PackageVerificationState verificationState = new PackageVerificationState( 10826 requiredUid, args); 10827 10828 mPendingVerification.append(verificationId, verificationState); 10829 10830 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10831 receivers, verificationState); 10832 10833 // Apps installed for "all" users use the device owner to verify the app 10834 UserHandle verifierUser = getUser(); 10835 if (verifierUser == UserHandle.ALL) { 10836 verifierUser = UserHandle.OWNER; 10837 } 10838 10839 /* 10840 * If any sufficient verifiers were listed in the package 10841 * manifest, attempt to ask them. 10842 */ 10843 if (sufficientVerifiers != null) { 10844 final int N = sufficientVerifiers.size(); 10845 if (N == 0) { 10846 Slog.i(TAG, "Additional verifiers required, but none installed."); 10847 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10848 } else { 10849 for (int i = 0; i < N; i++) { 10850 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10851 10852 final Intent sufficientIntent = new Intent(verification); 10853 sufficientIntent.setComponent(verifierComponent); 10854 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10855 } 10856 } 10857 } 10858 10859 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10860 mRequiredVerifierPackage, receivers); 10861 if (ret == PackageManager.INSTALL_SUCCEEDED 10862 && mRequiredVerifierPackage != null) { 10863 Trace.asyncTraceBegin( 10864 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 10865 /* 10866 * Send the intent to the required verification agent, 10867 * but only start the verification timeout after the 10868 * target BroadcastReceivers have run. 10869 */ 10870 verification.setComponent(requiredVerifierComponent); 10871 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10872 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10873 new BroadcastReceiver() { 10874 @Override 10875 public void onReceive(Context context, Intent intent) { 10876 final Message msg = mHandler 10877 .obtainMessage(CHECK_PENDING_VERIFICATION); 10878 msg.arg1 = verificationId; 10879 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10880 } 10881 }, null, 0, null, null); 10882 10883 /* 10884 * We don't want the copy to proceed until verification 10885 * succeeds, so null out this field. 10886 */ 10887 mArgs = null; 10888 } 10889 } else { 10890 /* 10891 * No package verification is enabled, so immediately start 10892 * the remote call to initiate copy using temporary file. 10893 */ 10894 ret = args.copyApk(mContainerService, true); 10895 } 10896 } 10897 10898 mRet = ret; 10899 } 10900 10901 @Override 10902 void handleReturnCode() { 10903 // If mArgs is null, then MCS couldn't be reached. When it 10904 // reconnects, it will try again to install. At that point, this 10905 // will succeed. 10906 if (mArgs != null) { 10907 processPendingInstall(mArgs, mRet); 10908 } 10909 } 10910 10911 @Override 10912 void handleServiceError() { 10913 mArgs = createInstallArgs(this); 10914 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10915 } 10916 10917 public boolean isForwardLocked() { 10918 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10919 } 10920 } 10921 10922 /** 10923 * Used during creation of InstallArgs 10924 * 10925 * @param installFlags package installation flags 10926 * @return true if should be installed on external storage 10927 */ 10928 private static boolean installOnExternalAsec(int installFlags) { 10929 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10930 return false; 10931 } 10932 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10933 return true; 10934 } 10935 return false; 10936 } 10937 10938 /** 10939 * Used during creation of InstallArgs 10940 * 10941 * @param installFlags package installation flags 10942 * @return true if should be installed as forward locked 10943 */ 10944 private static boolean installForwardLocked(int installFlags) { 10945 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10946 } 10947 10948 private InstallArgs createInstallArgs(InstallParams params) { 10949 if (params.move != null) { 10950 return new MoveInstallArgs(params); 10951 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10952 return new AsecInstallArgs(params); 10953 } else { 10954 return new FileInstallArgs(params); 10955 } 10956 } 10957 10958 /** 10959 * Create args that describe an existing installed package. Typically used 10960 * when cleaning up old installs, or used as a move source. 10961 */ 10962 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10963 String resourcePath, String[] instructionSets) { 10964 final boolean isInAsec; 10965 if (installOnExternalAsec(installFlags)) { 10966 /* Apps on SD card are always in ASEC containers. */ 10967 isInAsec = true; 10968 } else if (installForwardLocked(installFlags) 10969 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10970 /* 10971 * Forward-locked apps are only in ASEC containers if they're the 10972 * new style 10973 */ 10974 isInAsec = true; 10975 } else { 10976 isInAsec = false; 10977 } 10978 10979 if (isInAsec) { 10980 return new AsecInstallArgs(codePath, instructionSets, 10981 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10982 } else { 10983 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10984 } 10985 } 10986 10987 static abstract class InstallArgs { 10988 /** @see InstallParams#origin */ 10989 final OriginInfo origin; 10990 /** @see InstallParams#move */ 10991 final MoveInfo move; 10992 10993 final IPackageInstallObserver2 observer; 10994 // Always refers to PackageManager flags only 10995 final int installFlags; 10996 final String installerPackageName; 10997 final String volumeUuid; 10998 final ManifestDigest manifestDigest; 10999 final UserHandle user; 11000 final String abiOverride; 11001 final String[] installGrantPermissions; 11002 11003 // The list of instruction sets supported by this app. This is currently 11004 // only used during the rmdex() phase to clean up resources. We can get rid of this 11005 // if we move dex files under the common app path. 11006 /* nullable */ String[] instructionSets; 11007 11008 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11009 int installFlags, String installerPackageName, String volumeUuid, 11010 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11011 String abiOverride, String[] installGrantPermissions) { 11012 this.origin = origin; 11013 this.move = move; 11014 this.installFlags = installFlags; 11015 this.observer = observer; 11016 this.installerPackageName = installerPackageName; 11017 this.volumeUuid = volumeUuid; 11018 this.manifestDigest = manifestDigest; 11019 this.user = user; 11020 this.instructionSets = instructionSets; 11021 this.abiOverride = abiOverride; 11022 this.installGrantPermissions = installGrantPermissions; 11023 } 11024 11025 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11026 abstract int doPreInstall(int status); 11027 11028 /** 11029 * Rename package into final resting place. All paths on the given 11030 * scanned package should be updated to reflect the rename. 11031 */ 11032 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11033 abstract int doPostInstall(int status, int uid); 11034 11035 /** @see PackageSettingBase#codePathString */ 11036 abstract String getCodePath(); 11037 /** @see PackageSettingBase#resourcePathString */ 11038 abstract String getResourcePath(); 11039 11040 // Need installer lock especially for dex file removal. 11041 abstract void cleanUpResourcesLI(); 11042 abstract boolean doPostDeleteLI(boolean delete); 11043 11044 /** 11045 * Called before the source arguments are copied. This is used mostly 11046 * for MoveParams when it needs to read the source file to put it in the 11047 * destination. 11048 */ 11049 int doPreCopy() { 11050 return PackageManager.INSTALL_SUCCEEDED; 11051 } 11052 11053 /** 11054 * Called after the source arguments are copied. This is used mostly for 11055 * MoveParams when it needs to read the source file to put it in the 11056 * destination. 11057 * 11058 * @return 11059 */ 11060 int doPostCopy(int uid) { 11061 return PackageManager.INSTALL_SUCCEEDED; 11062 } 11063 11064 protected boolean isFwdLocked() { 11065 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11066 } 11067 11068 protected boolean isExternalAsec() { 11069 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11070 } 11071 11072 UserHandle getUser() { 11073 return user; 11074 } 11075 } 11076 11077 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11078 if (!allCodePaths.isEmpty()) { 11079 if (instructionSets == null) { 11080 throw new IllegalStateException("instructionSet == null"); 11081 } 11082 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11083 for (String codePath : allCodePaths) { 11084 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11085 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11086 if (retCode < 0) { 11087 Slog.w(TAG, "Couldn't remove dex file for package: " 11088 + " at location " + codePath + ", retcode=" + retCode); 11089 // we don't consider this to be a failure of the core package deletion 11090 } 11091 } 11092 } 11093 } 11094 } 11095 11096 /** 11097 * Logic to handle installation of non-ASEC applications, including copying 11098 * and renaming logic. 11099 */ 11100 class FileInstallArgs extends InstallArgs { 11101 private File codeFile; 11102 private File resourceFile; 11103 11104 // Example topology: 11105 // /data/app/com.example/base.apk 11106 // /data/app/com.example/split_foo.apk 11107 // /data/app/com.example/lib/arm/libfoo.so 11108 // /data/app/com.example/lib/arm64/libfoo.so 11109 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11110 11111 /** New install */ 11112 FileInstallArgs(InstallParams params) { 11113 super(params.origin, params.move, params.observer, params.installFlags, 11114 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11115 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11116 params.grantedRuntimePermissions); 11117 if (isFwdLocked()) { 11118 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11119 } 11120 } 11121 11122 /** Existing install */ 11123 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11124 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11125 null, null); 11126 this.codeFile = (codePath != null) ? new File(codePath) : null; 11127 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11128 } 11129 11130 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11131 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11132 try { 11133 return doCopyApk(imcs, temp); 11134 } finally { 11135 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11136 } 11137 } 11138 11139 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11140 if (origin.staged) { 11141 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11142 codeFile = origin.file; 11143 resourceFile = origin.file; 11144 return PackageManager.INSTALL_SUCCEEDED; 11145 } 11146 11147 try { 11148 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11149 codeFile = tempDir; 11150 resourceFile = tempDir; 11151 } catch (IOException e) { 11152 Slog.w(TAG, "Failed to create copy file: " + e); 11153 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11154 } 11155 11156 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11157 @Override 11158 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11159 if (!FileUtils.isValidExtFilename(name)) { 11160 throw new IllegalArgumentException("Invalid filename: " + name); 11161 } 11162 try { 11163 final File file = new File(codeFile, name); 11164 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11165 O_RDWR | O_CREAT, 0644); 11166 Os.chmod(file.getAbsolutePath(), 0644); 11167 return new ParcelFileDescriptor(fd); 11168 } catch (ErrnoException e) { 11169 throw new RemoteException("Failed to open: " + e.getMessage()); 11170 } 11171 } 11172 }; 11173 11174 int ret = PackageManager.INSTALL_SUCCEEDED; 11175 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11176 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11177 Slog.e(TAG, "Failed to copy package"); 11178 return ret; 11179 } 11180 11181 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11182 NativeLibraryHelper.Handle handle = null; 11183 try { 11184 handle = NativeLibraryHelper.Handle.create(codeFile); 11185 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11186 abiOverride); 11187 } catch (IOException e) { 11188 Slog.e(TAG, "Copying native libraries failed", e); 11189 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11190 } finally { 11191 IoUtils.closeQuietly(handle); 11192 } 11193 11194 return ret; 11195 } 11196 11197 int doPreInstall(int status) { 11198 if (status != PackageManager.INSTALL_SUCCEEDED) { 11199 cleanUp(); 11200 } 11201 return status; 11202 } 11203 11204 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11205 if (status != PackageManager.INSTALL_SUCCEEDED) { 11206 cleanUp(); 11207 return false; 11208 } 11209 11210 final File targetDir = codeFile.getParentFile(); 11211 final File beforeCodeFile = codeFile; 11212 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11213 11214 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11215 try { 11216 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11217 } catch (ErrnoException e) { 11218 Slog.w(TAG, "Failed to rename", e); 11219 return false; 11220 } 11221 11222 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11223 Slog.w(TAG, "Failed to restorecon"); 11224 return false; 11225 } 11226 11227 // Reflect the rename internally 11228 codeFile = afterCodeFile; 11229 resourceFile = afterCodeFile; 11230 11231 // Reflect the rename in scanned details 11232 pkg.codePath = afterCodeFile.getAbsolutePath(); 11233 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11234 pkg.baseCodePath); 11235 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11236 pkg.splitCodePaths); 11237 11238 // Reflect the rename in app info 11239 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11240 pkg.applicationInfo.setCodePath(pkg.codePath); 11241 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11242 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11243 pkg.applicationInfo.setResourcePath(pkg.codePath); 11244 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11245 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11246 11247 return true; 11248 } 11249 11250 int doPostInstall(int status, int uid) { 11251 if (status != PackageManager.INSTALL_SUCCEEDED) { 11252 cleanUp(); 11253 } 11254 return status; 11255 } 11256 11257 @Override 11258 String getCodePath() { 11259 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11260 } 11261 11262 @Override 11263 String getResourcePath() { 11264 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11265 } 11266 11267 private boolean cleanUp() { 11268 if (codeFile == null || !codeFile.exists()) { 11269 return false; 11270 } 11271 11272 if (codeFile.isDirectory()) { 11273 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11274 } else { 11275 codeFile.delete(); 11276 } 11277 11278 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11279 resourceFile.delete(); 11280 } 11281 11282 return true; 11283 } 11284 11285 void cleanUpResourcesLI() { 11286 // Try enumerating all code paths before deleting 11287 List<String> allCodePaths = Collections.EMPTY_LIST; 11288 if (codeFile != null && codeFile.exists()) { 11289 try { 11290 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11291 allCodePaths = pkg.getAllCodePaths(); 11292 } catch (PackageParserException e) { 11293 // Ignored; we tried our best 11294 } 11295 } 11296 11297 cleanUp(); 11298 removeDexFiles(allCodePaths, instructionSets); 11299 } 11300 11301 boolean doPostDeleteLI(boolean delete) { 11302 // XXX err, shouldn't we respect the delete flag? 11303 cleanUpResourcesLI(); 11304 return true; 11305 } 11306 } 11307 11308 private boolean isAsecExternal(String cid) { 11309 final String asecPath = PackageHelper.getSdFilesystem(cid); 11310 return !asecPath.startsWith(mAsecInternalPath); 11311 } 11312 11313 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11314 PackageManagerException { 11315 if (copyRet < 0) { 11316 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11317 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11318 throw new PackageManagerException(copyRet, message); 11319 } 11320 } 11321 } 11322 11323 /** 11324 * Extract the MountService "container ID" from the full code path of an 11325 * .apk. 11326 */ 11327 static String cidFromCodePath(String fullCodePath) { 11328 int eidx = fullCodePath.lastIndexOf("/"); 11329 String subStr1 = fullCodePath.substring(0, eidx); 11330 int sidx = subStr1.lastIndexOf("/"); 11331 return subStr1.substring(sidx+1, eidx); 11332 } 11333 11334 /** 11335 * Logic to handle installation of ASEC applications, including copying and 11336 * renaming logic. 11337 */ 11338 class AsecInstallArgs extends InstallArgs { 11339 static final String RES_FILE_NAME = "pkg.apk"; 11340 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11341 11342 String cid; 11343 String packagePath; 11344 String resourcePath; 11345 11346 /** New install */ 11347 AsecInstallArgs(InstallParams params) { 11348 super(params.origin, params.move, params.observer, params.installFlags, 11349 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11350 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11351 params.grantedRuntimePermissions); 11352 } 11353 11354 /** Existing install */ 11355 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11356 boolean isExternal, boolean isForwardLocked) { 11357 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11358 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11359 instructionSets, null, null); 11360 // Hackily pretend we're still looking at a full code path 11361 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11362 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11363 } 11364 11365 // Extract cid from fullCodePath 11366 int eidx = fullCodePath.lastIndexOf("/"); 11367 String subStr1 = fullCodePath.substring(0, eidx); 11368 int sidx = subStr1.lastIndexOf("/"); 11369 cid = subStr1.substring(sidx+1, eidx); 11370 setMountPath(subStr1); 11371 } 11372 11373 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11374 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11375 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11376 instructionSets, null, null); 11377 this.cid = cid; 11378 setMountPath(PackageHelper.getSdDir(cid)); 11379 } 11380 11381 void createCopyFile() { 11382 cid = mInstallerService.allocateExternalStageCidLegacy(); 11383 } 11384 11385 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11386 if (origin.staged) { 11387 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11388 cid = origin.cid; 11389 setMountPath(PackageHelper.getSdDir(cid)); 11390 return PackageManager.INSTALL_SUCCEEDED; 11391 } 11392 11393 if (temp) { 11394 createCopyFile(); 11395 } else { 11396 /* 11397 * Pre-emptively destroy the container since it's destroyed if 11398 * copying fails due to it existing anyway. 11399 */ 11400 PackageHelper.destroySdDir(cid); 11401 } 11402 11403 final String newMountPath = imcs.copyPackageToContainer( 11404 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11405 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11406 11407 if (newMountPath != null) { 11408 setMountPath(newMountPath); 11409 return PackageManager.INSTALL_SUCCEEDED; 11410 } else { 11411 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11412 } 11413 } 11414 11415 @Override 11416 String getCodePath() { 11417 return packagePath; 11418 } 11419 11420 @Override 11421 String getResourcePath() { 11422 return resourcePath; 11423 } 11424 11425 int doPreInstall(int status) { 11426 if (status != PackageManager.INSTALL_SUCCEEDED) { 11427 // Destroy container 11428 PackageHelper.destroySdDir(cid); 11429 } else { 11430 boolean mounted = PackageHelper.isContainerMounted(cid); 11431 if (!mounted) { 11432 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11433 Process.SYSTEM_UID); 11434 if (newMountPath != null) { 11435 setMountPath(newMountPath); 11436 } else { 11437 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11438 } 11439 } 11440 } 11441 return status; 11442 } 11443 11444 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11445 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11446 String newMountPath = null; 11447 if (PackageHelper.isContainerMounted(cid)) { 11448 // Unmount the container 11449 if (!PackageHelper.unMountSdDir(cid)) { 11450 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11451 return false; 11452 } 11453 } 11454 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11455 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11456 " which might be stale. Will try to clean up."); 11457 // Clean up the stale container and proceed to recreate. 11458 if (!PackageHelper.destroySdDir(newCacheId)) { 11459 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11460 return false; 11461 } 11462 // Successfully cleaned up stale container. Try to rename again. 11463 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11464 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11465 + " inspite of cleaning it up."); 11466 return false; 11467 } 11468 } 11469 if (!PackageHelper.isContainerMounted(newCacheId)) { 11470 Slog.w(TAG, "Mounting container " + newCacheId); 11471 newMountPath = PackageHelper.mountSdDir(newCacheId, 11472 getEncryptKey(), Process.SYSTEM_UID); 11473 } else { 11474 newMountPath = PackageHelper.getSdDir(newCacheId); 11475 } 11476 if (newMountPath == null) { 11477 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11478 return false; 11479 } 11480 Log.i(TAG, "Succesfully renamed " + cid + 11481 " to " + newCacheId + 11482 " at new path: " + newMountPath); 11483 cid = newCacheId; 11484 11485 final File beforeCodeFile = new File(packagePath); 11486 setMountPath(newMountPath); 11487 final File afterCodeFile = new File(packagePath); 11488 11489 // Reflect the rename in scanned details 11490 pkg.codePath = afterCodeFile.getAbsolutePath(); 11491 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11492 pkg.baseCodePath); 11493 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11494 pkg.splitCodePaths); 11495 11496 // Reflect the rename in app info 11497 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11498 pkg.applicationInfo.setCodePath(pkg.codePath); 11499 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11500 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11501 pkg.applicationInfo.setResourcePath(pkg.codePath); 11502 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11503 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11504 11505 return true; 11506 } 11507 11508 private void setMountPath(String mountPath) { 11509 final File mountFile = new File(mountPath); 11510 11511 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11512 if (monolithicFile.exists()) { 11513 packagePath = monolithicFile.getAbsolutePath(); 11514 if (isFwdLocked()) { 11515 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11516 } else { 11517 resourcePath = packagePath; 11518 } 11519 } else { 11520 packagePath = mountFile.getAbsolutePath(); 11521 resourcePath = packagePath; 11522 } 11523 } 11524 11525 int doPostInstall(int status, int uid) { 11526 if (status != PackageManager.INSTALL_SUCCEEDED) { 11527 cleanUp(); 11528 } else { 11529 final int groupOwner; 11530 final String protectedFile; 11531 if (isFwdLocked()) { 11532 groupOwner = UserHandle.getSharedAppGid(uid); 11533 protectedFile = RES_FILE_NAME; 11534 } else { 11535 groupOwner = -1; 11536 protectedFile = null; 11537 } 11538 11539 if (uid < Process.FIRST_APPLICATION_UID 11540 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11541 Slog.e(TAG, "Failed to finalize " + cid); 11542 PackageHelper.destroySdDir(cid); 11543 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11544 } 11545 11546 boolean mounted = PackageHelper.isContainerMounted(cid); 11547 if (!mounted) { 11548 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11549 } 11550 } 11551 return status; 11552 } 11553 11554 private void cleanUp() { 11555 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11556 11557 // Destroy secure container 11558 PackageHelper.destroySdDir(cid); 11559 } 11560 11561 private List<String> getAllCodePaths() { 11562 final File codeFile = new File(getCodePath()); 11563 if (codeFile != null && codeFile.exists()) { 11564 try { 11565 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11566 return pkg.getAllCodePaths(); 11567 } catch (PackageParserException e) { 11568 // Ignored; we tried our best 11569 } 11570 } 11571 return Collections.EMPTY_LIST; 11572 } 11573 11574 void cleanUpResourcesLI() { 11575 // Enumerate all code paths before deleting 11576 cleanUpResourcesLI(getAllCodePaths()); 11577 } 11578 11579 private void cleanUpResourcesLI(List<String> allCodePaths) { 11580 cleanUp(); 11581 removeDexFiles(allCodePaths, instructionSets); 11582 } 11583 11584 String getPackageName() { 11585 return getAsecPackageName(cid); 11586 } 11587 11588 boolean doPostDeleteLI(boolean delete) { 11589 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11590 final List<String> allCodePaths = getAllCodePaths(); 11591 boolean mounted = PackageHelper.isContainerMounted(cid); 11592 if (mounted) { 11593 // Unmount first 11594 if (PackageHelper.unMountSdDir(cid)) { 11595 mounted = false; 11596 } 11597 } 11598 if (!mounted && delete) { 11599 cleanUpResourcesLI(allCodePaths); 11600 } 11601 return !mounted; 11602 } 11603 11604 @Override 11605 int doPreCopy() { 11606 if (isFwdLocked()) { 11607 if (!PackageHelper.fixSdPermissions(cid, 11608 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11609 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11610 } 11611 } 11612 11613 return PackageManager.INSTALL_SUCCEEDED; 11614 } 11615 11616 @Override 11617 int doPostCopy(int uid) { 11618 if (isFwdLocked()) { 11619 if (uid < Process.FIRST_APPLICATION_UID 11620 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11621 RES_FILE_NAME)) { 11622 Slog.e(TAG, "Failed to finalize " + cid); 11623 PackageHelper.destroySdDir(cid); 11624 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11625 } 11626 } 11627 11628 return PackageManager.INSTALL_SUCCEEDED; 11629 } 11630 } 11631 11632 /** 11633 * Logic to handle movement of existing installed applications. 11634 */ 11635 class MoveInstallArgs extends InstallArgs { 11636 private File codeFile; 11637 private File resourceFile; 11638 11639 /** New install */ 11640 MoveInstallArgs(InstallParams params) { 11641 super(params.origin, params.move, params.observer, params.installFlags, 11642 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11643 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11644 params.grantedRuntimePermissions); 11645 } 11646 11647 int copyApk(IMediaContainerService imcs, boolean temp) { 11648 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11649 + move.fromUuid + " to " + move.toUuid); 11650 synchronized (mInstaller) { 11651 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11652 move.dataAppName, move.appId, move.seinfo) != 0) { 11653 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11654 } 11655 } 11656 11657 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11658 resourceFile = codeFile; 11659 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11660 11661 return PackageManager.INSTALL_SUCCEEDED; 11662 } 11663 11664 int doPreInstall(int status) { 11665 if (status != PackageManager.INSTALL_SUCCEEDED) { 11666 cleanUp(move.toUuid); 11667 } 11668 return status; 11669 } 11670 11671 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11672 if (status != PackageManager.INSTALL_SUCCEEDED) { 11673 cleanUp(move.toUuid); 11674 return false; 11675 } 11676 11677 // Reflect the move in app info 11678 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11679 pkg.applicationInfo.setCodePath(pkg.codePath); 11680 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11681 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11682 pkg.applicationInfo.setResourcePath(pkg.codePath); 11683 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11684 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11685 11686 return true; 11687 } 11688 11689 int doPostInstall(int status, int uid) { 11690 if (status == PackageManager.INSTALL_SUCCEEDED) { 11691 cleanUp(move.fromUuid); 11692 } else { 11693 cleanUp(move.toUuid); 11694 } 11695 return status; 11696 } 11697 11698 @Override 11699 String getCodePath() { 11700 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11701 } 11702 11703 @Override 11704 String getResourcePath() { 11705 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11706 } 11707 11708 private boolean cleanUp(String volumeUuid) { 11709 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11710 move.dataAppName); 11711 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11712 synchronized (mInstallLock) { 11713 // Clean up both app data and code 11714 removeDataDirsLI(volumeUuid, move.packageName); 11715 if (codeFile.isDirectory()) { 11716 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11717 } else { 11718 codeFile.delete(); 11719 } 11720 } 11721 return true; 11722 } 11723 11724 void cleanUpResourcesLI() { 11725 throw new UnsupportedOperationException(); 11726 } 11727 11728 boolean doPostDeleteLI(boolean delete) { 11729 throw new UnsupportedOperationException(); 11730 } 11731 } 11732 11733 static String getAsecPackageName(String packageCid) { 11734 int idx = packageCid.lastIndexOf("-"); 11735 if (idx == -1) { 11736 return packageCid; 11737 } 11738 return packageCid.substring(0, idx); 11739 } 11740 11741 // Utility method used to create code paths based on package name and available index. 11742 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11743 String idxStr = ""; 11744 int idx = 1; 11745 // Fall back to default value of idx=1 if prefix is not 11746 // part of oldCodePath 11747 if (oldCodePath != null) { 11748 String subStr = oldCodePath; 11749 // Drop the suffix right away 11750 if (suffix != null && subStr.endsWith(suffix)) { 11751 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11752 } 11753 // If oldCodePath already contains prefix find out the 11754 // ending index to either increment or decrement. 11755 int sidx = subStr.lastIndexOf(prefix); 11756 if (sidx != -1) { 11757 subStr = subStr.substring(sidx + prefix.length()); 11758 if (subStr != null) { 11759 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11760 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11761 } 11762 try { 11763 idx = Integer.parseInt(subStr); 11764 if (idx <= 1) { 11765 idx++; 11766 } else { 11767 idx--; 11768 } 11769 } catch(NumberFormatException e) { 11770 } 11771 } 11772 } 11773 } 11774 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11775 return prefix + idxStr; 11776 } 11777 11778 private File getNextCodePath(File targetDir, String packageName) { 11779 int suffix = 1; 11780 File result; 11781 do { 11782 result = new File(targetDir, packageName + "-" + suffix); 11783 suffix++; 11784 } while (result.exists()); 11785 return result; 11786 } 11787 11788 // Utility method that returns the relative package path with respect 11789 // to the installation directory. Like say for /data/data/com.test-1.apk 11790 // string com.test-1 is returned. 11791 static String deriveCodePathName(String codePath) { 11792 if (codePath == null) { 11793 return null; 11794 } 11795 final File codeFile = new File(codePath); 11796 final String name = codeFile.getName(); 11797 if (codeFile.isDirectory()) { 11798 return name; 11799 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11800 final int lastDot = name.lastIndexOf('.'); 11801 return name.substring(0, lastDot); 11802 } else { 11803 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11804 return null; 11805 } 11806 } 11807 11808 class PackageInstalledInfo { 11809 String name; 11810 int uid; 11811 // The set of users that originally had this package installed. 11812 int[] origUsers; 11813 // The set of users that now have this package installed. 11814 int[] newUsers; 11815 PackageParser.Package pkg; 11816 int returnCode; 11817 String returnMsg; 11818 PackageRemovedInfo removedInfo; 11819 11820 public void setError(int code, String msg) { 11821 returnCode = code; 11822 returnMsg = msg; 11823 Slog.w(TAG, msg); 11824 } 11825 11826 public void setError(String msg, PackageParserException e) { 11827 returnCode = e.error; 11828 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11829 Slog.w(TAG, msg, e); 11830 } 11831 11832 public void setError(String msg, PackageManagerException e) { 11833 returnCode = e.error; 11834 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11835 Slog.w(TAG, msg, e); 11836 } 11837 11838 // In some error cases we want to convey more info back to the observer 11839 String origPackage; 11840 String origPermission; 11841 } 11842 11843 /* 11844 * Install a non-existing package. 11845 */ 11846 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11847 UserHandle user, String installerPackageName, String volumeUuid, 11848 PackageInstalledInfo res) { 11849 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11850 11851 // Remember this for later, in case we need to rollback this install 11852 String pkgName = pkg.packageName; 11853 11854 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11855 // TODO: b/23350563 11856 final boolean dataDirExists = Environment 11857 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11858 11859 synchronized(mPackages) { 11860 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11861 // A package with the same name is already installed, though 11862 // it has been renamed to an older name. The package we 11863 // are trying to install should be installed as an update to 11864 // the existing one, but that has not been requested, so bail. 11865 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11866 + " without first uninstalling package running as " 11867 + mSettings.mRenamedPackages.get(pkgName)); 11868 return; 11869 } 11870 if (mPackages.containsKey(pkgName)) { 11871 // Don't allow installation over an existing package with the same name. 11872 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11873 + " without first uninstalling."); 11874 return; 11875 } 11876 } 11877 11878 try { 11879 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11880 System.currentTimeMillis(), user); 11881 11882 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11883 // delete the partially installed application. the data directory will have to be 11884 // restored if it was already existing 11885 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11886 // remove package from internal structures. Note that we want deletePackageX to 11887 // delete the package data and cache directories that it created in 11888 // scanPackageLocked, unless those directories existed before we even tried to 11889 // install. 11890 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11891 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11892 res.removedInfo, true); 11893 } 11894 11895 } catch (PackageManagerException e) { 11896 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11897 } 11898 11899 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11900 } 11901 11902 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11903 // Can't rotate keys during boot or if sharedUser. 11904 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11905 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11906 return false; 11907 } 11908 // app is using upgradeKeySets; make sure all are valid 11909 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11910 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11911 for (int i = 0; i < upgradeKeySets.length; i++) { 11912 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11913 Slog.wtf(TAG, "Package " 11914 + (oldPs.name != null ? oldPs.name : "<null>") 11915 + " contains upgrade-key-set reference to unknown key-set: " 11916 + upgradeKeySets[i] 11917 + " reverting to signatures check."); 11918 return false; 11919 } 11920 } 11921 return true; 11922 } 11923 11924 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11925 // Upgrade keysets are being used. Determine if new package has a superset of the 11926 // required keys. 11927 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11928 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11929 for (int i = 0; i < upgradeKeySets.length; i++) { 11930 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11931 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11932 return true; 11933 } 11934 } 11935 return false; 11936 } 11937 11938 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11939 UserHandle user, String installerPackageName, String volumeUuid, 11940 PackageInstalledInfo res) { 11941 final PackageParser.Package oldPackage; 11942 final String pkgName = pkg.packageName; 11943 final int[] allUsers; 11944 final boolean[] perUserInstalled; 11945 11946 // First find the old package info and check signatures 11947 synchronized(mPackages) { 11948 oldPackage = mPackages.get(pkgName); 11949 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11950 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11951 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11952 if(!checkUpgradeKeySetLP(ps, pkg)) { 11953 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11954 "New package not signed by keys specified by upgrade-keysets: " 11955 + pkgName); 11956 return; 11957 } 11958 } else { 11959 // default to original signature matching 11960 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11961 != PackageManager.SIGNATURE_MATCH) { 11962 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11963 "New package has a different signature: " + pkgName); 11964 return; 11965 } 11966 } 11967 11968 // In case of rollback, remember per-user/profile install state 11969 allUsers = sUserManager.getUserIds(); 11970 perUserInstalled = new boolean[allUsers.length]; 11971 for (int i = 0; i < allUsers.length; i++) { 11972 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11973 } 11974 } 11975 11976 boolean sysPkg = (isSystemApp(oldPackage)); 11977 if (sysPkg) { 11978 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11979 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11980 } else { 11981 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11982 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11983 } 11984 } 11985 11986 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11987 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11988 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11989 String volumeUuid, PackageInstalledInfo res) { 11990 String pkgName = deletedPackage.packageName; 11991 boolean deletedPkg = true; 11992 boolean updatedSettings = false; 11993 11994 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11995 + deletedPackage); 11996 long origUpdateTime; 11997 if (pkg.mExtras != null) { 11998 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11999 } else { 12000 origUpdateTime = 0; 12001 } 12002 12003 // First delete the existing package while retaining the data directory 12004 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12005 res.removedInfo, true)) { 12006 // If the existing package wasn't successfully deleted 12007 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12008 deletedPkg = false; 12009 } else { 12010 // Successfully deleted the old package; proceed with replace. 12011 12012 // If deleted package lived in a container, give users a chance to 12013 // relinquish resources before killing. 12014 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12015 if (DEBUG_INSTALL) { 12016 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12017 } 12018 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12019 final ArrayList<String> pkgList = new ArrayList<String>(1); 12020 pkgList.add(deletedPackage.applicationInfo.packageName); 12021 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12022 } 12023 12024 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12025 try { 12026 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12027 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12028 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12029 perUserInstalled, res, user); 12030 updatedSettings = true; 12031 } catch (PackageManagerException e) { 12032 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12033 } 12034 } 12035 12036 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12037 // remove package from internal structures. Note that we want deletePackageX to 12038 // delete the package data and cache directories that it created in 12039 // scanPackageLocked, unless those directories existed before we even tried to 12040 // install. 12041 if(updatedSettings) { 12042 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12043 deletePackageLI( 12044 pkgName, null, true, allUsers, perUserInstalled, 12045 PackageManager.DELETE_KEEP_DATA, 12046 res.removedInfo, true); 12047 } 12048 // Since we failed to install the new package we need to restore the old 12049 // package that we deleted. 12050 if (deletedPkg) { 12051 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12052 File restoreFile = new File(deletedPackage.codePath); 12053 // Parse old package 12054 boolean oldExternal = isExternal(deletedPackage); 12055 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12056 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12057 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12058 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12059 try { 12060 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 12061 } catch (PackageManagerException e) { 12062 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12063 + e.getMessage()); 12064 return; 12065 } 12066 // Restore of old package succeeded. Update permissions. 12067 // writer 12068 synchronized (mPackages) { 12069 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12070 UPDATE_PERMISSIONS_ALL); 12071 // can downgrade to reader 12072 mSettings.writeLPr(); 12073 } 12074 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12075 } 12076 } 12077 } 12078 12079 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12080 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12081 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12082 String volumeUuid, PackageInstalledInfo res) { 12083 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12084 + ", old=" + deletedPackage); 12085 boolean disabledSystem = false; 12086 boolean updatedSettings = false; 12087 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12088 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12089 != 0) { 12090 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12091 } 12092 String packageName = deletedPackage.packageName; 12093 if (packageName == null) { 12094 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12095 "Attempt to delete null packageName."); 12096 return; 12097 } 12098 PackageParser.Package oldPkg; 12099 PackageSetting oldPkgSetting; 12100 // reader 12101 synchronized (mPackages) { 12102 oldPkg = mPackages.get(packageName); 12103 oldPkgSetting = mSettings.mPackages.get(packageName); 12104 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12105 (oldPkgSetting == null)) { 12106 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12107 "Couldn't find package:" + packageName + " information"); 12108 return; 12109 } 12110 } 12111 12112 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12113 12114 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12115 res.removedInfo.removedPackage = packageName; 12116 // Remove existing system package 12117 removePackageLI(oldPkgSetting, true); 12118 // writer 12119 synchronized (mPackages) { 12120 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12121 if (!disabledSystem && deletedPackage != null) { 12122 // We didn't need to disable the .apk as a current system package, 12123 // which means we are replacing another update that is already 12124 // installed. We need to make sure to delete the older one's .apk. 12125 res.removedInfo.args = createInstallArgsForExisting(0, 12126 deletedPackage.applicationInfo.getCodePath(), 12127 deletedPackage.applicationInfo.getResourcePath(), 12128 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12129 } else { 12130 res.removedInfo.args = null; 12131 } 12132 } 12133 12134 // Successfully disabled the old package. Now proceed with re-installation 12135 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12136 12137 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12138 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12139 12140 PackageParser.Package newPackage = null; 12141 try { 12142 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12143 if (newPackage.mExtras != null) { 12144 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12145 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12146 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12147 12148 // is the update attempting to change shared user? that isn't going to work... 12149 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12150 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12151 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12152 + " to " + newPkgSetting.sharedUser); 12153 updatedSettings = true; 12154 } 12155 } 12156 12157 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12158 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12159 perUserInstalled, res, user); 12160 updatedSettings = true; 12161 } 12162 12163 } catch (PackageManagerException e) { 12164 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12165 } 12166 12167 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12168 // Re installation failed. Restore old information 12169 // Remove new pkg information 12170 if (newPackage != null) { 12171 removeInstalledPackageLI(newPackage, true); 12172 } 12173 // Add back the old system package 12174 try { 12175 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12176 } catch (PackageManagerException e) { 12177 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12178 } 12179 // Restore the old system information in Settings 12180 synchronized (mPackages) { 12181 if (disabledSystem) { 12182 mSettings.enableSystemPackageLPw(packageName); 12183 } 12184 if (updatedSettings) { 12185 mSettings.setInstallerPackageName(packageName, 12186 oldPkgSetting.installerPackageName); 12187 } 12188 mSettings.writeLPr(); 12189 } 12190 } 12191 } 12192 12193 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12194 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12195 UserHandle user) { 12196 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12197 12198 String pkgName = newPackage.packageName; 12199 synchronized (mPackages) { 12200 //write settings. the installStatus will be incomplete at this stage. 12201 //note that the new package setting would have already been 12202 //added to mPackages. It hasn't been persisted yet. 12203 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12204 mSettings.writeLPr(); 12205 } 12206 12207 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12208 synchronized (mPackages) { 12209 updatePermissionsLPw(newPackage.packageName, newPackage, 12210 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12211 ? UPDATE_PERMISSIONS_ALL : 0)); 12212 // For system-bundled packages, we assume that installing an upgraded version 12213 // of the package implies that the user actually wants to run that new code, 12214 // so we enable the package. 12215 PackageSetting ps = mSettings.mPackages.get(pkgName); 12216 if (ps != null) { 12217 if (isSystemApp(newPackage)) { 12218 // NB: implicit assumption that system package upgrades apply to all users 12219 if (DEBUG_INSTALL) { 12220 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12221 } 12222 if (res.origUsers != null) { 12223 for (int userHandle : res.origUsers) { 12224 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12225 userHandle, installerPackageName); 12226 } 12227 } 12228 // Also convey the prior install/uninstall state 12229 if (allUsers != null && perUserInstalled != null) { 12230 for (int i = 0; i < allUsers.length; i++) { 12231 if (DEBUG_INSTALL) { 12232 Slog.d(TAG, " user " + allUsers[i] 12233 + " => " + perUserInstalled[i]); 12234 } 12235 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12236 } 12237 // these install state changes will be persisted in the 12238 // upcoming call to mSettings.writeLPr(). 12239 } 12240 } 12241 // It's implied that when a user requests installation, they want the app to be 12242 // installed and enabled. 12243 int userId = user.getIdentifier(); 12244 if (userId != UserHandle.USER_ALL) { 12245 ps.setInstalled(true, userId); 12246 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12247 } 12248 } 12249 res.name = pkgName; 12250 res.uid = newPackage.applicationInfo.uid; 12251 res.pkg = newPackage; 12252 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12253 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12254 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12255 //to update install status 12256 mSettings.writeLPr(); 12257 } 12258 12259 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12260 } 12261 12262 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12263 try { 12264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12265 installPackageLI(args, res); 12266 } finally { 12267 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12268 } 12269 } 12270 12271 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12272 final int installFlags = args.installFlags; 12273 final String installerPackageName = args.installerPackageName; 12274 final String volumeUuid = args.volumeUuid; 12275 final File tmpPackageFile = new File(args.getCodePath()); 12276 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12277 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12278 || (args.volumeUuid != null)); 12279 boolean replace = false; 12280 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12281 if (args.move != null) { 12282 // moving a complete application; perfom an initial scan on the new install location 12283 scanFlags |= SCAN_INITIAL; 12284 } 12285 // Result object to be returned 12286 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12287 12288 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12289 12290 // Retrieve PackageSettings and parse package 12291 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12292 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12293 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12294 PackageParser pp = new PackageParser(); 12295 pp.setSeparateProcesses(mSeparateProcesses); 12296 pp.setDisplayMetrics(mMetrics); 12297 12298 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12299 final PackageParser.Package pkg; 12300 try { 12301 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12302 } catch (PackageParserException e) { 12303 res.setError("Failed parse during installPackageLI", e); 12304 return; 12305 } finally { 12306 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12307 } 12308 12309 // Mark that we have an install time CPU ABI override. 12310 pkg.cpuAbiOverride = args.abiOverride; 12311 12312 String pkgName = res.name = pkg.packageName; 12313 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12314 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12315 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12316 return; 12317 } 12318 } 12319 12320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12321 try { 12322 pp.collectCertificates(pkg, parseFlags); 12323 pp.collectManifestDigest(pkg); 12324 } catch (PackageParserException e) { 12325 res.setError("Failed collect during installPackageLI", e); 12326 return; 12327 } finally { 12328 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12329 } 12330 12331 /* If the installer passed in a manifest digest, compare it now. */ 12332 if (args.manifestDigest != null) { 12333 if (DEBUG_INSTALL) { 12334 final String parsedManifest = pkg.manifestDigest == null ? "null" 12335 : pkg.manifestDigest.toString(); 12336 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12337 + parsedManifest); 12338 } 12339 12340 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12341 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12342 return; 12343 } 12344 } else if (DEBUG_INSTALL) { 12345 final String parsedManifest = pkg.manifestDigest == null 12346 ? "null" : pkg.manifestDigest.toString(); 12347 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12348 } 12349 12350 // Get rid of all references to package scan path via parser. 12351 pp = null; 12352 String oldCodePath = null; 12353 boolean systemApp = false; 12354 synchronized (mPackages) { 12355 // Check if installing already existing package 12356 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12357 String oldName = mSettings.mRenamedPackages.get(pkgName); 12358 if (pkg.mOriginalPackages != null 12359 && pkg.mOriginalPackages.contains(oldName) 12360 && mPackages.containsKey(oldName)) { 12361 // This package is derived from an original package, 12362 // and this device has been updating from that original 12363 // name. We must continue using the original name, so 12364 // rename the new package here. 12365 pkg.setPackageName(oldName); 12366 pkgName = pkg.packageName; 12367 replace = true; 12368 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12369 + oldName + " pkgName=" + pkgName); 12370 } else if (mPackages.containsKey(pkgName)) { 12371 // This package, under its official name, already exists 12372 // on the device; we should replace it. 12373 replace = true; 12374 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12375 } 12376 12377 // Prevent apps opting out from runtime permissions 12378 if (replace) { 12379 PackageParser.Package oldPackage = mPackages.get(pkgName); 12380 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12381 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12382 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12383 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12384 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12385 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12386 + " doesn't support runtime permissions but the old" 12387 + " target SDK " + oldTargetSdk + " does."); 12388 return; 12389 } 12390 } 12391 } 12392 12393 PackageSetting ps = mSettings.mPackages.get(pkgName); 12394 if (ps != null) { 12395 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12396 12397 // Quick sanity check that we're signed correctly if updating; 12398 // we'll check this again later when scanning, but we want to 12399 // bail early here before tripping over redefined permissions. 12400 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12401 if (!checkUpgradeKeySetLP(ps, pkg)) { 12402 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12403 + pkg.packageName + " upgrade keys do not match the " 12404 + "previously installed version"); 12405 return; 12406 } 12407 } else { 12408 try { 12409 verifySignaturesLP(ps, pkg); 12410 } catch (PackageManagerException e) { 12411 res.setError(e.error, e.getMessage()); 12412 return; 12413 } 12414 } 12415 12416 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12417 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12418 systemApp = (ps.pkg.applicationInfo.flags & 12419 ApplicationInfo.FLAG_SYSTEM) != 0; 12420 } 12421 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12422 } 12423 12424 // Check whether the newly-scanned package wants to define an already-defined perm 12425 int N = pkg.permissions.size(); 12426 for (int i = N-1; i >= 0; i--) { 12427 PackageParser.Permission perm = pkg.permissions.get(i); 12428 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12429 if (bp != null) { 12430 // If the defining package is signed with our cert, it's okay. This 12431 // also includes the "updating the same package" case, of course. 12432 // "updating same package" could also involve key-rotation. 12433 final boolean sigsOk; 12434 if (bp.sourcePackage.equals(pkg.packageName) 12435 && (bp.packageSetting instanceof PackageSetting) 12436 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12437 scanFlags))) { 12438 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12439 } else { 12440 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12441 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12442 } 12443 if (!sigsOk) { 12444 // If the owning package is the system itself, we log but allow 12445 // install to proceed; we fail the install on all other permission 12446 // redefinitions. 12447 if (!bp.sourcePackage.equals("android")) { 12448 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12449 + pkg.packageName + " attempting to redeclare permission " 12450 + perm.info.name + " already owned by " + bp.sourcePackage); 12451 res.origPermission = perm.info.name; 12452 res.origPackage = bp.sourcePackage; 12453 return; 12454 } else { 12455 Slog.w(TAG, "Package " + pkg.packageName 12456 + " attempting to redeclare system permission " 12457 + perm.info.name + "; ignoring new declaration"); 12458 pkg.permissions.remove(i); 12459 } 12460 } 12461 } 12462 } 12463 12464 } 12465 12466 if (systemApp && onExternal) { 12467 // Disable updates to system apps on sdcard 12468 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12469 "Cannot install updates to system apps on sdcard"); 12470 return; 12471 } 12472 12473 if (args.move != null) { 12474 // We did an in-place move, so dex is ready to roll 12475 scanFlags |= SCAN_NO_DEX; 12476 scanFlags |= SCAN_MOVE; 12477 12478 synchronized (mPackages) { 12479 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12480 if (ps == null) { 12481 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12482 "Missing settings for moved package " + pkgName); 12483 } 12484 12485 // We moved the entire application as-is, so bring over the 12486 // previously derived ABI information. 12487 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12488 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12489 } 12490 12491 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12492 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12493 scanFlags |= SCAN_NO_DEX; 12494 12495 try { 12496 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12497 true /* extract libs */); 12498 } catch (PackageManagerException pme) { 12499 Slog.e(TAG, "Error deriving application ABI", pme); 12500 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12501 return; 12502 } 12503 12504 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12505 int result = mPackageDexOptimizer 12506 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12507 false /* defer */, false /* inclDependencies */); 12508 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12509 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12510 return; 12511 } 12512 } 12513 12514 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12515 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12516 return; 12517 } 12518 12519 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12520 12521 if (replace) { 12522 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12523 installerPackageName, volumeUuid, res); 12524 } else { 12525 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12526 args.user, installerPackageName, volumeUuid, res); 12527 } 12528 synchronized (mPackages) { 12529 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12530 if (ps != null) { 12531 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12532 } 12533 } 12534 } 12535 12536 private void startIntentFilterVerifications(int userId, boolean replacing, 12537 PackageParser.Package pkg) { 12538 if (mIntentFilterVerifierComponent == null) { 12539 Slog.w(TAG, "No IntentFilter verification will not be done as " 12540 + "there is no IntentFilterVerifier available!"); 12541 return; 12542 } 12543 12544 final int verifierUid = getPackageUid( 12545 mIntentFilterVerifierComponent.getPackageName(), 12546 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12547 12548 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12549 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12550 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12551 mHandler.sendMessage(msg); 12552 } 12553 12554 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12555 PackageParser.Package pkg) { 12556 int size = pkg.activities.size(); 12557 if (size == 0) { 12558 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12559 "No activity, so no need to verify any IntentFilter!"); 12560 return; 12561 } 12562 12563 final boolean hasDomainURLs = hasDomainURLs(pkg); 12564 if (!hasDomainURLs) { 12565 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12566 "No domain URLs, so no need to verify any IntentFilter!"); 12567 return; 12568 } 12569 12570 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12571 + " if any IntentFilter from the " + size 12572 + " Activities needs verification ..."); 12573 12574 int count = 0; 12575 final String packageName = pkg.packageName; 12576 12577 synchronized (mPackages) { 12578 // If this is a new install and we see that we've already run verification for this 12579 // package, we have nothing to do: it means the state was restored from backup. 12580 if (!replacing) { 12581 IntentFilterVerificationInfo ivi = 12582 mSettings.getIntentFilterVerificationLPr(packageName); 12583 if (ivi != null) { 12584 if (DEBUG_DOMAIN_VERIFICATION) { 12585 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12586 + ivi.getStatusString()); 12587 } 12588 return; 12589 } 12590 } 12591 12592 // If any filters need to be verified, then all need to be. 12593 boolean needToVerify = false; 12594 for (PackageParser.Activity a : pkg.activities) { 12595 for (ActivityIntentInfo filter : a.intents) { 12596 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12597 if (DEBUG_DOMAIN_VERIFICATION) { 12598 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12599 } 12600 needToVerify = true; 12601 break; 12602 } 12603 } 12604 } 12605 12606 if (needToVerify) { 12607 final int verificationId = mIntentFilterVerificationToken++; 12608 for (PackageParser.Activity a : pkg.activities) { 12609 for (ActivityIntentInfo filter : a.intents) { 12610 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12611 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12612 "Verification needed for IntentFilter:" + filter.toString()); 12613 mIntentFilterVerifier.addOneIntentFilterVerification( 12614 verifierUid, userId, verificationId, filter, packageName); 12615 count++; 12616 } 12617 } 12618 } 12619 } 12620 } 12621 12622 if (count > 0) { 12623 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12624 + " IntentFilter verification" + (count > 1 ? "s" : "") 12625 + " for userId:" + userId); 12626 mIntentFilterVerifier.startVerifications(userId); 12627 } else { 12628 if (DEBUG_DOMAIN_VERIFICATION) { 12629 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12630 } 12631 } 12632 } 12633 12634 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12635 final ComponentName cn = filter.activity.getComponentName(); 12636 final String packageName = cn.getPackageName(); 12637 12638 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12639 packageName); 12640 if (ivi == null) { 12641 return true; 12642 } 12643 int status = ivi.getStatus(); 12644 switch (status) { 12645 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12646 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12647 return true; 12648 12649 default: 12650 // Nothing to do 12651 return false; 12652 } 12653 } 12654 12655 private static boolean isMultiArch(PackageSetting ps) { 12656 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12657 } 12658 12659 private static boolean isMultiArch(ApplicationInfo info) { 12660 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12661 } 12662 12663 private static boolean isExternal(PackageParser.Package pkg) { 12664 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12665 } 12666 12667 private static boolean isExternal(PackageSetting ps) { 12668 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12669 } 12670 12671 private static boolean isExternal(ApplicationInfo info) { 12672 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12673 } 12674 12675 private static boolean isSystemApp(PackageParser.Package pkg) { 12676 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12677 } 12678 12679 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12680 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12681 } 12682 12683 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12684 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12685 } 12686 12687 private static boolean isSystemApp(PackageSetting ps) { 12688 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12689 } 12690 12691 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12692 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12693 } 12694 12695 private int packageFlagsToInstallFlags(PackageSetting ps) { 12696 int installFlags = 0; 12697 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12698 // This existing package was an external ASEC install when we have 12699 // the external flag without a UUID 12700 installFlags |= PackageManager.INSTALL_EXTERNAL; 12701 } 12702 if (ps.isForwardLocked()) { 12703 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12704 } 12705 return installFlags; 12706 } 12707 12708 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12709 if (isExternal(pkg)) { 12710 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12711 return mSettings.getExternalVersion(); 12712 } else { 12713 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12714 } 12715 } else { 12716 return mSettings.getInternalVersion(); 12717 } 12718 } 12719 12720 private void deleteTempPackageFiles() { 12721 final FilenameFilter filter = new FilenameFilter() { 12722 public boolean accept(File dir, String name) { 12723 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12724 } 12725 }; 12726 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12727 file.delete(); 12728 } 12729 } 12730 12731 @Override 12732 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12733 int flags) { 12734 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12735 flags); 12736 } 12737 12738 @Override 12739 public void deletePackage(final String packageName, 12740 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12741 mContext.enforceCallingOrSelfPermission( 12742 android.Manifest.permission.DELETE_PACKAGES, null); 12743 Preconditions.checkNotNull(packageName); 12744 Preconditions.checkNotNull(observer); 12745 final int uid = Binder.getCallingUid(); 12746 if (UserHandle.getUserId(uid) != userId) { 12747 mContext.enforceCallingPermission( 12748 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12749 "deletePackage for user " + userId); 12750 } 12751 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12752 try { 12753 observer.onPackageDeleted(packageName, 12754 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12755 } catch (RemoteException re) { 12756 } 12757 return; 12758 } 12759 12760 boolean uninstallBlocked = false; 12761 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12762 int[] users = sUserManager.getUserIds(); 12763 for (int i = 0; i < users.length; ++i) { 12764 if (getBlockUninstallForUser(packageName, users[i])) { 12765 uninstallBlocked = true; 12766 break; 12767 } 12768 } 12769 } else { 12770 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12771 } 12772 if (uninstallBlocked) { 12773 try { 12774 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12775 null); 12776 } catch (RemoteException re) { 12777 } 12778 return; 12779 } 12780 12781 if (DEBUG_REMOVE) { 12782 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12783 } 12784 // Queue up an async operation since the package deletion may take a little while. 12785 mHandler.post(new Runnable() { 12786 public void run() { 12787 mHandler.removeCallbacks(this); 12788 final int returnCode = deletePackageX(packageName, userId, flags); 12789 if (observer != null) { 12790 try { 12791 observer.onPackageDeleted(packageName, returnCode, null); 12792 } catch (RemoteException e) { 12793 Log.i(TAG, "Observer no longer exists."); 12794 } //end catch 12795 } //end if 12796 } //end run 12797 }); 12798 } 12799 12800 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12801 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12802 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12803 try { 12804 if (dpm != null) { 12805 if (dpm.isDeviceOwner(packageName)) { 12806 return true; 12807 } 12808 int[] users; 12809 if (userId == UserHandle.USER_ALL) { 12810 users = sUserManager.getUserIds(); 12811 } else { 12812 users = new int[]{userId}; 12813 } 12814 for (int i = 0; i < users.length; ++i) { 12815 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12816 return true; 12817 } 12818 } 12819 } 12820 } catch (RemoteException e) { 12821 } 12822 return false; 12823 } 12824 12825 /** 12826 * This method is an internal method that could be get invoked either 12827 * to delete an installed package or to clean up a failed installation. 12828 * After deleting an installed package, a broadcast is sent to notify any 12829 * listeners that the package has been installed. For cleaning up a failed 12830 * installation, the broadcast is not necessary since the package's 12831 * installation wouldn't have sent the initial broadcast either 12832 * The key steps in deleting a package are 12833 * deleting the package information in internal structures like mPackages, 12834 * deleting the packages base directories through installd 12835 * updating mSettings to reflect current status 12836 * persisting settings for later use 12837 * sending a broadcast if necessary 12838 */ 12839 private int deletePackageX(String packageName, int userId, int flags) { 12840 final PackageRemovedInfo info = new PackageRemovedInfo(); 12841 final boolean res; 12842 12843 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12844 ? UserHandle.ALL : new UserHandle(userId); 12845 12846 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12847 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12848 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12849 } 12850 12851 boolean removedForAllUsers = false; 12852 boolean systemUpdate = false; 12853 12854 // for the uninstall-updates case and restricted profiles, remember the per- 12855 // userhandle installed state 12856 int[] allUsers; 12857 boolean[] perUserInstalled; 12858 synchronized (mPackages) { 12859 PackageSetting ps = mSettings.mPackages.get(packageName); 12860 allUsers = sUserManager.getUserIds(); 12861 perUserInstalled = new boolean[allUsers.length]; 12862 for (int i = 0; i < allUsers.length; i++) { 12863 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12864 } 12865 } 12866 12867 synchronized (mInstallLock) { 12868 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12869 res = deletePackageLI(packageName, removeForUser, 12870 true, allUsers, perUserInstalled, 12871 flags | REMOVE_CHATTY, info, true); 12872 systemUpdate = info.isRemovedPackageSystemUpdate; 12873 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12874 removedForAllUsers = true; 12875 } 12876 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12877 + " removedForAllUsers=" + removedForAllUsers); 12878 } 12879 12880 if (res) { 12881 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12882 12883 // If the removed package was a system update, the old system package 12884 // was re-enabled; we need to broadcast this information 12885 if (systemUpdate) { 12886 Bundle extras = new Bundle(1); 12887 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12888 ? info.removedAppId : info.uid); 12889 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12890 12891 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12892 extras, null, null, null); 12893 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12894 extras, null, null, null); 12895 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12896 null, packageName, null, null); 12897 } 12898 } 12899 // Force a gc here. 12900 Runtime.getRuntime().gc(); 12901 // Delete the resources here after sending the broadcast to let 12902 // other processes clean up before deleting resources. 12903 if (info.args != null) { 12904 synchronized (mInstallLock) { 12905 info.args.doPostDeleteLI(true); 12906 } 12907 } 12908 12909 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12910 } 12911 12912 class PackageRemovedInfo { 12913 String removedPackage; 12914 int uid = -1; 12915 int removedAppId = -1; 12916 int[] removedUsers = null; 12917 boolean isRemovedPackageSystemUpdate = false; 12918 // Clean up resources deleted packages. 12919 InstallArgs args = null; 12920 12921 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12922 Bundle extras = new Bundle(1); 12923 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12924 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12925 if (replacing) { 12926 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12927 } 12928 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12929 if (removedPackage != null) { 12930 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12931 extras, null, null, removedUsers); 12932 if (fullRemove && !replacing) { 12933 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12934 extras, null, null, removedUsers); 12935 } 12936 } 12937 if (removedAppId >= 0) { 12938 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12939 removedUsers); 12940 } 12941 } 12942 } 12943 12944 /* 12945 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12946 * flag is not set, the data directory is removed as well. 12947 * make sure this flag is set for partially installed apps. If not its meaningless to 12948 * delete a partially installed application. 12949 */ 12950 private void removePackageDataLI(PackageSetting ps, 12951 int[] allUserHandles, boolean[] perUserInstalled, 12952 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12953 String packageName = ps.name; 12954 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12955 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12956 // Retrieve object to delete permissions for shared user later on 12957 final PackageSetting deletedPs; 12958 // reader 12959 synchronized (mPackages) { 12960 deletedPs = mSettings.mPackages.get(packageName); 12961 if (outInfo != null) { 12962 outInfo.removedPackage = packageName; 12963 outInfo.removedUsers = deletedPs != null 12964 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12965 : null; 12966 } 12967 } 12968 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12969 removeDataDirsLI(ps.volumeUuid, packageName); 12970 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12971 } 12972 // writer 12973 synchronized (mPackages) { 12974 if (deletedPs != null) { 12975 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12976 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12977 clearDefaultBrowserIfNeeded(packageName); 12978 if (outInfo != null) { 12979 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12980 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12981 } 12982 updatePermissionsLPw(deletedPs.name, null, 0); 12983 if (deletedPs.sharedUser != null) { 12984 // Remove permissions associated with package. Since runtime 12985 // permissions are per user we have to kill the removed package 12986 // or packages running under the shared user of the removed 12987 // package if revoking the permissions requested only by the removed 12988 // package is successful and this causes a change in gids. 12989 for (int userId : UserManagerService.getInstance().getUserIds()) { 12990 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12991 userId); 12992 if (userIdToKill == UserHandle.USER_ALL 12993 || userIdToKill >= UserHandle.USER_OWNER) { 12994 // If gids changed for this user, kill all affected packages. 12995 mHandler.post(new Runnable() { 12996 @Override 12997 public void run() { 12998 // This has to happen with no lock held. 12999 killApplication(deletedPs.name, deletedPs.appId, 13000 KILL_APP_REASON_GIDS_CHANGED); 13001 } 13002 }); 13003 break; 13004 } 13005 } 13006 } 13007 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13008 } 13009 // make sure to preserve per-user disabled state if this removal was just 13010 // a downgrade of a system app to the factory package 13011 if (allUserHandles != null && perUserInstalled != null) { 13012 if (DEBUG_REMOVE) { 13013 Slog.d(TAG, "Propagating install state across downgrade"); 13014 } 13015 for (int i = 0; i < allUserHandles.length; i++) { 13016 if (DEBUG_REMOVE) { 13017 Slog.d(TAG, " user " + allUserHandles[i] 13018 + " => " + perUserInstalled[i]); 13019 } 13020 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13021 } 13022 } 13023 } 13024 // can downgrade to reader 13025 if (writeSettings) { 13026 // Save settings now 13027 mSettings.writeLPr(); 13028 } 13029 } 13030 if (outInfo != null) { 13031 // A user ID was deleted here. Go through all users and remove it 13032 // from KeyStore. 13033 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13034 } 13035 } 13036 13037 static boolean locationIsPrivileged(File path) { 13038 try { 13039 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13040 .getCanonicalPath(); 13041 return path.getCanonicalPath().startsWith(privilegedAppDir); 13042 } catch (IOException e) { 13043 Slog.e(TAG, "Unable to access code path " + path); 13044 } 13045 return false; 13046 } 13047 13048 /* 13049 * Tries to delete system package. 13050 */ 13051 private boolean deleteSystemPackageLI(PackageSetting newPs, 13052 int[] allUserHandles, boolean[] perUserInstalled, 13053 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13054 final boolean applyUserRestrictions 13055 = (allUserHandles != null) && (perUserInstalled != null); 13056 PackageSetting disabledPs = null; 13057 // Confirm if the system package has been updated 13058 // An updated system app can be deleted. This will also have to restore 13059 // the system pkg from system partition 13060 // reader 13061 synchronized (mPackages) { 13062 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13063 } 13064 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13065 + " disabledPs=" + disabledPs); 13066 if (disabledPs == null) { 13067 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13068 return false; 13069 } else if (DEBUG_REMOVE) { 13070 Slog.d(TAG, "Deleting system pkg from data partition"); 13071 } 13072 if (DEBUG_REMOVE) { 13073 if (applyUserRestrictions) { 13074 Slog.d(TAG, "Remembering install states:"); 13075 for (int i = 0; i < allUserHandles.length; i++) { 13076 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13077 } 13078 } 13079 } 13080 // Delete the updated package 13081 outInfo.isRemovedPackageSystemUpdate = true; 13082 if (disabledPs.versionCode < newPs.versionCode) { 13083 // Delete data for downgrades 13084 flags &= ~PackageManager.DELETE_KEEP_DATA; 13085 } else { 13086 // Preserve data by setting flag 13087 flags |= PackageManager.DELETE_KEEP_DATA; 13088 } 13089 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13090 allUserHandles, perUserInstalled, outInfo, writeSettings); 13091 if (!ret) { 13092 return false; 13093 } 13094 // writer 13095 synchronized (mPackages) { 13096 // Reinstate the old system package 13097 mSettings.enableSystemPackageLPw(newPs.name); 13098 // Remove any native libraries from the upgraded package. 13099 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13100 } 13101 // Install the system package 13102 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13103 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13104 if (locationIsPrivileged(disabledPs.codePath)) { 13105 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13106 } 13107 13108 final PackageParser.Package newPkg; 13109 try { 13110 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13111 } catch (PackageManagerException e) { 13112 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13113 return false; 13114 } 13115 13116 // writer 13117 synchronized (mPackages) { 13118 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13119 13120 // Propagate the permissions state as we do not want to drop on the floor 13121 // runtime permissions. The update permissions method below will take 13122 // care of removing obsolete permissions and grant install permissions. 13123 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13124 updatePermissionsLPw(newPkg.packageName, newPkg, 13125 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13126 13127 if (applyUserRestrictions) { 13128 if (DEBUG_REMOVE) { 13129 Slog.d(TAG, "Propagating install state across reinstall"); 13130 } 13131 for (int i = 0; i < allUserHandles.length; i++) { 13132 if (DEBUG_REMOVE) { 13133 Slog.d(TAG, " user " + allUserHandles[i] 13134 + " => " + perUserInstalled[i]); 13135 } 13136 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13137 13138 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13139 } 13140 // Regardless of writeSettings we need to ensure that this restriction 13141 // state propagation is persisted 13142 mSettings.writeAllUsersPackageRestrictionsLPr(); 13143 } 13144 // can downgrade to reader here 13145 if (writeSettings) { 13146 mSettings.writeLPr(); 13147 } 13148 } 13149 return true; 13150 } 13151 13152 private boolean deleteInstalledPackageLI(PackageSetting ps, 13153 boolean deleteCodeAndResources, int flags, 13154 int[] allUserHandles, boolean[] perUserInstalled, 13155 PackageRemovedInfo outInfo, boolean writeSettings) { 13156 if (outInfo != null) { 13157 outInfo.uid = ps.appId; 13158 } 13159 13160 // Delete package data from internal structures and also remove data if flag is set 13161 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13162 13163 // Delete application code and resources 13164 if (deleteCodeAndResources && (outInfo != null)) { 13165 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13166 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13167 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13168 } 13169 return true; 13170 } 13171 13172 @Override 13173 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13174 int userId) { 13175 mContext.enforceCallingOrSelfPermission( 13176 android.Manifest.permission.DELETE_PACKAGES, null); 13177 synchronized (mPackages) { 13178 PackageSetting ps = mSettings.mPackages.get(packageName); 13179 if (ps == null) { 13180 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13181 return false; 13182 } 13183 if (!ps.getInstalled(userId)) { 13184 // Can't block uninstall for an app that is not installed or enabled. 13185 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13186 return false; 13187 } 13188 ps.setBlockUninstall(blockUninstall, userId); 13189 mSettings.writePackageRestrictionsLPr(userId); 13190 } 13191 return true; 13192 } 13193 13194 @Override 13195 public boolean getBlockUninstallForUser(String packageName, int userId) { 13196 synchronized (mPackages) { 13197 PackageSetting ps = mSettings.mPackages.get(packageName); 13198 if (ps == null) { 13199 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13200 return false; 13201 } 13202 return ps.getBlockUninstall(userId); 13203 } 13204 } 13205 13206 /* 13207 * This method handles package deletion in general 13208 */ 13209 private boolean deletePackageLI(String packageName, UserHandle user, 13210 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13211 int flags, PackageRemovedInfo outInfo, 13212 boolean writeSettings) { 13213 if (packageName == null) { 13214 Slog.w(TAG, "Attempt to delete null packageName."); 13215 return false; 13216 } 13217 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13218 PackageSetting ps; 13219 boolean dataOnly = false; 13220 int removeUser = -1; 13221 int appId = -1; 13222 synchronized (mPackages) { 13223 ps = mSettings.mPackages.get(packageName); 13224 if (ps == null) { 13225 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13226 return false; 13227 } 13228 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13229 && user.getIdentifier() != UserHandle.USER_ALL) { 13230 // The caller is asking that the package only be deleted for a single 13231 // user. To do this, we just mark its uninstalled state and delete 13232 // its data. If this is a system app, we only allow this to happen if 13233 // they have set the special DELETE_SYSTEM_APP which requests different 13234 // semantics than normal for uninstalling system apps. 13235 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13236 final int userId = user.getIdentifier(); 13237 ps.setUserState(userId, 13238 COMPONENT_ENABLED_STATE_DEFAULT, 13239 false, //installed 13240 true, //stopped 13241 true, //notLaunched 13242 false, //hidden 13243 null, null, null, 13244 false, // blockUninstall 13245 ps.readUserState(userId).domainVerificationStatus, 0); 13246 if (!isSystemApp(ps)) { 13247 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13248 // Other user still have this package installed, so all 13249 // we need to do is clear this user's data and save that 13250 // it is uninstalled. 13251 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13252 removeUser = user.getIdentifier(); 13253 appId = ps.appId; 13254 scheduleWritePackageRestrictionsLocked(removeUser); 13255 } else { 13256 // We need to set it back to 'installed' so the uninstall 13257 // broadcasts will be sent correctly. 13258 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13259 ps.setInstalled(true, user.getIdentifier()); 13260 } 13261 } else { 13262 // This is a system app, so we assume that the 13263 // other users still have this package installed, so all 13264 // we need to do is clear this user's data and save that 13265 // it is uninstalled. 13266 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13267 removeUser = user.getIdentifier(); 13268 appId = ps.appId; 13269 scheduleWritePackageRestrictionsLocked(removeUser); 13270 } 13271 } 13272 } 13273 13274 if (removeUser >= 0) { 13275 // From above, we determined that we are deleting this only 13276 // for a single user. Continue the work here. 13277 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13278 if (outInfo != null) { 13279 outInfo.removedPackage = packageName; 13280 outInfo.removedAppId = appId; 13281 outInfo.removedUsers = new int[] {removeUser}; 13282 } 13283 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13284 removeKeystoreDataIfNeeded(removeUser, appId); 13285 schedulePackageCleaning(packageName, removeUser, false); 13286 synchronized (mPackages) { 13287 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13288 scheduleWritePackageRestrictionsLocked(removeUser); 13289 } 13290 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13291 } 13292 return true; 13293 } 13294 13295 if (dataOnly) { 13296 // Delete application data first 13297 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13298 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13299 return true; 13300 } 13301 13302 boolean ret = false; 13303 if (isSystemApp(ps)) { 13304 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13305 // When an updated system application is deleted we delete the existing resources as well and 13306 // fall back to existing code in system partition 13307 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13308 flags, outInfo, writeSettings); 13309 } else { 13310 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13311 // Kill application pre-emptively especially for apps on sd. 13312 killApplication(packageName, ps.appId, "uninstall pkg"); 13313 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13314 allUserHandles, perUserInstalled, 13315 outInfo, writeSettings); 13316 } 13317 13318 return ret; 13319 } 13320 13321 private final class ClearStorageConnection implements ServiceConnection { 13322 IMediaContainerService mContainerService; 13323 13324 @Override 13325 public void onServiceConnected(ComponentName name, IBinder service) { 13326 synchronized (this) { 13327 mContainerService = IMediaContainerService.Stub.asInterface(service); 13328 notifyAll(); 13329 } 13330 } 13331 13332 @Override 13333 public void onServiceDisconnected(ComponentName name) { 13334 } 13335 } 13336 13337 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13338 final boolean mounted; 13339 if (Environment.isExternalStorageEmulated()) { 13340 mounted = true; 13341 } else { 13342 final String status = Environment.getExternalStorageState(); 13343 13344 mounted = status.equals(Environment.MEDIA_MOUNTED) 13345 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13346 } 13347 13348 if (!mounted) { 13349 return; 13350 } 13351 13352 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13353 int[] users; 13354 if (userId == UserHandle.USER_ALL) { 13355 users = sUserManager.getUserIds(); 13356 } else { 13357 users = new int[] { userId }; 13358 } 13359 final ClearStorageConnection conn = new ClearStorageConnection(); 13360 if (mContext.bindServiceAsUser( 13361 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13362 try { 13363 for (int curUser : users) { 13364 long timeout = SystemClock.uptimeMillis() + 5000; 13365 synchronized (conn) { 13366 long now = SystemClock.uptimeMillis(); 13367 while (conn.mContainerService == null && now < timeout) { 13368 try { 13369 conn.wait(timeout - now); 13370 } catch (InterruptedException e) { 13371 } 13372 } 13373 } 13374 if (conn.mContainerService == null) { 13375 return; 13376 } 13377 13378 final UserEnvironment userEnv = new UserEnvironment(curUser); 13379 clearDirectory(conn.mContainerService, 13380 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13381 if (allData) { 13382 clearDirectory(conn.mContainerService, 13383 userEnv.buildExternalStorageAppDataDirs(packageName)); 13384 clearDirectory(conn.mContainerService, 13385 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13386 } 13387 } 13388 } finally { 13389 mContext.unbindService(conn); 13390 } 13391 } 13392 } 13393 13394 @Override 13395 public void clearApplicationUserData(final String packageName, 13396 final IPackageDataObserver observer, final int userId) { 13397 mContext.enforceCallingOrSelfPermission( 13398 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13399 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13400 // Queue up an async operation since the package deletion may take a little while. 13401 mHandler.post(new Runnable() { 13402 public void run() { 13403 mHandler.removeCallbacks(this); 13404 final boolean succeeded; 13405 synchronized (mInstallLock) { 13406 succeeded = clearApplicationUserDataLI(packageName, userId); 13407 } 13408 clearExternalStorageDataSync(packageName, userId, true); 13409 if (succeeded) { 13410 // invoke DeviceStorageMonitor's update method to clear any notifications 13411 DeviceStorageMonitorInternal 13412 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13413 if (dsm != null) { 13414 dsm.checkMemory(); 13415 } 13416 } 13417 if(observer != null) { 13418 try { 13419 observer.onRemoveCompleted(packageName, succeeded); 13420 } catch (RemoteException e) { 13421 Log.i(TAG, "Observer no longer exists."); 13422 } 13423 } //end if observer 13424 } //end run 13425 }); 13426 } 13427 13428 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13429 if (packageName == null) { 13430 Slog.w(TAG, "Attempt to delete null packageName."); 13431 return false; 13432 } 13433 13434 // Try finding details about the requested package 13435 PackageParser.Package pkg; 13436 synchronized (mPackages) { 13437 pkg = mPackages.get(packageName); 13438 if (pkg == null) { 13439 final PackageSetting ps = mSettings.mPackages.get(packageName); 13440 if (ps != null) { 13441 pkg = ps.pkg; 13442 } 13443 } 13444 13445 if (pkg == null) { 13446 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13447 return false; 13448 } 13449 13450 PackageSetting ps = (PackageSetting) pkg.mExtras; 13451 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13452 } 13453 13454 // Always delete data directories for package, even if we found no other 13455 // record of app. This helps users recover from UID mismatches without 13456 // resorting to a full data wipe. 13457 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13458 if (retCode < 0) { 13459 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13460 return false; 13461 } 13462 13463 final int appId = pkg.applicationInfo.uid; 13464 removeKeystoreDataIfNeeded(userId, appId); 13465 13466 // Create a native library symlink only if we have native libraries 13467 // and if the native libraries are 32 bit libraries. We do not provide 13468 // this symlink for 64 bit libraries. 13469 if (pkg.applicationInfo.primaryCpuAbi != null && 13470 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13471 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13472 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13473 nativeLibPath, userId) < 0) { 13474 Slog.w(TAG, "Failed linking native library dir"); 13475 return false; 13476 } 13477 } 13478 13479 return true; 13480 } 13481 13482 /** 13483 * Reverts user permission state changes (permissions and flags) in 13484 * all packages for a given user. 13485 * 13486 * @param userId The device user for which to do a reset. 13487 */ 13488 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13489 final int packageCount = mPackages.size(); 13490 for (int i = 0; i < packageCount; i++) { 13491 PackageParser.Package pkg = mPackages.valueAt(i); 13492 PackageSetting ps = (PackageSetting) pkg.mExtras; 13493 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13494 } 13495 } 13496 13497 /** 13498 * Reverts user permission state changes (permissions and flags). 13499 * 13500 * @param ps The package for which to reset. 13501 * @param userId The device user for which to do a reset. 13502 */ 13503 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13504 final PackageSetting ps, final int userId) { 13505 if (ps.pkg == null) { 13506 return; 13507 } 13508 13509 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13510 | FLAG_PERMISSION_USER_FIXED 13511 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13512 13513 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13514 | FLAG_PERMISSION_POLICY_FIXED; 13515 13516 boolean writeInstallPermissions = false; 13517 boolean writeRuntimePermissions = false; 13518 13519 final int permissionCount = ps.pkg.requestedPermissions.size(); 13520 for (int i = 0; i < permissionCount; i++) { 13521 String permission = ps.pkg.requestedPermissions.get(i); 13522 13523 BasePermission bp = mSettings.mPermissions.get(permission); 13524 if (bp == null) { 13525 continue; 13526 } 13527 13528 // If shared user we just reset the state to which only this app contributed. 13529 if (ps.sharedUser != null) { 13530 boolean used = false; 13531 final int packageCount = ps.sharedUser.packages.size(); 13532 for (int j = 0; j < packageCount; j++) { 13533 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13534 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13535 && pkg.pkg.requestedPermissions.contains(permission)) { 13536 used = true; 13537 break; 13538 } 13539 } 13540 if (used) { 13541 continue; 13542 } 13543 } 13544 13545 PermissionsState permissionsState = ps.getPermissionsState(); 13546 13547 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13548 13549 // Always clear the user settable flags. 13550 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13551 bp.name) != null; 13552 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13553 if (hasInstallState) { 13554 writeInstallPermissions = true; 13555 } else { 13556 writeRuntimePermissions = true; 13557 } 13558 } 13559 13560 // Below is only runtime permission handling. 13561 if (!bp.isRuntime()) { 13562 continue; 13563 } 13564 13565 // Never clobber system or policy. 13566 if ((oldFlags & policyOrSystemFlags) != 0) { 13567 continue; 13568 } 13569 13570 // If this permission was granted by default, make sure it is. 13571 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13572 if (permissionsState.grantRuntimePermission(bp, userId) 13573 != PERMISSION_OPERATION_FAILURE) { 13574 writeRuntimePermissions = true; 13575 } 13576 } else { 13577 // Otherwise, reset the permission. 13578 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13579 switch (revokeResult) { 13580 case PERMISSION_OPERATION_SUCCESS: { 13581 writeRuntimePermissions = true; 13582 } break; 13583 13584 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13585 writeRuntimePermissions = true; 13586 final int appId = ps.appId; 13587 mHandler.post(new Runnable() { 13588 @Override 13589 public void run() { 13590 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13591 } 13592 }); 13593 } break; 13594 } 13595 } 13596 } 13597 13598 // Synchronously write as we are taking permissions away. 13599 if (writeRuntimePermissions) { 13600 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13601 } 13602 13603 // Synchronously write as we are taking permissions away. 13604 if (writeInstallPermissions) { 13605 mSettings.writeLPr(); 13606 } 13607 } 13608 13609 /** 13610 * Remove entries from the keystore daemon. Will only remove it if the 13611 * {@code appId} is valid. 13612 */ 13613 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13614 if (appId < 0) { 13615 return; 13616 } 13617 13618 final KeyStore keyStore = KeyStore.getInstance(); 13619 if (keyStore != null) { 13620 if (userId == UserHandle.USER_ALL) { 13621 for (final int individual : sUserManager.getUserIds()) { 13622 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13623 } 13624 } else { 13625 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13626 } 13627 } else { 13628 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13629 } 13630 } 13631 13632 @Override 13633 public void deleteApplicationCacheFiles(final String packageName, 13634 final IPackageDataObserver observer) { 13635 mContext.enforceCallingOrSelfPermission( 13636 android.Manifest.permission.DELETE_CACHE_FILES, null); 13637 // Queue up an async operation since the package deletion may take a little while. 13638 final int userId = UserHandle.getCallingUserId(); 13639 mHandler.post(new Runnable() { 13640 public void run() { 13641 mHandler.removeCallbacks(this); 13642 final boolean succeded; 13643 synchronized (mInstallLock) { 13644 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13645 } 13646 clearExternalStorageDataSync(packageName, userId, false); 13647 if (observer != null) { 13648 try { 13649 observer.onRemoveCompleted(packageName, succeded); 13650 } catch (RemoteException e) { 13651 Log.i(TAG, "Observer no longer exists."); 13652 } 13653 } //end if observer 13654 } //end run 13655 }); 13656 } 13657 13658 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13659 if (packageName == null) { 13660 Slog.w(TAG, "Attempt to delete null packageName."); 13661 return false; 13662 } 13663 PackageParser.Package p; 13664 synchronized (mPackages) { 13665 p = mPackages.get(packageName); 13666 } 13667 if (p == null) { 13668 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13669 return false; 13670 } 13671 final ApplicationInfo applicationInfo = p.applicationInfo; 13672 if (applicationInfo == null) { 13673 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13674 return false; 13675 } 13676 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13677 if (retCode < 0) { 13678 Slog.w(TAG, "Couldn't remove cache files for package: " 13679 + packageName + " u" + userId); 13680 return false; 13681 } 13682 return true; 13683 } 13684 13685 @Override 13686 public void getPackageSizeInfo(final String packageName, int userHandle, 13687 final IPackageStatsObserver observer) { 13688 mContext.enforceCallingOrSelfPermission( 13689 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13690 if (packageName == null) { 13691 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13692 } 13693 13694 PackageStats stats = new PackageStats(packageName, userHandle); 13695 13696 /* 13697 * Queue up an async operation since the package measurement may take a 13698 * little while. 13699 */ 13700 Message msg = mHandler.obtainMessage(INIT_COPY); 13701 msg.obj = new MeasureParams(stats, observer); 13702 mHandler.sendMessage(msg); 13703 } 13704 13705 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13706 PackageStats pStats) { 13707 if (packageName == null) { 13708 Slog.w(TAG, "Attempt to get size of null packageName."); 13709 return false; 13710 } 13711 PackageParser.Package p; 13712 boolean dataOnly = false; 13713 String libDirRoot = null; 13714 String asecPath = null; 13715 PackageSetting ps = null; 13716 synchronized (mPackages) { 13717 p = mPackages.get(packageName); 13718 ps = mSettings.mPackages.get(packageName); 13719 if(p == null) { 13720 dataOnly = true; 13721 if((ps == null) || (ps.pkg == null)) { 13722 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13723 return false; 13724 } 13725 p = ps.pkg; 13726 } 13727 if (ps != null) { 13728 libDirRoot = ps.legacyNativeLibraryPathString; 13729 } 13730 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13731 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13732 if (secureContainerId != null) { 13733 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13734 } 13735 } 13736 } 13737 String publicSrcDir = null; 13738 if(!dataOnly) { 13739 final ApplicationInfo applicationInfo = p.applicationInfo; 13740 if (applicationInfo == null) { 13741 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13742 return false; 13743 } 13744 if (p.isForwardLocked()) { 13745 publicSrcDir = applicationInfo.getBaseResourcePath(); 13746 } 13747 } 13748 // TODO: extend to measure size of split APKs 13749 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13750 // not just the first level. 13751 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13752 // just the primary. 13753 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13754 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13755 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13756 if (res < 0) { 13757 return false; 13758 } 13759 13760 // Fix-up for forward-locked applications in ASEC containers. 13761 if (!isExternal(p)) { 13762 pStats.codeSize += pStats.externalCodeSize; 13763 pStats.externalCodeSize = 0L; 13764 } 13765 13766 return true; 13767 } 13768 13769 13770 @Override 13771 public void addPackageToPreferred(String packageName) { 13772 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13773 } 13774 13775 @Override 13776 public void removePackageFromPreferred(String packageName) { 13777 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13778 } 13779 13780 @Override 13781 public List<PackageInfo> getPreferredPackages(int flags) { 13782 return new ArrayList<PackageInfo>(); 13783 } 13784 13785 private int getUidTargetSdkVersionLockedLPr(int uid) { 13786 Object obj = mSettings.getUserIdLPr(uid); 13787 if (obj instanceof SharedUserSetting) { 13788 final SharedUserSetting sus = (SharedUserSetting) obj; 13789 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13790 final Iterator<PackageSetting> it = sus.packages.iterator(); 13791 while (it.hasNext()) { 13792 final PackageSetting ps = it.next(); 13793 if (ps.pkg != null) { 13794 int v = ps.pkg.applicationInfo.targetSdkVersion; 13795 if (v < vers) vers = v; 13796 } 13797 } 13798 return vers; 13799 } else if (obj instanceof PackageSetting) { 13800 final PackageSetting ps = (PackageSetting) obj; 13801 if (ps.pkg != null) { 13802 return ps.pkg.applicationInfo.targetSdkVersion; 13803 } 13804 } 13805 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13806 } 13807 13808 @Override 13809 public void addPreferredActivity(IntentFilter filter, int match, 13810 ComponentName[] set, ComponentName activity, int userId) { 13811 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13812 "Adding preferred"); 13813 } 13814 13815 private void addPreferredActivityInternal(IntentFilter filter, int match, 13816 ComponentName[] set, ComponentName activity, boolean always, int userId, 13817 String opname) { 13818 // writer 13819 int callingUid = Binder.getCallingUid(); 13820 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13821 if (filter.countActions() == 0) { 13822 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13823 return; 13824 } 13825 synchronized (mPackages) { 13826 if (mContext.checkCallingOrSelfPermission( 13827 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13828 != PackageManager.PERMISSION_GRANTED) { 13829 if (getUidTargetSdkVersionLockedLPr(callingUid) 13830 < Build.VERSION_CODES.FROYO) { 13831 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13832 + callingUid); 13833 return; 13834 } 13835 mContext.enforceCallingOrSelfPermission( 13836 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13837 } 13838 13839 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13840 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13841 + userId + ":"); 13842 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13843 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13844 scheduleWritePackageRestrictionsLocked(userId); 13845 } 13846 } 13847 13848 @Override 13849 public void replacePreferredActivity(IntentFilter filter, int match, 13850 ComponentName[] set, ComponentName activity, int userId) { 13851 if (filter.countActions() != 1) { 13852 throw new IllegalArgumentException( 13853 "replacePreferredActivity expects filter to have only 1 action."); 13854 } 13855 if (filter.countDataAuthorities() != 0 13856 || filter.countDataPaths() != 0 13857 || filter.countDataSchemes() > 1 13858 || filter.countDataTypes() != 0) { 13859 throw new IllegalArgumentException( 13860 "replacePreferredActivity expects filter to have no data authorities, " + 13861 "paths, or types; and at most one scheme."); 13862 } 13863 13864 final int callingUid = Binder.getCallingUid(); 13865 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13866 synchronized (mPackages) { 13867 if (mContext.checkCallingOrSelfPermission( 13868 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13869 != PackageManager.PERMISSION_GRANTED) { 13870 if (getUidTargetSdkVersionLockedLPr(callingUid) 13871 < Build.VERSION_CODES.FROYO) { 13872 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13873 + Binder.getCallingUid()); 13874 return; 13875 } 13876 mContext.enforceCallingOrSelfPermission( 13877 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13878 } 13879 13880 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13881 if (pir != null) { 13882 // Get all of the existing entries that exactly match this filter. 13883 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13884 if (existing != null && existing.size() == 1) { 13885 PreferredActivity cur = existing.get(0); 13886 if (DEBUG_PREFERRED) { 13887 Slog.i(TAG, "Checking replace of preferred:"); 13888 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13889 if (!cur.mPref.mAlways) { 13890 Slog.i(TAG, " -- CUR; not mAlways!"); 13891 } else { 13892 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13893 Slog.i(TAG, " -- CUR: mSet=" 13894 + Arrays.toString(cur.mPref.mSetComponents)); 13895 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13896 Slog.i(TAG, " -- NEW: mMatch=" 13897 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13898 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13899 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13900 } 13901 } 13902 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13903 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13904 && cur.mPref.sameSet(set)) { 13905 // Setting the preferred activity to what it happens to be already 13906 if (DEBUG_PREFERRED) { 13907 Slog.i(TAG, "Replacing with same preferred activity " 13908 + cur.mPref.mShortComponent + " for user " 13909 + userId + ":"); 13910 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13911 } 13912 return; 13913 } 13914 } 13915 13916 if (existing != null) { 13917 if (DEBUG_PREFERRED) { 13918 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13919 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13920 } 13921 for (int i = 0; i < existing.size(); i++) { 13922 PreferredActivity pa = existing.get(i); 13923 if (DEBUG_PREFERRED) { 13924 Slog.i(TAG, "Removing existing preferred activity " 13925 + pa.mPref.mComponent + ":"); 13926 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13927 } 13928 pir.removeFilter(pa); 13929 } 13930 } 13931 } 13932 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13933 "Replacing preferred"); 13934 } 13935 } 13936 13937 @Override 13938 public void clearPackagePreferredActivities(String packageName) { 13939 final int uid = Binder.getCallingUid(); 13940 // writer 13941 synchronized (mPackages) { 13942 PackageParser.Package pkg = mPackages.get(packageName); 13943 if (pkg == null || pkg.applicationInfo.uid != uid) { 13944 if (mContext.checkCallingOrSelfPermission( 13945 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13946 != PackageManager.PERMISSION_GRANTED) { 13947 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13948 < Build.VERSION_CODES.FROYO) { 13949 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13950 + Binder.getCallingUid()); 13951 return; 13952 } 13953 mContext.enforceCallingOrSelfPermission( 13954 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13955 } 13956 } 13957 13958 int user = UserHandle.getCallingUserId(); 13959 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13960 scheduleWritePackageRestrictionsLocked(user); 13961 } 13962 } 13963 } 13964 13965 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13966 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13967 ArrayList<PreferredActivity> removed = null; 13968 boolean changed = false; 13969 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13970 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13971 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13972 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13973 continue; 13974 } 13975 Iterator<PreferredActivity> it = pir.filterIterator(); 13976 while (it.hasNext()) { 13977 PreferredActivity pa = it.next(); 13978 // Mark entry for removal only if it matches the package name 13979 // and the entry is of type "always". 13980 if (packageName == null || 13981 (pa.mPref.mComponent.getPackageName().equals(packageName) 13982 && pa.mPref.mAlways)) { 13983 if (removed == null) { 13984 removed = new ArrayList<PreferredActivity>(); 13985 } 13986 removed.add(pa); 13987 } 13988 } 13989 if (removed != null) { 13990 for (int j=0; j<removed.size(); j++) { 13991 PreferredActivity pa = removed.get(j); 13992 pir.removeFilter(pa); 13993 } 13994 changed = true; 13995 } 13996 } 13997 return changed; 13998 } 13999 14000 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14001 private void clearIntentFilterVerificationsLPw(int userId) { 14002 final int packageCount = mPackages.size(); 14003 for (int i = 0; i < packageCount; i++) { 14004 PackageParser.Package pkg = mPackages.valueAt(i); 14005 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14006 } 14007 } 14008 14009 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14010 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14011 if (userId == UserHandle.USER_ALL) { 14012 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14013 sUserManager.getUserIds())) { 14014 for (int oneUserId : sUserManager.getUserIds()) { 14015 scheduleWritePackageRestrictionsLocked(oneUserId); 14016 } 14017 } 14018 } else { 14019 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14020 scheduleWritePackageRestrictionsLocked(userId); 14021 } 14022 } 14023 } 14024 14025 void clearDefaultBrowserIfNeeded(String packageName) { 14026 for (int oneUserId : sUserManager.getUserIds()) { 14027 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14028 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14029 if (packageName.equals(defaultBrowserPackageName)) { 14030 setDefaultBrowserPackageName(null, oneUserId); 14031 } 14032 } 14033 } 14034 14035 @Override 14036 public void resetApplicationPreferences(int userId) { 14037 mContext.enforceCallingOrSelfPermission( 14038 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14039 // writer 14040 synchronized (mPackages) { 14041 final long identity = Binder.clearCallingIdentity(); 14042 try { 14043 clearPackagePreferredActivitiesLPw(null, userId); 14044 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14045 // TODO: We have to reset the default SMS and Phone. This requires 14046 // significant refactoring to keep all default apps in the package 14047 // manager (cleaner but more work) or have the services provide 14048 // callbacks to the package manager to request a default app reset. 14049 applyFactoryDefaultBrowserLPw(userId); 14050 clearIntentFilterVerificationsLPw(userId); 14051 primeDomainVerificationsLPw(userId); 14052 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14053 scheduleWritePackageRestrictionsLocked(userId); 14054 } finally { 14055 Binder.restoreCallingIdentity(identity); 14056 } 14057 } 14058 } 14059 14060 @Override 14061 public int getPreferredActivities(List<IntentFilter> outFilters, 14062 List<ComponentName> outActivities, String packageName) { 14063 14064 int num = 0; 14065 final int userId = UserHandle.getCallingUserId(); 14066 // reader 14067 synchronized (mPackages) { 14068 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14069 if (pir != null) { 14070 final Iterator<PreferredActivity> it = pir.filterIterator(); 14071 while (it.hasNext()) { 14072 final PreferredActivity pa = it.next(); 14073 if (packageName == null 14074 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14075 && pa.mPref.mAlways)) { 14076 if (outFilters != null) { 14077 outFilters.add(new IntentFilter(pa)); 14078 } 14079 if (outActivities != null) { 14080 outActivities.add(pa.mPref.mComponent); 14081 } 14082 } 14083 } 14084 } 14085 } 14086 14087 return num; 14088 } 14089 14090 @Override 14091 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14092 int userId) { 14093 int callingUid = Binder.getCallingUid(); 14094 if (callingUid != Process.SYSTEM_UID) { 14095 throw new SecurityException( 14096 "addPersistentPreferredActivity can only be run by the system"); 14097 } 14098 if (filter.countActions() == 0) { 14099 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14100 return; 14101 } 14102 synchronized (mPackages) { 14103 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14104 " :"); 14105 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14106 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14107 new PersistentPreferredActivity(filter, activity)); 14108 scheduleWritePackageRestrictionsLocked(userId); 14109 } 14110 } 14111 14112 @Override 14113 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14114 int callingUid = Binder.getCallingUid(); 14115 if (callingUid != Process.SYSTEM_UID) { 14116 throw new SecurityException( 14117 "clearPackagePersistentPreferredActivities can only be run by the system"); 14118 } 14119 ArrayList<PersistentPreferredActivity> removed = null; 14120 boolean changed = false; 14121 synchronized (mPackages) { 14122 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14123 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14124 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14125 .valueAt(i); 14126 if (userId != thisUserId) { 14127 continue; 14128 } 14129 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14130 while (it.hasNext()) { 14131 PersistentPreferredActivity ppa = it.next(); 14132 // Mark entry for removal only if it matches the package name. 14133 if (ppa.mComponent.getPackageName().equals(packageName)) { 14134 if (removed == null) { 14135 removed = new ArrayList<PersistentPreferredActivity>(); 14136 } 14137 removed.add(ppa); 14138 } 14139 } 14140 if (removed != null) { 14141 for (int j=0; j<removed.size(); j++) { 14142 PersistentPreferredActivity ppa = removed.get(j); 14143 ppir.removeFilter(ppa); 14144 } 14145 changed = true; 14146 } 14147 } 14148 14149 if (changed) { 14150 scheduleWritePackageRestrictionsLocked(userId); 14151 } 14152 } 14153 } 14154 14155 /** 14156 * Common machinery for picking apart a restored XML blob and passing 14157 * it to a caller-supplied functor to be applied to the running system. 14158 */ 14159 private void restoreFromXml(XmlPullParser parser, int userId, 14160 String expectedStartTag, BlobXmlRestorer functor) 14161 throws IOException, XmlPullParserException { 14162 int type; 14163 while ((type = parser.next()) != XmlPullParser.START_TAG 14164 && type != XmlPullParser.END_DOCUMENT) { 14165 } 14166 if (type != XmlPullParser.START_TAG) { 14167 // oops didn't find a start tag?! 14168 if (DEBUG_BACKUP) { 14169 Slog.e(TAG, "Didn't find start tag during restore"); 14170 } 14171 return; 14172 } 14173 14174 // this is supposed to be TAG_PREFERRED_BACKUP 14175 if (!expectedStartTag.equals(parser.getName())) { 14176 if (DEBUG_BACKUP) { 14177 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14178 } 14179 return; 14180 } 14181 14182 // skip interfering stuff, then we're aligned with the backing implementation 14183 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14184 functor.apply(parser, userId); 14185 } 14186 14187 private interface BlobXmlRestorer { 14188 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14189 } 14190 14191 /** 14192 * Non-Binder method, support for the backup/restore mechanism: write the 14193 * full set of preferred activities in its canonical XML format. Returns the 14194 * XML output as a byte array, or null if there is none. 14195 */ 14196 @Override 14197 public byte[] getPreferredActivityBackup(int userId) { 14198 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14199 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14200 } 14201 14202 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14203 try { 14204 final XmlSerializer serializer = new FastXmlSerializer(); 14205 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14206 serializer.startDocument(null, true); 14207 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14208 14209 synchronized (mPackages) { 14210 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14211 } 14212 14213 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14214 serializer.endDocument(); 14215 serializer.flush(); 14216 } catch (Exception e) { 14217 if (DEBUG_BACKUP) { 14218 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14219 } 14220 return null; 14221 } 14222 14223 return dataStream.toByteArray(); 14224 } 14225 14226 @Override 14227 public void restorePreferredActivities(byte[] backup, int userId) { 14228 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14229 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14230 } 14231 14232 try { 14233 final XmlPullParser parser = Xml.newPullParser(); 14234 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14235 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14236 new BlobXmlRestorer() { 14237 @Override 14238 public void apply(XmlPullParser parser, int userId) 14239 throws XmlPullParserException, IOException { 14240 synchronized (mPackages) { 14241 mSettings.readPreferredActivitiesLPw(parser, userId); 14242 } 14243 } 14244 } ); 14245 } catch (Exception e) { 14246 if (DEBUG_BACKUP) { 14247 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14248 } 14249 } 14250 } 14251 14252 /** 14253 * Non-Binder method, support for the backup/restore mechanism: write the 14254 * default browser (etc) settings in its canonical XML format. Returns the default 14255 * browser XML representation as a byte array, or null if there is none. 14256 */ 14257 @Override 14258 public byte[] getDefaultAppsBackup(int userId) { 14259 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14260 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14261 } 14262 14263 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14264 try { 14265 final XmlSerializer serializer = new FastXmlSerializer(); 14266 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14267 serializer.startDocument(null, true); 14268 serializer.startTag(null, TAG_DEFAULT_APPS); 14269 14270 synchronized (mPackages) { 14271 mSettings.writeDefaultAppsLPr(serializer, userId); 14272 } 14273 14274 serializer.endTag(null, TAG_DEFAULT_APPS); 14275 serializer.endDocument(); 14276 serializer.flush(); 14277 } catch (Exception e) { 14278 if (DEBUG_BACKUP) { 14279 Slog.e(TAG, "Unable to write default apps for backup", e); 14280 } 14281 return null; 14282 } 14283 14284 return dataStream.toByteArray(); 14285 } 14286 14287 @Override 14288 public void restoreDefaultApps(byte[] backup, int userId) { 14289 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14290 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14291 } 14292 14293 try { 14294 final XmlPullParser parser = Xml.newPullParser(); 14295 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14296 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14297 new BlobXmlRestorer() { 14298 @Override 14299 public void apply(XmlPullParser parser, int userId) 14300 throws XmlPullParserException, IOException { 14301 synchronized (mPackages) { 14302 mSettings.readDefaultAppsLPw(parser, userId); 14303 } 14304 } 14305 } ); 14306 } catch (Exception e) { 14307 if (DEBUG_BACKUP) { 14308 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14309 } 14310 } 14311 } 14312 14313 @Override 14314 public byte[] getIntentFilterVerificationBackup(int userId) { 14315 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14316 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14317 } 14318 14319 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14320 try { 14321 final XmlSerializer serializer = new FastXmlSerializer(); 14322 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14323 serializer.startDocument(null, true); 14324 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14325 14326 synchronized (mPackages) { 14327 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14328 } 14329 14330 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14331 serializer.endDocument(); 14332 serializer.flush(); 14333 } catch (Exception e) { 14334 if (DEBUG_BACKUP) { 14335 Slog.e(TAG, "Unable to write default apps for backup", e); 14336 } 14337 return null; 14338 } 14339 14340 return dataStream.toByteArray(); 14341 } 14342 14343 @Override 14344 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14345 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14346 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14347 } 14348 14349 try { 14350 final XmlPullParser parser = Xml.newPullParser(); 14351 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14352 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14353 new BlobXmlRestorer() { 14354 @Override 14355 public void apply(XmlPullParser parser, int userId) 14356 throws XmlPullParserException, IOException { 14357 synchronized (mPackages) { 14358 mSettings.readAllDomainVerificationsLPr(parser, userId); 14359 mSettings.writeLPr(); 14360 } 14361 } 14362 } ); 14363 } catch (Exception e) { 14364 if (DEBUG_BACKUP) { 14365 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14366 } 14367 } 14368 } 14369 14370 @Override 14371 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14372 int sourceUserId, int targetUserId, int flags) { 14373 mContext.enforceCallingOrSelfPermission( 14374 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14375 int callingUid = Binder.getCallingUid(); 14376 enforceOwnerRights(ownerPackage, callingUid); 14377 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14378 if (intentFilter.countActions() == 0) { 14379 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14380 return; 14381 } 14382 synchronized (mPackages) { 14383 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14384 ownerPackage, targetUserId, flags); 14385 CrossProfileIntentResolver resolver = 14386 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14387 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14388 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14389 if (existing != null) { 14390 int size = existing.size(); 14391 for (int i = 0; i < size; i++) { 14392 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14393 return; 14394 } 14395 } 14396 } 14397 resolver.addFilter(newFilter); 14398 scheduleWritePackageRestrictionsLocked(sourceUserId); 14399 } 14400 } 14401 14402 @Override 14403 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14404 mContext.enforceCallingOrSelfPermission( 14405 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14406 int callingUid = Binder.getCallingUid(); 14407 enforceOwnerRights(ownerPackage, callingUid); 14408 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14409 synchronized (mPackages) { 14410 CrossProfileIntentResolver resolver = 14411 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14412 ArraySet<CrossProfileIntentFilter> set = 14413 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14414 for (CrossProfileIntentFilter filter : set) { 14415 if (filter.getOwnerPackage().equals(ownerPackage)) { 14416 resolver.removeFilter(filter); 14417 } 14418 } 14419 scheduleWritePackageRestrictionsLocked(sourceUserId); 14420 } 14421 } 14422 14423 // Enforcing that callingUid is owning pkg on userId 14424 private void enforceOwnerRights(String pkg, int callingUid) { 14425 // The system owns everything. 14426 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14427 return; 14428 } 14429 int callingUserId = UserHandle.getUserId(callingUid); 14430 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14431 if (pi == null) { 14432 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14433 + callingUserId); 14434 } 14435 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14436 throw new SecurityException("Calling uid " + callingUid 14437 + " does not own package " + pkg); 14438 } 14439 } 14440 14441 @Override 14442 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14443 Intent intent = new Intent(Intent.ACTION_MAIN); 14444 intent.addCategory(Intent.CATEGORY_HOME); 14445 14446 final int callingUserId = UserHandle.getCallingUserId(); 14447 List<ResolveInfo> list = queryIntentActivities(intent, null, 14448 PackageManager.GET_META_DATA, callingUserId); 14449 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14450 true, false, false, callingUserId); 14451 14452 allHomeCandidates.clear(); 14453 if (list != null) { 14454 for (ResolveInfo ri : list) { 14455 allHomeCandidates.add(ri); 14456 } 14457 } 14458 return (preferred == null || preferred.activityInfo == null) 14459 ? null 14460 : new ComponentName(preferred.activityInfo.packageName, 14461 preferred.activityInfo.name); 14462 } 14463 14464 @Override 14465 public void setApplicationEnabledSetting(String appPackageName, 14466 int newState, int flags, int userId, String callingPackage) { 14467 if (!sUserManager.exists(userId)) return; 14468 if (callingPackage == null) { 14469 callingPackage = Integer.toString(Binder.getCallingUid()); 14470 } 14471 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14472 } 14473 14474 @Override 14475 public void setComponentEnabledSetting(ComponentName componentName, 14476 int newState, int flags, int userId) { 14477 if (!sUserManager.exists(userId)) return; 14478 setEnabledSetting(componentName.getPackageName(), 14479 componentName.getClassName(), newState, flags, userId, null); 14480 } 14481 14482 private void setEnabledSetting(final String packageName, String className, int newState, 14483 final int flags, int userId, String callingPackage) { 14484 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14485 || newState == COMPONENT_ENABLED_STATE_ENABLED 14486 || newState == COMPONENT_ENABLED_STATE_DISABLED 14487 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14488 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14489 throw new IllegalArgumentException("Invalid new component state: " 14490 + newState); 14491 } 14492 PackageSetting pkgSetting; 14493 final int uid = Binder.getCallingUid(); 14494 final int permission = mContext.checkCallingOrSelfPermission( 14495 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14496 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14497 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14498 boolean sendNow = false; 14499 boolean isApp = (className == null); 14500 String componentName = isApp ? packageName : className; 14501 int packageUid = -1; 14502 ArrayList<String> components; 14503 14504 // writer 14505 synchronized (mPackages) { 14506 pkgSetting = mSettings.mPackages.get(packageName); 14507 if (pkgSetting == null) { 14508 if (className == null) { 14509 throw new IllegalArgumentException( 14510 "Unknown package: " + packageName); 14511 } 14512 throw new IllegalArgumentException( 14513 "Unknown component: " + packageName 14514 + "/" + className); 14515 } 14516 // Allow root and verify that userId is not being specified by a different user 14517 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14518 throw new SecurityException( 14519 "Permission Denial: attempt to change component state from pid=" 14520 + Binder.getCallingPid() 14521 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14522 } 14523 if (className == null) { 14524 // We're dealing with an application/package level state change 14525 if (pkgSetting.getEnabled(userId) == newState) { 14526 // Nothing to do 14527 return; 14528 } 14529 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14530 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14531 // Don't care about who enables an app. 14532 callingPackage = null; 14533 } 14534 pkgSetting.setEnabled(newState, userId, callingPackage); 14535 // pkgSetting.pkg.mSetEnabled = newState; 14536 } else { 14537 // We're dealing with a component level state change 14538 // First, verify that this is a valid class name. 14539 PackageParser.Package pkg = pkgSetting.pkg; 14540 if (pkg == null || !pkg.hasComponentClassName(className)) { 14541 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14542 throw new IllegalArgumentException("Component class " + className 14543 + " does not exist in " + packageName); 14544 } else { 14545 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14546 + className + " does not exist in " + packageName); 14547 } 14548 } 14549 switch (newState) { 14550 case COMPONENT_ENABLED_STATE_ENABLED: 14551 if (!pkgSetting.enableComponentLPw(className, userId)) { 14552 return; 14553 } 14554 break; 14555 case COMPONENT_ENABLED_STATE_DISABLED: 14556 if (!pkgSetting.disableComponentLPw(className, userId)) { 14557 return; 14558 } 14559 break; 14560 case COMPONENT_ENABLED_STATE_DEFAULT: 14561 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14562 return; 14563 } 14564 break; 14565 default: 14566 Slog.e(TAG, "Invalid new component state: " + newState); 14567 return; 14568 } 14569 } 14570 scheduleWritePackageRestrictionsLocked(userId); 14571 components = mPendingBroadcasts.get(userId, packageName); 14572 final boolean newPackage = components == null; 14573 if (newPackage) { 14574 components = new ArrayList<String>(); 14575 } 14576 if (!components.contains(componentName)) { 14577 components.add(componentName); 14578 } 14579 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14580 sendNow = true; 14581 // Purge entry from pending broadcast list if another one exists already 14582 // since we are sending one right away. 14583 mPendingBroadcasts.remove(userId, packageName); 14584 } else { 14585 if (newPackage) { 14586 mPendingBroadcasts.put(userId, packageName, components); 14587 } 14588 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14589 // Schedule a message 14590 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14591 } 14592 } 14593 } 14594 14595 long callingId = Binder.clearCallingIdentity(); 14596 try { 14597 if (sendNow) { 14598 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14599 sendPackageChangedBroadcast(packageName, 14600 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14601 } 14602 } finally { 14603 Binder.restoreCallingIdentity(callingId); 14604 } 14605 } 14606 14607 private void sendPackageChangedBroadcast(String packageName, 14608 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14609 if (DEBUG_INSTALL) 14610 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14611 + componentNames); 14612 Bundle extras = new Bundle(4); 14613 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14614 String nameList[] = new String[componentNames.size()]; 14615 componentNames.toArray(nameList); 14616 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14617 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14618 extras.putInt(Intent.EXTRA_UID, packageUid); 14619 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14620 new int[] {UserHandle.getUserId(packageUid)}); 14621 } 14622 14623 @Override 14624 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14625 if (!sUserManager.exists(userId)) return; 14626 final int uid = Binder.getCallingUid(); 14627 final int permission = mContext.checkCallingOrSelfPermission( 14628 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14629 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14630 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14631 // writer 14632 synchronized (mPackages) { 14633 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14634 allowedByPermission, uid, userId)) { 14635 scheduleWritePackageRestrictionsLocked(userId); 14636 } 14637 } 14638 } 14639 14640 @Override 14641 public String getInstallerPackageName(String packageName) { 14642 // reader 14643 synchronized (mPackages) { 14644 return mSettings.getInstallerPackageNameLPr(packageName); 14645 } 14646 } 14647 14648 @Override 14649 public int getApplicationEnabledSetting(String packageName, int userId) { 14650 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14651 int uid = Binder.getCallingUid(); 14652 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14653 // reader 14654 synchronized (mPackages) { 14655 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14656 } 14657 } 14658 14659 @Override 14660 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14661 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14662 int uid = Binder.getCallingUid(); 14663 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14664 // reader 14665 synchronized (mPackages) { 14666 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14667 } 14668 } 14669 14670 @Override 14671 public void enterSafeMode() { 14672 enforceSystemOrRoot("Only the system can request entering safe mode"); 14673 14674 if (!mSystemReady) { 14675 mSafeMode = true; 14676 } 14677 } 14678 14679 @Override 14680 public void systemReady() { 14681 mSystemReady = true; 14682 14683 // Read the compatibilty setting when the system is ready. 14684 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14685 mContext.getContentResolver(), 14686 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14687 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14688 if (DEBUG_SETTINGS) { 14689 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14690 } 14691 14692 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14693 14694 synchronized (mPackages) { 14695 // Verify that all of the preferred activity components actually 14696 // exist. It is possible for applications to be updated and at 14697 // that point remove a previously declared activity component that 14698 // had been set as a preferred activity. We try to clean this up 14699 // the next time we encounter that preferred activity, but it is 14700 // possible for the user flow to never be able to return to that 14701 // situation so here we do a sanity check to make sure we haven't 14702 // left any junk around. 14703 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14704 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14705 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14706 removed.clear(); 14707 for (PreferredActivity pa : pir.filterSet()) { 14708 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14709 removed.add(pa); 14710 } 14711 } 14712 if (removed.size() > 0) { 14713 for (int r=0; r<removed.size(); r++) { 14714 PreferredActivity pa = removed.get(r); 14715 Slog.w(TAG, "Removing dangling preferred activity: " 14716 + pa.mPref.mComponent); 14717 pir.removeFilter(pa); 14718 } 14719 mSettings.writePackageRestrictionsLPr( 14720 mSettings.mPreferredActivities.keyAt(i)); 14721 } 14722 } 14723 14724 for (int userId : UserManagerService.getInstance().getUserIds()) { 14725 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14726 grantPermissionsUserIds = ArrayUtils.appendInt( 14727 grantPermissionsUserIds, userId); 14728 } 14729 } 14730 } 14731 sUserManager.systemReady(); 14732 14733 // If we upgraded grant all default permissions before kicking off. 14734 for (int userId : grantPermissionsUserIds) { 14735 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14736 } 14737 14738 // Kick off any messages waiting for system ready 14739 if (mPostSystemReadyMessages != null) { 14740 for (Message msg : mPostSystemReadyMessages) { 14741 msg.sendToTarget(); 14742 } 14743 mPostSystemReadyMessages = null; 14744 } 14745 14746 // Watch for external volumes that come and go over time 14747 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14748 storage.registerListener(mStorageListener); 14749 14750 mInstallerService.systemReady(); 14751 mPackageDexOptimizer.systemReady(); 14752 14753 MountServiceInternal mountServiceInternal = LocalServices.getService( 14754 MountServiceInternal.class); 14755 mountServiceInternal.addExternalStoragePolicy( 14756 new MountServiceInternal.ExternalStorageMountPolicy() { 14757 @Override 14758 public int getMountMode(int uid, String packageName) { 14759 if (Process.isIsolated(uid)) { 14760 return Zygote.MOUNT_EXTERNAL_NONE; 14761 } 14762 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14763 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14764 } 14765 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14766 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14767 } 14768 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14769 return Zygote.MOUNT_EXTERNAL_READ; 14770 } 14771 return Zygote.MOUNT_EXTERNAL_WRITE; 14772 } 14773 14774 @Override 14775 public boolean hasExternalStorage(int uid, String packageName) { 14776 return true; 14777 } 14778 }); 14779 } 14780 14781 @Override 14782 public boolean isSafeMode() { 14783 return mSafeMode; 14784 } 14785 14786 @Override 14787 public boolean hasSystemUidErrors() { 14788 return mHasSystemUidErrors; 14789 } 14790 14791 static String arrayToString(int[] array) { 14792 StringBuffer buf = new StringBuffer(128); 14793 buf.append('['); 14794 if (array != null) { 14795 for (int i=0; i<array.length; i++) { 14796 if (i > 0) buf.append(", "); 14797 buf.append(array[i]); 14798 } 14799 } 14800 buf.append(']'); 14801 return buf.toString(); 14802 } 14803 14804 static class DumpState { 14805 public static final int DUMP_LIBS = 1 << 0; 14806 public static final int DUMP_FEATURES = 1 << 1; 14807 public static final int DUMP_RESOLVERS = 1 << 2; 14808 public static final int DUMP_PERMISSIONS = 1 << 3; 14809 public static final int DUMP_PACKAGES = 1 << 4; 14810 public static final int DUMP_SHARED_USERS = 1 << 5; 14811 public static final int DUMP_MESSAGES = 1 << 6; 14812 public static final int DUMP_PROVIDERS = 1 << 7; 14813 public static final int DUMP_VERIFIERS = 1 << 8; 14814 public static final int DUMP_PREFERRED = 1 << 9; 14815 public static final int DUMP_PREFERRED_XML = 1 << 10; 14816 public static final int DUMP_KEYSETS = 1 << 11; 14817 public static final int DUMP_VERSION = 1 << 12; 14818 public static final int DUMP_INSTALLS = 1 << 13; 14819 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14820 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14821 14822 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14823 14824 private int mTypes; 14825 14826 private int mOptions; 14827 14828 private boolean mTitlePrinted; 14829 14830 private SharedUserSetting mSharedUser; 14831 14832 public boolean isDumping(int type) { 14833 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14834 return true; 14835 } 14836 14837 return (mTypes & type) != 0; 14838 } 14839 14840 public void setDump(int type) { 14841 mTypes |= type; 14842 } 14843 14844 public boolean isOptionEnabled(int option) { 14845 return (mOptions & option) != 0; 14846 } 14847 14848 public void setOptionEnabled(int option) { 14849 mOptions |= option; 14850 } 14851 14852 public boolean onTitlePrinted() { 14853 final boolean printed = mTitlePrinted; 14854 mTitlePrinted = true; 14855 return printed; 14856 } 14857 14858 public boolean getTitlePrinted() { 14859 return mTitlePrinted; 14860 } 14861 14862 public void setTitlePrinted(boolean enabled) { 14863 mTitlePrinted = enabled; 14864 } 14865 14866 public SharedUserSetting getSharedUser() { 14867 return mSharedUser; 14868 } 14869 14870 public void setSharedUser(SharedUserSetting user) { 14871 mSharedUser = user; 14872 } 14873 } 14874 14875 @Override 14876 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14877 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14878 != PackageManager.PERMISSION_GRANTED) { 14879 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14880 + Binder.getCallingPid() 14881 + ", uid=" + Binder.getCallingUid() 14882 + " without permission " 14883 + android.Manifest.permission.DUMP); 14884 return; 14885 } 14886 14887 DumpState dumpState = new DumpState(); 14888 boolean fullPreferred = false; 14889 boolean checkin = false; 14890 14891 String packageName = null; 14892 ArraySet<String> permissionNames = null; 14893 14894 int opti = 0; 14895 while (opti < args.length) { 14896 String opt = args[opti]; 14897 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14898 break; 14899 } 14900 opti++; 14901 14902 if ("-a".equals(opt)) { 14903 // Right now we only know how to print all. 14904 } else if ("-h".equals(opt)) { 14905 pw.println("Package manager dump options:"); 14906 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14907 pw.println(" --checkin: dump for a checkin"); 14908 pw.println(" -f: print details of intent filters"); 14909 pw.println(" -h: print this help"); 14910 pw.println(" cmd may be one of:"); 14911 pw.println(" l[ibraries]: list known shared libraries"); 14912 pw.println(" f[ibraries]: list device features"); 14913 pw.println(" k[eysets]: print known keysets"); 14914 pw.println(" r[esolvers]: dump intent resolvers"); 14915 pw.println(" perm[issions]: dump permissions"); 14916 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14917 pw.println(" pref[erred]: print preferred package settings"); 14918 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14919 pw.println(" prov[iders]: dump content providers"); 14920 pw.println(" p[ackages]: dump installed packages"); 14921 pw.println(" s[hared-users]: dump shared user IDs"); 14922 pw.println(" m[essages]: print collected runtime messages"); 14923 pw.println(" v[erifiers]: print package verifier info"); 14924 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14925 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14926 pw.println(" version: print database version info"); 14927 pw.println(" write: write current settings now"); 14928 pw.println(" installs: details about install sessions"); 14929 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14930 pw.println(" <package.name>: info about given package"); 14931 return; 14932 } else if ("--checkin".equals(opt)) { 14933 checkin = true; 14934 } else if ("-f".equals(opt)) { 14935 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14936 } else { 14937 pw.println("Unknown argument: " + opt + "; use -h for help"); 14938 } 14939 } 14940 14941 // Is the caller requesting to dump a particular piece of data? 14942 if (opti < args.length) { 14943 String cmd = args[opti]; 14944 opti++; 14945 // Is this a package name? 14946 if ("android".equals(cmd) || cmd.contains(".")) { 14947 packageName = cmd; 14948 // When dumping a single package, we always dump all of its 14949 // filter information since the amount of data will be reasonable. 14950 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14951 } else if ("check-permission".equals(cmd)) { 14952 if (opti >= args.length) { 14953 pw.println("Error: check-permission missing permission argument"); 14954 return; 14955 } 14956 String perm = args[opti]; 14957 opti++; 14958 if (opti >= args.length) { 14959 pw.println("Error: check-permission missing package argument"); 14960 return; 14961 } 14962 String pkg = args[opti]; 14963 opti++; 14964 int user = UserHandle.getUserId(Binder.getCallingUid()); 14965 if (opti < args.length) { 14966 try { 14967 user = Integer.parseInt(args[opti]); 14968 } catch (NumberFormatException e) { 14969 pw.println("Error: check-permission user argument is not a number: " 14970 + args[opti]); 14971 return; 14972 } 14973 } 14974 pw.println(checkPermission(perm, pkg, user)); 14975 return; 14976 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14977 dumpState.setDump(DumpState.DUMP_LIBS); 14978 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14979 dumpState.setDump(DumpState.DUMP_FEATURES); 14980 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14981 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14982 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14983 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14984 } else if ("permission".equals(cmd)) { 14985 if (opti >= args.length) { 14986 pw.println("Error: permission requires permission name"); 14987 return; 14988 } 14989 permissionNames = new ArraySet<>(); 14990 while (opti < args.length) { 14991 permissionNames.add(args[opti]); 14992 opti++; 14993 } 14994 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14995 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14996 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14997 dumpState.setDump(DumpState.DUMP_PREFERRED); 14998 } else if ("preferred-xml".equals(cmd)) { 14999 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15000 if (opti < args.length && "--full".equals(args[opti])) { 15001 fullPreferred = true; 15002 opti++; 15003 } 15004 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15005 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15006 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15007 dumpState.setDump(DumpState.DUMP_PACKAGES); 15008 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15009 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15010 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15011 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15012 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15013 dumpState.setDump(DumpState.DUMP_MESSAGES); 15014 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15015 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15016 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15017 || "intent-filter-verifiers".equals(cmd)) { 15018 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15019 } else if ("version".equals(cmd)) { 15020 dumpState.setDump(DumpState.DUMP_VERSION); 15021 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15022 dumpState.setDump(DumpState.DUMP_KEYSETS); 15023 } else if ("installs".equals(cmd)) { 15024 dumpState.setDump(DumpState.DUMP_INSTALLS); 15025 } else if ("write".equals(cmd)) { 15026 synchronized (mPackages) { 15027 mSettings.writeLPr(); 15028 pw.println("Settings written."); 15029 return; 15030 } 15031 } 15032 } 15033 15034 if (checkin) { 15035 pw.println("vers,1"); 15036 } 15037 15038 // reader 15039 synchronized (mPackages) { 15040 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15041 if (!checkin) { 15042 if (dumpState.onTitlePrinted()) 15043 pw.println(); 15044 pw.println("Database versions:"); 15045 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15046 } 15047 } 15048 15049 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15050 if (!checkin) { 15051 if (dumpState.onTitlePrinted()) 15052 pw.println(); 15053 pw.println("Verifiers:"); 15054 pw.print(" Required: "); 15055 pw.print(mRequiredVerifierPackage); 15056 pw.print(" (uid="); 15057 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15058 pw.println(")"); 15059 } else if (mRequiredVerifierPackage != null) { 15060 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15061 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15062 } 15063 } 15064 15065 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15066 packageName == null) { 15067 if (mIntentFilterVerifierComponent != null) { 15068 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15069 if (!checkin) { 15070 if (dumpState.onTitlePrinted()) 15071 pw.println(); 15072 pw.println("Intent Filter Verifier:"); 15073 pw.print(" Using: "); 15074 pw.print(verifierPackageName); 15075 pw.print(" (uid="); 15076 pw.print(getPackageUid(verifierPackageName, 0)); 15077 pw.println(")"); 15078 } else if (verifierPackageName != null) { 15079 pw.print("ifv,"); pw.print(verifierPackageName); 15080 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15081 } 15082 } else { 15083 pw.println(); 15084 pw.println("No Intent Filter Verifier available!"); 15085 } 15086 } 15087 15088 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15089 boolean printedHeader = false; 15090 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15091 while (it.hasNext()) { 15092 String name = it.next(); 15093 SharedLibraryEntry ent = mSharedLibraries.get(name); 15094 if (!checkin) { 15095 if (!printedHeader) { 15096 if (dumpState.onTitlePrinted()) 15097 pw.println(); 15098 pw.println("Libraries:"); 15099 printedHeader = true; 15100 } 15101 pw.print(" "); 15102 } else { 15103 pw.print("lib,"); 15104 } 15105 pw.print(name); 15106 if (!checkin) { 15107 pw.print(" -> "); 15108 } 15109 if (ent.path != null) { 15110 if (!checkin) { 15111 pw.print("(jar) "); 15112 pw.print(ent.path); 15113 } else { 15114 pw.print(",jar,"); 15115 pw.print(ent.path); 15116 } 15117 } else { 15118 if (!checkin) { 15119 pw.print("(apk) "); 15120 pw.print(ent.apk); 15121 } else { 15122 pw.print(",apk,"); 15123 pw.print(ent.apk); 15124 } 15125 } 15126 pw.println(); 15127 } 15128 } 15129 15130 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15131 if (dumpState.onTitlePrinted()) 15132 pw.println(); 15133 if (!checkin) { 15134 pw.println("Features:"); 15135 } 15136 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15137 while (it.hasNext()) { 15138 String name = it.next(); 15139 if (!checkin) { 15140 pw.print(" "); 15141 } else { 15142 pw.print("feat,"); 15143 } 15144 pw.println(name); 15145 } 15146 } 15147 15148 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15149 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15150 : "Activity Resolver Table:", " ", packageName, 15151 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15152 dumpState.setTitlePrinted(true); 15153 } 15154 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15155 : "Receiver Resolver Table:", " ", packageName, 15156 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15157 dumpState.setTitlePrinted(true); 15158 } 15159 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15160 : "Service Resolver Table:", " ", packageName, 15161 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15162 dumpState.setTitlePrinted(true); 15163 } 15164 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15165 : "Provider Resolver Table:", " ", packageName, 15166 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15167 dumpState.setTitlePrinted(true); 15168 } 15169 } 15170 15171 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15172 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15173 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15174 int user = mSettings.mPreferredActivities.keyAt(i); 15175 if (pir.dump(pw, 15176 dumpState.getTitlePrinted() 15177 ? "\nPreferred Activities User " + user + ":" 15178 : "Preferred Activities User " + user + ":", " ", 15179 packageName, true, false)) { 15180 dumpState.setTitlePrinted(true); 15181 } 15182 } 15183 } 15184 15185 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15186 pw.flush(); 15187 FileOutputStream fout = new FileOutputStream(fd); 15188 BufferedOutputStream str = new BufferedOutputStream(fout); 15189 XmlSerializer serializer = new FastXmlSerializer(); 15190 try { 15191 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15192 serializer.startDocument(null, true); 15193 serializer.setFeature( 15194 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15195 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15196 serializer.endDocument(); 15197 serializer.flush(); 15198 } catch (IllegalArgumentException e) { 15199 pw.println("Failed writing: " + e); 15200 } catch (IllegalStateException e) { 15201 pw.println("Failed writing: " + e); 15202 } catch (IOException e) { 15203 pw.println("Failed writing: " + e); 15204 } 15205 } 15206 15207 if (!checkin 15208 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15209 && packageName == null) { 15210 pw.println(); 15211 int count = mSettings.mPackages.size(); 15212 if (count == 0) { 15213 pw.println("No applications!"); 15214 pw.println(); 15215 } else { 15216 final String prefix = " "; 15217 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15218 if (allPackageSettings.size() == 0) { 15219 pw.println("No domain preferred apps!"); 15220 pw.println(); 15221 } else { 15222 pw.println("App verification status:"); 15223 pw.println(); 15224 count = 0; 15225 for (PackageSetting ps : allPackageSettings) { 15226 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15227 if (ivi == null || ivi.getPackageName() == null) continue; 15228 pw.println(prefix + "Package: " + ivi.getPackageName()); 15229 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15230 pw.println(prefix + "Status: " + ivi.getStatusString()); 15231 pw.println(); 15232 count++; 15233 } 15234 if (count == 0) { 15235 pw.println(prefix + "No app verification established."); 15236 pw.println(); 15237 } 15238 for (int userId : sUserManager.getUserIds()) { 15239 pw.println("App linkages for user " + userId + ":"); 15240 pw.println(); 15241 count = 0; 15242 for (PackageSetting ps : allPackageSettings) { 15243 final long status = ps.getDomainVerificationStatusForUser(userId); 15244 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15245 continue; 15246 } 15247 pw.println(prefix + "Package: " + ps.name); 15248 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15249 String statusStr = IntentFilterVerificationInfo. 15250 getStatusStringFromValue(status); 15251 pw.println(prefix + "Status: " + statusStr); 15252 pw.println(); 15253 count++; 15254 } 15255 if (count == 0) { 15256 pw.println(prefix + "No configured app linkages."); 15257 pw.println(); 15258 } 15259 } 15260 } 15261 } 15262 } 15263 15264 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15265 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15266 if (packageName == null && permissionNames == null) { 15267 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15268 if (iperm == 0) { 15269 if (dumpState.onTitlePrinted()) 15270 pw.println(); 15271 pw.println("AppOp Permissions:"); 15272 } 15273 pw.print(" AppOp Permission "); 15274 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15275 pw.println(":"); 15276 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15277 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15278 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15279 } 15280 } 15281 } 15282 } 15283 15284 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15285 boolean printedSomething = false; 15286 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15287 if (packageName != null && !packageName.equals(p.info.packageName)) { 15288 continue; 15289 } 15290 if (!printedSomething) { 15291 if (dumpState.onTitlePrinted()) 15292 pw.println(); 15293 pw.println("Registered ContentProviders:"); 15294 printedSomething = true; 15295 } 15296 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15297 pw.print(" "); pw.println(p.toString()); 15298 } 15299 printedSomething = false; 15300 for (Map.Entry<String, PackageParser.Provider> entry : 15301 mProvidersByAuthority.entrySet()) { 15302 PackageParser.Provider p = entry.getValue(); 15303 if (packageName != null && !packageName.equals(p.info.packageName)) { 15304 continue; 15305 } 15306 if (!printedSomething) { 15307 if (dumpState.onTitlePrinted()) 15308 pw.println(); 15309 pw.println("ContentProvider Authorities:"); 15310 printedSomething = true; 15311 } 15312 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15313 pw.print(" "); pw.println(p.toString()); 15314 if (p.info != null && p.info.applicationInfo != null) { 15315 final String appInfo = p.info.applicationInfo.toString(); 15316 pw.print(" applicationInfo="); pw.println(appInfo); 15317 } 15318 } 15319 } 15320 15321 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15322 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15323 } 15324 15325 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15326 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15327 } 15328 15329 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15330 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15331 } 15332 15333 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15334 // XXX should handle packageName != null by dumping only install data that 15335 // the given package is involved with. 15336 if (dumpState.onTitlePrinted()) pw.println(); 15337 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15338 } 15339 15340 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15341 if (dumpState.onTitlePrinted()) pw.println(); 15342 mSettings.dumpReadMessagesLPr(pw, dumpState); 15343 15344 pw.println(); 15345 pw.println("Package warning messages:"); 15346 BufferedReader in = null; 15347 String line = null; 15348 try { 15349 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15350 while ((line = in.readLine()) != null) { 15351 if (line.contains("ignored: updated version")) continue; 15352 pw.println(line); 15353 } 15354 } catch (IOException ignored) { 15355 } finally { 15356 IoUtils.closeQuietly(in); 15357 } 15358 } 15359 15360 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15361 BufferedReader in = null; 15362 String line = null; 15363 try { 15364 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15365 while ((line = in.readLine()) != null) { 15366 if (line.contains("ignored: updated version")) continue; 15367 pw.print("msg,"); 15368 pw.println(line); 15369 } 15370 } catch (IOException ignored) { 15371 } finally { 15372 IoUtils.closeQuietly(in); 15373 } 15374 } 15375 } 15376 } 15377 15378 private String dumpDomainString(String packageName) { 15379 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15380 List<IntentFilter> filters = getAllIntentFilters(packageName); 15381 15382 ArraySet<String> result = new ArraySet<>(); 15383 if (iviList.size() > 0) { 15384 for (IntentFilterVerificationInfo ivi : iviList) { 15385 for (String host : ivi.getDomains()) { 15386 result.add(host); 15387 } 15388 } 15389 } 15390 if (filters != null && filters.size() > 0) { 15391 for (IntentFilter filter : filters) { 15392 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15393 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15394 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15395 result.addAll(filter.getHostsList()); 15396 } 15397 } 15398 } 15399 15400 StringBuilder sb = new StringBuilder(result.size() * 16); 15401 for (String domain : result) { 15402 if (sb.length() > 0) sb.append(" "); 15403 sb.append(domain); 15404 } 15405 return sb.toString(); 15406 } 15407 15408 // ------- apps on sdcard specific code ------- 15409 static final boolean DEBUG_SD_INSTALL = false; 15410 15411 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15412 15413 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15414 15415 private boolean mMediaMounted = false; 15416 15417 static String getEncryptKey() { 15418 try { 15419 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15420 SD_ENCRYPTION_KEYSTORE_NAME); 15421 if (sdEncKey == null) { 15422 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15423 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15424 if (sdEncKey == null) { 15425 Slog.e(TAG, "Failed to create encryption keys"); 15426 return null; 15427 } 15428 } 15429 return sdEncKey; 15430 } catch (NoSuchAlgorithmException nsae) { 15431 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15432 return null; 15433 } catch (IOException ioe) { 15434 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15435 return null; 15436 } 15437 } 15438 15439 /* 15440 * Update media status on PackageManager. 15441 */ 15442 @Override 15443 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15444 int callingUid = Binder.getCallingUid(); 15445 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15446 throw new SecurityException("Media status can only be updated by the system"); 15447 } 15448 // reader; this apparently protects mMediaMounted, but should probably 15449 // be a different lock in that case. 15450 synchronized (mPackages) { 15451 Log.i(TAG, "Updating external media status from " 15452 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15453 + (mediaStatus ? "mounted" : "unmounted")); 15454 if (DEBUG_SD_INSTALL) 15455 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15456 + ", mMediaMounted=" + mMediaMounted); 15457 if (mediaStatus == mMediaMounted) { 15458 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15459 : 0, -1); 15460 mHandler.sendMessage(msg); 15461 return; 15462 } 15463 mMediaMounted = mediaStatus; 15464 } 15465 // Queue up an async operation since the package installation may take a 15466 // little while. 15467 mHandler.post(new Runnable() { 15468 public void run() { 15469 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15470 } 15471 }); 15472 } 15473 15474 /** 15475 * Called by MountService when the initial ASECs to scan are available. 15476 * Should block until all the ASEC containers are finished being scanned. 15477 */ 15478 public void scanAvailableAsecs() { 15479 updateExternalMediaStatusInner(true, false, false); 15480 if (mShouldRestoreconData) { 15481 SELinuxMMAC.setRestoreconDone(); 15482 mShouldRestoreconData = false; 15483 } 15484 } 15485 15486 /* 15487 * Collect information of applications on external media, map them against 15488 * existing containers and update information based on current mount status. 15489 * Please note that we always have to report status if reportStatus has been 15490 * set to true especially when unloading packages. 15491 */ 15492 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15493 boolean externalStorage) { 15494 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15495 int[] uidArr = EmptyArray.INT; 15496 15497 final String[] list = PackageHelper.getSecureContainerList(); 15498 if (ArrayUtils.isEmpty(list)) { 15499 Log.i(TAG, "No secure containers found"); 15500 } else { 15501 // Process list of secure containers and categorize them 15502 // as active or stale based on their package internal state. 15503 15504 // reader 15505 synchronized (mPackages) { 15506 for (String cid : list) { 15507 // Leave stages untouched for now; installer service owns them 15508 if (PackageInstallerService.isStageName(cid)) continue; 15509 15510 if (DEBUG_SD_INSTALL) 15511 Log.i(TAG, "Processing container " + cid); 15512 String pkgName = getAsecPackageName(cid); 15513 if (pkgName == null) { 15514 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15515 continue; 15516 } 15517 if (DEBUG_SD_INSTALL) 15518 Log.i(TAG, "Looking for pkg : " + pkgName); 15519 15520 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15521 if (ps == null) { 15522 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15523 continue; 15524 } 15525 15526 /* 15527 * Skip packages that are not external if we're unmounting 15528 * external storage. 15529 */ 15530 if (externalStorage && !isMounted && !isExternal(ps)) { 15531 continue; 15532 } 15533 15534 final AsecInstallArgs args = new AsecInstallArgs(cid, 15535 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15536 // The package status is changed only if the code path 15537 // matches between settings and the container id. 15538 if (ps.codePathString != null 15539 && ps.codePathString.startsWith(args.getCodePath())) { 15540 if (DEBUG_SD_INSTALL) { 15541 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15542 + " at code path: " + ps.codePathString); 15543 } 15544 15545 // We do have a valid package installed on sdcard 15546 processCids.put(args, ps.codePathString); 15547 final int uid = ps.appId; 15548 if (uid != -1) { 15549 uidArr = ArrayUtils.appendInt(uidArr, uid); 15550 } 15551 } else { 15552 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15553 + ps.codePathString); 15554 } 15555 } 15556 } 15557 15558 Arrays.sort(uidArr); 15559 } 15560 15561 // Process packages with valid entries. 15562 if (isMounted) { 15563 if (DEBUG_SD_INSTALL) 15564 Log.i(TAG, "Loading packages"); 15565 loadMediaPackages(processCids, uidArr); 15566 startCleaningPackages(); 15567 mInstallerService.onSecureContainersAvailable(); 15568 } else { 15569 if (DEBUG_SD_INSTALL) 15570 Log.i(TAG, "Unloading packages"); 15571 unloadMediaPackages(processCids, uidArr, reportStatus); 15572 } 15573 } 15574 15575 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15576 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15577 final int size = infos.size(); 15578 final String[] packageNames = new String[size]; 15579 final int[] packageUids = new int[size]; 15580 for (int i = 0; i < size; i++) { 15581 final ApplicationInfo info = infos.get(i); 15582 packageNames[i] = info.packageName; 15583 packageUids[i] = info.uid; 15584 } 15585 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15586 finishedReceiver); 15587 } 15588 15589 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15590 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15591 sendResourcesChangedBroadcast(mediaStatus, replacing, 15592 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15593 } 15594 15595 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15596 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15597 int size = pkgList.length; 15598 if (size > 0) { 15599 // Send broadcasts here 15600 Bundle extras = new Bundle(); 15601 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15602 if (uidArr != null) { 15603 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15604 } 15605 if (replacing) { 15606 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15607 } 15608 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15609 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15610 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15611 } 15612 } 15613 15614 /* 15615 * Look at potentially valid container ids from processCids If package 15616 * information doesn't match the one on record or package scanning fails, 15617 * the cid is added to list of removeCids. We currently don't delete stale 15618 * containers. 15619 */ 15620 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15621 ArrayList<String> pkgList = new ArrayList<String>(); 15622 Set<AsecInstallArgs> keys = processCids.keySet(); 15623 15624 for (AsecInstallArgs args : keys) { 15625 String codePath = processCids.get(args); 15626 if (DEBUG_SD_INSTALL) 15627 Log.i(TAG, "Loading container : " + args.cid); 15628 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15629 try { 15630 // Make sure there are no container errors first. 15631 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15632 Slog.e(TAG, "Failed to mount cid : " + args.cid 15633 + " when installing from sdcard"); 15634 continue; 15635 } 15636 // Check code path here. 15637 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15638 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15639 + " does not match one in settings " + codePath); 15640 continue; 15641 } 15642 // Parse package 15643 int parseFlags = mDefParseFlags; 15644 if (args.isExternalAsec()) { 15645 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15646 } 15647 if (args.isFwdLocked()) { 15648 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15649 } 15650 15651 synchronized (mInstallLock) { 15652 PackageParser.Package pkg = null; 15653 try { 15654 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15655 } catch (PackageManagerException e) { 15656 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15657 } 15658 // Scan the package 15659 if (pkg != null) { 15660 /* 15661 * TODO why is the lock being held? doPostInstall is 15662 * called in other places without the lock. This needs 15663 * to be straightened out. 15664 */ 15665 // writer 15666 synchronized (mPackages) { 15667 retCode = PackageManager.INSTALL_SUCCEEDED; 15668 pkgList.add(pkg.packageName); 15669 // Post process args 15670 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15671 pkg.applicationInfo.uid); 15672 } 15673 } else { 15674 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15675 } 15676 } 15677 15678 } finally { 15679 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15680 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15681 } 15682 } 15683 } 15684 // writer 15685 synchronized (mPackages) { 15686 // If the platform SDK has changed since the last time we booted, 15687 // we need to re-grant app permission to catch any new ones that 15688 // appear. This is really a hack, and means that apps can in some 15689 // cases get permissions that the user didn't initially explicitly 15690 // allow... it would be nice to have some better way to handle 15691 // this situation. 15692 final VersionInfo ver = mSettings.getExternalVersion(); 15693 15694 int updateFlags = UPDATE_PERMISSIONS_ALL; 15695 if (ver.sdkVersion != mSdkVersion) { 15696 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15697 + mSdkVersion + "; regranting permissions for external"); 15698 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15699 } 15700 updatePermissionsLPw(null, null, updateFlags); 15701 15702 // Yay, everything is now upgraded 15703 ver.forceCurrent(); 15704 15705 // can downgrade to reader 15706 // Persist settings 15707 mSettings.writeLPr(); 15708 } 15709 // Send a broadcast to let everyone know we are done processing 15710 if (pkgList.size() > 0) { 15711 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15712 } 15713 } 15714 15715 /* 15716 * Utility method to unload a list of specified containers 15717 */ 15718 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15719 // Just unmount all valid containers. 15720 for (AsecInstallArgs arg : cidArgs) { 15721 synchronized (mInstallLock) { 15722 arg.doPostDeleteLI(false); 15723 } 15724 } 15725 } 15726 15727 /* 15728 * Unload packages mounted on external media. This involves deleting package 15729 * data from internal structures, sending broadcasts about diabled packages, 15730 * gc'ing to free up references, unmounting all secure containers 15731 * corresponding to packages on external media, and posting a 15732 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15733 * that we always have to post this message if status has been requested no 15734 * matter what. 15735 */ 15736 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15737 final boolean reportStatus) { 15738 if (DEBUG_SD_INSTALL) 15739 Log.i(TAG, "unloading media packages"); 15740 ArrayList<String> pkgList = new ArrayList<String>(); 15741 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15742 final Set<AsecInstallArgs> keys = processCids.keySet(); 15743 for (AsecInstallArgs args : keys) { 15744 String pkgName = args.getPackageName(); 15745 if (DEBUG_SD_INSTALL) 15746 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15747 // Delete package internally 15748 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15749 synchronized (mInstallLock) { 15750 boolean res = deletePackageLI(pkgName, null, false, null, null, 15751 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15752 if (res) { 15753 pkgList.add(pkgName); 15754 } else { 15755 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15756 failedList.add(args); 15757 } 15758 } 15759 } 15760 15761 // reader 15762 synchronized (mPackages) { 15763 // We didn't update the settings after removing each package; 15764 // write them now for all packages. 15765 mSettings.writeLPr(); 15766 } 15767 15768 // We have to absolutely send UPDATED_MEDIA_STATUS only 15769 // after confirming that all the receivers processed the ordered 15770 // broadcast when packages get disabled, force a gc to clean things up. 15771 // and unload all the containers. 15772 if (pkgList.size() > 0) { 15773 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15774 new IIntentReceiver.Stub() { 15775 public void performReceive(Intent intent, int resultCode, String data, 15776 Bundle extras, boolean ordered, boolean sticky, 15777 int sendingUser) throws RemoteException { 15778 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15779 reportStatus ? 1 : 0, 1, keys); 15780 mHandler.sendMessage(msg); 15781 } 15782 }); 15783 } else { 15784 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15785 keys); 15786 mHandler.sendMessage(msg); 15787 } 15788 } 15789 15790 private void loadPrivatePackages(VolumeInfo vol) { 15791 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15792 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15793 synchronized (mInstallLock) { 15794 synchronized (mPackages) { 15795 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15796 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15797 for (PackageSetting ps : packages) { 15798 final PackageParser.Package pkg; 15799 try { 15800 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15801 loaded.add(pkg.applicationInfo); 15802 } catch (PackageManagerException e) { 15803 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15804 } 15805 15806 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15807 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15808 } 15809 } 15810 15811 int updateFlags = UPDATE_PERMISSIONS_ALL; 15812 if (ver.sdkVersion != mSdkVersion) { 15813 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15814 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15815 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15816 } 15817 updatePermissionsLPw(null, null, updateFlags); 15818 15819 // Yay, everything is now upgraded 15820 ver.forceCurrent(); 15821 15822 mSettings.writeLPr(); 15823 } 15824 } 15825 15826 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15827 sendResourcesChangedBroadcast(true, false, loaded, null); 15828 } 15829 15830 private void unloadPrivatePackages(VolumeInfo vol) { 15831 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15832 synchronized (mInstallLock) { 15833 synchronized (mPackages) { 15834 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15835 for (PackageSetting ps : packages) { 15836 if (ps.pkg == null) continue; 15837 15838 final ApplicationInfo info = ps.pkg.applicationInfo; 15839 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15840 if (deletePackageLI(ps.name, null, false, null, null, 15841 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15842 unloaded.add(info); 15843 } else { 15844 Slog.w(TAG, "Failed to unload " + ps.codePath); 15845 } 15846 } 15847 15848 mSettings.writeLPr(); 15849 } 15850 } 15851 15852 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15853 sendResourcesChangedBroadcast(false, false, unloaded, null); 15854 } 15855 15856 /** 15857 * Examine all users present on given mounted volume, and destroy data 15858 * belonging to users that are no longer valid, or whose user ID has been 15859 * recycled. 15860 */ 15861 private void reconcileUsers(String volumeUuid) { 15862 final File[] files = FileUtils 15863 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15864 for (File file : files) { 15865 if (!file.isDirectory()) continue; 15866 15867 final int userId; 15868 final UserInfo info; 15869 try { 15870 userId = Integer.parseInt(file.getName()); 15871 info = sUserManager.getUserInfo(userId); 15872 } catch (NumberFormatException e) { 15873 Slog.w(TAG, "Invalid user directory " + file); 15874 continue; 15875 } 15876 15877 boolean destroyUser = false; 15878 if (info == null) { 15879 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15880 + " because no matching user was found"); 15881 destroyUser = true; 15882 } else { 15883 try { 15884 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15885 } catch (IOException e) { 15886 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15887 + " because we failed to enforce serial number: " + e); 15888 destroyUser = true; 15889 } 15890 } 15891 15892 if (destroyUser) { 15893 synchronized (mInstallLock) { 15894 mInstaller.removeUserDataDirs(volumeUuid, userId); 15895 } 15896 } 15897 } 15898 15899 final UserManager um = mContext.getSystemService(UserManager.class); 15900 for (UserInfo user : um.getUsers()) { 15901 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15902 if (userDir.exists()) continue; 15903 15904 try { 15905 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15906 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15907 } catch (IOException e) { 15908 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15909 } 15910 } 15911 } 15912 15913 /** 15914 * Examine all apps present on given mounted volume, and destroy apps that 15915 * aren't expected, either due to uninstallation or reinstallation on 15916 * another volume. 15917 */ 15918 private void reconcileApps(String volumeUuid) { 15919 final File[] files = FileUtils 15920 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15921 for (File file : files) { 15922 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15923 && !PackageInstallerService.isStageName(file.getName()); 15924 if (!isPackage) { 15925 // Ignore entries which are not packages 15926 continue; 15927 } 15928 15929 boolean destroyApp = false; 15930 String packageName = null; 15931 try { 15932 final PackageLite pkg = PackageParser.parsePackageLite(file, 15933 PackageParser.PARSE_MUST_BE_APK); 15934 packageName = pkg.packageName; 15935 15936 synchronized (mPackages) { 15937 final PackageSetting ps = mSettings.mPackages.get(packageName); 15938 if (ps == null) { 15939 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15940 + volumeUuid + " because we found no install record"); 15941 destroyApp = true; 15942 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15943 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15944 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15945 destroyApp = true; 15946 } 15947 } 15948 15949 } catch (PackageParserException e) { 15950 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15951 destroyApp = true; 15952 } 15953 15954 if (destroyApp) { 15955 synchronized (mInstallLock) { 15956 if (packageName != null) { 15957 removeDataDirsLI(volumeUuid, packageName); 15958 } 15959 if (file.isDirectory()) { 15960 mInstaller.rmPackageDir(file.getAbsolutePath()); 15961 } else { 15962 file.delete(); 15963 } 15964 } 15965 } 15966 } 15967 } 15968 15969 private void unfreezePackage(String packageName) { 15970 synchronized (mPackages) { 15971 final PackageSetting ps = mSettings.mPackages.get(packageName); 15972 if (ps != null) { 15973 ps.frozen = false; 15974 } 15975 } 15976 } 15977 15978 @Override 15979 public int movePackage(final String packageName, final String volumeUuid) { 15980 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15981 15982 final int moveId = mNextMoveId.getAndIncrement(); 15983 try { 15984 movePackageInternal(packageName, volumeUuid, moveId); 15985 } catch (PackageManagerException e) { 15986 Slog.w(TAG, "Failed to move " + packageName, e); 15987 mMoveCallbacks.notifyStatusChanged(moveId, 15988 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15989 } 15990 return moveId; 15991 } 15992 15993 private void movePackageInternal(final String packageName, final String volumeUuid, 15994 final int moveId) throws PackageManagerException { 15995 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15996 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15997 final PackageManager pm = mContext.getPackageManager(); 15998 15999 final boolean currentAsec; 16000 final String currentVolumeUuid; 16001 final File codeFile; 16002 final String installerPackageName; 16003 final String packageAbiOverride; 16004 final int appId; 16005 final String seinfo; 16006 final String label; 16007 16008 // reader 16009 synchronized (mPackages) { 16010 final PackageParser.Package pkg = mPackages.get(packageName); 16011 final PackageSetting ps = mSettings.mPackages.get(packageName); 16012 if (pkg == null || ps == null) { 16013 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16014 } 16015 16016 if (pkg.applicationInfo.isSystemApp()) { 16017 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16018 "Cannot move system application"); 16019 } 16020 16021 if (pkg.applicationInfo.isExternalAsec()) { 16022 currentAsec = true; 16023 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16024 } else if (pkg.applicationInfo.isForwardLocked()) { 16025 currentAsec = true; 16026 currentVolumeUuid = "forward_locked"; 16027 } else { 16028 currentAsec = false; 16029 currentVolumeUuid = ps.volumeUuid; 16030 16031 final File probe = new File(pkg.codePath); 16032 final File probeOat = new File(probe, "oat"); 16033 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16034 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16035 "Move only supported for modern cluster style installs"); 16036 } 16037 } 16038 16039 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16040 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16041 "Package already moved to " + volumeUuid); 16042 } 16043 16044 if (ps.frozen) { 16045 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16046 "Failed to move already frozen package"); 16047 } 16048 ps.frozen = true; 16049 16050 codeFile = new File(pkg.codePath); 16051 installerPackageName = ps.installerPackageName; 16052 packageAbiOverride = ps.cpuAbiOverrideString; 16053 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16054 seinfo = pkg.applicationInfo.seinfo; 16055 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16056 } 16057 16058 // Now that we're guarded by frozen state, kill app during move 16059 final long token = Binder.clearCallingIdentity(); 16060 try { 16061 killApplication(packageName, appId, "move pkg"); 16062 } finally { 16063 Binder.restoreCallingIdentity(token); 16064 } 16065 16066 final Bundle extras = new Bundle(); 16067 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16068 extras.putString(Intent.EXTRA_TITLE, label); 16069 mMoveCallbacks.notifyCreated(moveId, extras); 16070 16071 int installFlags; 16072 final boolean moveCompleteApp; 16073 final File measurePath; 16074 16075 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16076 installFlags = INSTALL_INTERNAL; 16077 moveCompleteApp = !currentAsec; 16078 measurePath = Environment.getDataAppDirectory(volumeUuid); 16079 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16080 installFlags = INSTALL_EXTERNAL; 16081 moveCompleteApp = false; 16082 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16083 } else { 16084 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16085 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16086 || !volume.isMountedWritable()) { 16087 unfreezePackage(packageName); 16088 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16089 "Move location not mounted private volume"); 16090 } 16091 16092 Preconditions.checkState(!currentAsec); 16093 16094 installFlags = INSTALL_INTERNAL; 16095 moveCompleteApp = true; 16096 measurePath = Environment.getDataAppDirectory(volumeUuid); 16097 } 16098 16099 final PackageStats stats = new PackageStats(null, -1); 16100 synchronized (mInstaller) { 16101 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16102 unfreezePackage(packageName); 16103 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16104 "Failed to measure package size"); 16105 } 16106 } 16107 16108 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16109 + stats.dataSize); 16110 16111 final long startFreeBytes = measurePath.getFreeSpace(); 16112 final long sizeBytes; 16113 if (moveCompleteApp) { 16114 sizeBytes = stats.codeSize + stats.dataSize; 16115 } else { 16116 sizeBytes = stats.codeSize; 16117 } 16118 16119 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16120 unfreezePackage(packageName); 16121 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16122 "Not enough free space to move"); 16123 } 16124 16125 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16126 16127 final CountDownLatch installedLatch = new CountDownLatch(1); 16128 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16129 @Override 16130 public void onUserActionRequired(Intent intent) throws RemoteException { 16131 throw new IllegalStateException(); 16132 } 16133 16134 @Override 16135 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16136 Bundle extras) throws RemoteException { 16137 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16138 + PackageManager.installStatusToString(returnCode, msg)); 16139 16140 installedLatch.countDown(); 16141 16142 // Regardless of success or failure of the move operation, 16143 // always unfreeze the package 16144 unfreezePackage(packageName); 16145 16146 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16147 switch (status) { 16148 case PackageInstaller.STATUS_SUCCESS: 16149 mMoveCallbacks.notifyStatusChanged(moveId, 16150 PackageManager.MOVE_SUCCEEDED); 16151 break; 16152 case PackageInstaller.STATUS_FAILURE_STORAGE: 16153 mMoveCallbacks.notifyStatusChanged(moveId, 16154 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16155 break; 16156 default: 16157 mMoveCallbacks.notifyStatusChanged(moveId, 16158 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16159 break; 16160 } 16161 } 16162 }; 16163 16164 final MoveInfo move; 16165 if (moveCompleteApp) { 16166 // Kick off a thread to report progress estimates 16167 new Thread() { 16168 @Override 16169 public void run() { 16170 while (true) { 16171 try { 16172 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16173 break; 16174 } 16175 } catch (InterruptedException ignored) { 16176 } 16177 16178 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16179 final int progress = 10 + (int) MathUtils.constrain( 16180 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16181 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16182 } 16183 } 16184 }.start(); 16185 16186 final String dataAppName = codeFile.getName(); 16187 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16188 dataAppName, appId, seinfo); 16189 } else { 16190 move = null; 16191 } 16192 16193 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16194 16195 final Message msg = mHandler.obtainMessage(INIT_COPY); 16196 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16197 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16198 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16199 mHandler.sendMessage(msg); 16200 } 16201 16202 @Override 16203 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16204 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16205 16206 final int realMoveId = mNextMoveId.getAndIncrement(); 16207 final Bundle extras = new Bundle(); 16208 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16209 mMoveCallbacks.notifyCreated(realMoveId, extras); 16210 16211 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16212 @Override 16213 public void onCreated(int moveId, Bundle extras) { 16214 // Ignored 16215 } 16216 16217 @Override 16218 public void onStatusChanged(int moveId, int status, long estMillis) { 16219 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16220 } 16221 }; 16222 16223 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16224 storage.setPrimaryStorageUuid(volumeUuid, callback); 16225 return realMoveId; 16226 } 16227 16228 @Override 16229 public int getMoveStatus(int moveId) { 16230 mContext.enforceCallingOrSelfPermission( 16231 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16232 return mMoveCallbacks.mLastStatus.get(moveId); 16233 } 16234 16235 @Override 16236 public void registerMoveCallback(IPackageMoveObserver callback) { 16237 mContext.enforceCallingOrSelfPermission( 16238 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16239 mMoveCallbacks.register(callback); 16240 } 16241 16242 @Override 16243 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16244 mContext.enforceCallingOrSelfPermission( 16245 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16246 mMoveCallbacks.unregister(callback); 16247 } 16248 16249 @Override 16250 public boolean setInstallLocation(int loc) { 16251 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16252 null); 16253 if (getInstallLocation() == loc) { 16254 return true; 16255 } 16256 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16257 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16258 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16259 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16260 return true; 16261 } 16262 return false; 16263 } 16264 16265 @Override 16266 public int getInstallLocation() { 16267 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16268 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16269 PackageHelper.APP_INSTALL_AUTO); 16270 } 16271 16272 /** Called by UserManagerService */ 16273 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16274 mDirtyUsers.remove(userHandle); 16275 mSettings.removeUserLPw(userHandle); 16276 mPendingBroadcasts.remove(userHandle); 16277 if (mInstaller != null) { 16278 // Technically, we shouldn't be doing this with the package lock 16279 // held. However, this is very rare, and there is already so much 16280 // other disk I/O going on, that we'll let it slide for now. 16281 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16282 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16283 final String volumeUuid = vol.getFsUuid(); 16284 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16285 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16286 } 16287 } 16288 mUserNeedsBadging.delete(userHandle); 16289 removeUnusedPackagesLILPw(userManager, userHandle); 16290 } 16291 16292 /** 16293 * We're removing userHandle and would like to remove any downloaded packages 16294 * that are no longer in use by any other user. 16295 * @param userHandle the user being removed 16296 */ 16297 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16298 final boolean DEBUG_CLEAN_APKS = false; 16299 int [] users = userManager.getUserIdsLPr(); 16300 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16301 while (psit.hasNext()) { 16302 PackageSetting ps = psit.next(); 16303 if (ps.pkg == null) { 16304 continue; 16305 } 16306 final String packageName = ps.pkg.packageName; 16307 // Skip over if system app 16308 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16309 continue; 16310 } 16311 if (DEBUG_CLEAN_APKS) { 16312 Slog.i(TAG, "Checking package " + packageName); 16313 } 16314 boolean keep = false; 16315 for (int i = 0; i < users.length; i++) { 16316 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16317 keep = true; 16318 if (DEBUG_CLEAN_APKS) { 16319 Slog.i(TAG, " Keeping package " + packageName + " for user " 16320 + users[i]); 16321 } 16322 break; 16323 } 16324 } 16325 if (!keep) { 16326 if (DEBUG_CLEAN_APKS) { 16327 Slog.i(TAG, " Removing package " + packageName); 16328 } 16329 mHandler.post(new Runnable() { 16330 public void run() { 16331 deletePackageX(packageName, userHandle, 0); 16332 } //end run 16333 }); 16334 } 16335 } 16336 } 16337 16338 /** Called by UserManagerService */ 16339 void createNewUserLILPw(int userHandle) { 16340 if (mInstaller != null) { 16341 mInstaller.createUserConfig(userHandle); 16342 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16343 applyFactoryDefaultBrowserLPw(userHandle); 16344 primeDomainVerificationsLPw(userHandle); 16345 } 16346 } 16347 16348 void newUserCreated(final int userHandle) { 16349 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16350 } 16351 16352 @Override 16353 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16354 mContext.enforceCallingOrSelfPermission( 16355 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16356 "Only package verification agents can read the verifier device identity"); 16357 16358 synchronized (mPackages) { 16359 return mSettings.getVerifierDeviceIdentityLPw(); 16360 } 16361 } 16362 16363 @Override 16364 public void setPermissionEnforced(String permission, boolean enforced) { 16365 // TODO: Now that we no longer change GID for storage, this should to away. 16366 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16367 "setPermissionEnforced"); 16368 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16369 synchronized (mPackages) { 16370 if (mSettings.mReadExternalStorageEnforced == null 16371 || mSettings.mReadExternalStorageEnforced != enforced) { 16372 mSettings.mReadExternalStorageEnforced = enforced; 16373 mSettings.writeLPr(); 16374 } 16375 } 16376 // kill any non-foreground processes so we restart them and 16377 // grant/revoke the GID. 16378 final IActivityManager am = ActivityManagerNative.getDefault(); 16379 if (am != null) { 16380 final long token = Binder.clearCallingIdentity(); 16381 try { 16382 am.killProcessesBelowForeground("setPermissionEnforcement"); 16383 } catch (RemoteException e) { 16384 } finally { 16385 Binder.restoreCallingIdentity(token); 16386 } 16387 } 16388 } else { 16389 throw new IllegalArgumentException("No selective enforcement for " + permission); 16390 } 16391 } 16392 16393 @Override 16394 @Deprecated 16395 public boolean isPermissionEnforced(String permission) { 16396 return true; 16397 } 16398 16399 @Override 16400 public boolean isStorageLow() { 16401 final long token = Binder.clearCallingIdentity(); 16402 try { 16403 final DeviceStorageMonitorInternal 16404 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16405 if (dsm != null) { 16406 return dsm.isMemoryLow(); 16407 } else { 16408 return false; 16409 } 16410 } finally { 16411 Binder.restoreCallingIdentity(token); 16412 } 16413 } 16414 16415 @Override 16416 public IPackageInstaller getPackageInstaller() { 16417 return mInstallerService; 16418 } 16419 16420 private boolean userNeedsBadging(int userId) { 16421 int index = mUserNeedsBadging.indexOfKey(userId); 16422 if (index < 0) { 16423 final UserInfo userInfo; 16424 final long token = Binder.clearCallingIdentity(); 16425 try { 16426 userInfo = sUserManager.getUserInfo(userId); 16427 } finally { 16428 Binder.restoreCallingIdentity(token); 16429 } 16430 final boolean b; 16431 if (userInfo != null && userInfo.isManagedProfile()) { 16432 b = true; 16433 } else { 16434 b = false; 16435 } 16436 mUserNeedsBadging.put(userId, b); 16437 return b; 16438 } 16439 return mUserNeedsBadging.valueAt(index); 16440 } 16441 16442 @Override 16443 public KeySet getKeySetByAlias(String packageName, String alias) { 16444 if (packageName == null || alias == null) { 16445 return null; 16446 } 16447 synchronized(mPackages) { 16448 final PackageParser.Package pkg = mPackages.get(packageName); 16449 if (pkg == null) { 16450 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16451 throw new IllegalArgumentException("Unknown package: " + packageName); 16452 } 16453 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16454 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16455 } 16456 } 16457 16458 @Override 16459 public KeySet getSigningKeySet(String packageName) { 16460 if (packageName == null) { 16461 return null; 16462 } 16463 synchronized(mPackages) { 16464 final PackageParser.Package pkg = mPackages.get(packageName); 16465 if (pkg == null) { 16466 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16467 throw new IllegalArgumentException("Unknown package: " + packageName); 16468 } 16469 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16470 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16471 throw new SecurityException("May not access signing KeySet of other apps."); 16472 } 16473 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16474 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16475 } 16476 } 16477 16478 @Override 16479 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16480 if (packageName == null || ks == null) { 16481 return false; 16482 } 16483 synchronized(mPackages) { 16484 final PackageParser.Package pkg = mPackages.get(packageName); 16485 if (pkg == null) { 16486 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16487 throw new IllegalArgumentException("Unknown package: " + packageName); 16488 } 16489 IBinder ksh = ks.getToken(); 16490 if (ksh instanceof KeySetHandle) { 16491 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16492 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16493 } 16494 return false; 16495 } 16496 } 16497 16498 @Override 16499 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16500 if (packageName == null || ks == null) { 16501 return false; 16502 } 16503 synchronized(mPackages) { 16504 final PackageParser.Package pkg = mPackages.get(packageName); 16505 if (pkg == null) { 16506 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16507 throw new IllegalArgumentException("Unknown package: " + packageName); 16508 } 16509 IBinder ksh = ks.getToken(); 16510 if (ksh instanceof KeySetHandle) { 16511 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16512 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16513 } 16514 return false; 16515 } 16516 } 16517 16518 public void getUsageStatsIfNoPackageUsageInfo() { 16519 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16520 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16521 if (usm == null) { 16522 throw new IllegalStateException("UsageStatsManager must be initialized"); 16523 } 16524 long now = System.currentTimeMillis(); 16525 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16526 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16527 String packageName = entry.getKey(); 16528 PackageParser.Package pkg = mPackages.get(packageName); 16529 if (pkg == null) { 16530 continue; 16531 } 16532 UsageStats usage = entry.getValue(); 16533 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16534 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16535 } 16536 } 16537 } 16538 16539 /** 16540 * Check and throw if the given before/after packages would be considered a 16541 * downgrade. 16542 */ 16543 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16544 throws PackageManagerException { 16545 if (after.versionCode < before.mVersionCode) { 16546 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16547 "Update version code " + after.versionCode + " is older than current " 16548 + before.mVersionCode); 16549 } else if (after.versionCode == before.mVersionCode) { 16550 if (after.baseRevisionCode < before.baseRevisionCode) { 16551 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16552 "Update base revision code " + after.baseRevisionCode 16553 + " is older than current " + before.baseRevisionCode); 16554 } 16555 16556 if (!ArrayUtils.isEmpty(after.splitNames)) { 16557 for (int i = 0; i < after.splitNames.length; i++) { 16558 final String splitName = after.splitNames[i]; 16559 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16560 if (j != -1) { 16561 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16562 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16563 "Update split " + splitName + " revision code " 16564 + after.splitRevisionCodes[i] + " is older than current " 16565 + before.splitRevisionCodes[j]); 16566 } 16567 } 16568 } 16569 } 16570 } 16571 } 16572 16573 private static class MoveCallbacks extends Handler { 16574 private static final int MSG_CREATED = 1; 16575 private static final int MSG_STATUS_CHANGED = 2; 16576 16577 private final RemoteCallbackList<IPackageMoveObserver> 16578 mCallbacks = new RemoteCallbackList<>(); 16579 16580 private final SparseIntArray mLastStatus = new SparseIntArray(); 16581 16582 public MoveCallbacks(Looper looper) { 16583 super(looper); 16584 } 16585 16586 public void register(IPackageMoveObserver callback) { 16587 mCallbacks.register(callback); 16588 } 16589 16590 public void unregister(IPackageMoveObserver callback) { 16591 mCallbacks.unregister(callback); 16592 } 16593 16594 @Override 16595 public void handleMessage(Message msg) { 16596 final SomeArgs args = (SomeArgs) msg.obj; 16597 final int n = mCallbacks.beginBroadcast(); 16598 for (int i = 0; i < n; i++) { 16599 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16600 try { 16601 invokeCallback(callback, msg.what, args); 16602 } catch (RemoteException ignored) { 16603 } 16604 } 16605 mCallbacks.finishBroadcast(); 16606 args.recycle(); 16607 } 16608 16609 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16610 throws RemoteException { 16611 switch (what) { 16612 case MSG_CREATED: { 16613 callback.onCreated(args.argi1, (Bundle) args.arg2); 16614 break; 16615 } 16616 case MSG_STATUS_CHANGED: { 16617 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16618 break; 16619 } 16620 } 16621 } 16622 16623 private void notifyCreated(int moveId, Bundle extras) { 16624 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16625 16626 final SomeArgs args = SomeArgs.obtain(); 16627 args.argi1 = moveId; 16628 args.arg2 = extras; 16629 obtainMessage(MSG_CREATED, args).sendToTarget(); 16630 } 16631 16632 private void notifyStatusChanged(int moveId, int status) { 16633 notifyStatusChanged(moveId, status, -1); 16634 } 16635 16636 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16637 Slog.v(TAG, "Move " + moveId + " status " + status); 16638 16639 final SomeArgs args = SomeArgs.obtain(); 16640 args.argi1 = moveId; 16641 args.argi2 = status; 16642 args.arg3 = estMillis; 16643 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16644 16645 synchronized (mLastStatus) { 16646 mLastStatus.put(moveId, status); 16647 } 16648 } 16649 } 16650 16651 private final class OnPermissionChangeListeners extends Handler { 16652 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16653 16654 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16655 new RemoteCallbackList<>(); 16656 16657 public OnPermissionChangeListeners(Looper looper) { 16658 super(looper); 16659 } 16660 16661 @Override 16662 public void handleMessage(Message msg) { 16663 switch (msg.what) { 16664 case MSG_ON_PERMISSIONS_CHANGED: { 16665 final int uid = msg.arg1; 16666 handleOnPermissionsChanged(uid); 16667 } break; 16668 } 16669 } 16670 16671 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16672 mPermissionListeners.register(listener); 16673 16674 } 16675 16676 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16677 mPermissionListeners.unregister(listener); 16678 } 16679 16680 public void onPermissionsChanged(int uid) { 16681 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16682 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16683 } 16684 } 16685 16686 private void handleOnPermissionsChanged(int uid) { 16687 final int count = mPermissionListeners.beginBroadcast(); 16688 try { 16689 for (int i = 0; i < count; i++) { 16690 IOnPermissionsChangeListener callback = mPermissionListeners 16691 .getBroadcastItem(i); 16692 try { 16693 callback.onPermissionsChanged(uid); 16694 } catch (RemoteException e) { 16695 Log.e(TAG, "Permission listener is dead", e); 16696 } 16697 } 16698 } finally { 16699 mPermissionListeners.finishBroadcast(); 16700 } 16701 } 16702 } 16703 16704 private class PackageManagerInternalImpl extends PackageManagerInternal { 16705 @Override 16706 public void setLocationPackagesProvider(PackagesProvider provider) { 16707 synchronized (mPackages) { 16708 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16709 } 16710 } 16711 16712 @Override 16713 public void setImePackagesProvider(PackagesProvider provider) { 16714 synchronized (mPackages) { 16715 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16716 } 16717 } 16718 16719 @Override 16720 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16721 synchronized (mPackages) { 16722 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16723 } 16724 } 16725 16726 @Override 16727 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16728 synchronized (mPackages) { 16729 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16730 } 16731 } 16732 16733 @Override 16734 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16735 synchronized (mPackages) { 16736 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16737 } 16738 } 16739 16740 @Override 16741 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16742 synchronized (mPackages) { 16743 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16744 } 16745 } 16746 16747 @Override 16748 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16749 synchronized (mPackages) { 16750 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16751 } 16752 } 16753 16754 @Override 16755 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16756 synchronized (mPackages) { 16757 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16758 packageName, userId); 16759 } 16760 } 16761 16762 @Override 16763 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16764 synchronized (mPackages) { 16765 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16766 packageName, userId); 16767 } 16768 } 16769 @Override 16770 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16771 synchronized (mPackages) { 16772 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16773 packageName, userId); 16774 } 16775 } 16776 } 16777 16778 @Override 16779 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16780 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16781 synchronized (mPackages) { 16782 final long identity = Binder.clearCallingIdentity(); 16783 try { 16784 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16785 packageNames, userId); 16786 } finally { 16787 Binder.restoreCallingIdentity(identity); 16788 } 16789 } 16790 } 16791 16792 private static void enforceSystemOrPhoneCaller(String tag) { 16793 int callingUid = Binder.getCallingUid(); 16794 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16795 throw new SecurityException( 16796 "Cannot call " + tag + " from UID " + callingUid); 16797 } 16798 } 16799} 16800