PackageManagerService.java revision 16387b44f5fcdf205f101d8f49ee74515010f00d
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_USER_OWNER; 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 filterIfNotPrimaryUser(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 = filterIfNotPrimaryUser(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 filterIfNotPrimaryUser( 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 primaryUserOnly flag set, when current user is not the owner. 4688 * 4689 * @return filtered list 4690 */ 4691 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4692 if (userId == UserHandle.USER_OWNER) { 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_PRIMARY_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 String className; 4953 if (targetUserId == UserHandle.USER_OWNER) { 4954 className = FORWARD_INTENT_TO_USER_OWNER; 4955 } else { 4956 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4957 } 4958 ComponentName forwardingActivityComponentName = new ComponentName( 4959 mAndroidApplication.packageName, className); 4960 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4961 sourceUserId); 4962 if (targetUserId == UserHandle.USER_OWNER) { 4963 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4964 forwardingResolveInfo.noResourceId = true; 4965 } 4966 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4967 forwardingResolveInfo.priority = 0; 4968 forwardingResolveInfo.preferredOrder = 0; 4969 forwardingResolveInfo.match = 0; 4970 forwardingResolveInfo.isDefault = true; 4971 forwardingResolveInfo.filter = filter; 4972 forwardingResolveInfo.targetUserId = targetUserId; 4973 return forwardingResolveInfo; 4974 } 4975 4976 @Override 4977 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4978 Intent[] specifics, String[] specificTypes, Intent intent, 4979 String resolvedType, int flags, int userId) { 4980 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4981 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4982 false, "query intent activity options"); 4983 final String resultsAction = intent.getAction(); 4984 4985 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4986 | PackageManager.GET_RESOLVED_FILTER, userId); 4987 4988 if (DEBUG_INTENT_MATCHING) { 4989 Log.v(TAG, "Query " + intent + ": " + results); 4990 } 4991 4992 int specificsPos = 0; 4993 int N; 4994 4995 // todo: note that the algorithm used here is O(N^2). This 4996 // isn't a problem in our current environment, but if we start running 4997 // into situations where we have more than 5 or 10 matches then this 4998 // should probably be changed to something smarter... 4999 5000 // First we go through and resolve each of the specific items 5001 // that were supplied, taking care of removing any corresponding 5002 // duplicate items in the generic resolve list. 5003 if (specifics != null) { 5004 for (int i=0; i<specifics.length; i++) { 5005 final Intent sintent = specifics[i]; 5006 if (sintent == null) { 5007 continue; 5008 } 5009 5010 if (DEBUG_INTENT_MATCHING) { 5011 Log.v(TAG, "Specific #" + i + ": " + sintent); 5012 } 5013 5014 String action = sintent.getAction(); 5015 if (resultsAction != null && resultsAction.equals(action)) { 5016 // If this action was explicitly requested, then don't 5017 // remove things that have it. 5018 action = null; 5019 } 5020 5021 ResolveInfo ri = null; 5022 ActivityInfo ai = null; 5023 5024 ComponentName comp = sintent.getComponent(); 5025 if (comp == null) { 5026 ri = resolveIntent( 5027 sintent, 5028 specificTypes != null ? specificTypes[i] : null, 5029 flags, userId); 5030 if (ri == null) { 5031 continue; 5032 } 5033 if (ri == mResolveInfo) { 5034 // ACK! Must do something better with this. 5035 } 5036 ai = ri.activityInfo; 5037 comp = new ComponentName(ai.applicationInfo.packageName, 5038 ai.name); 5039 } else { 5040 ai = getActivityInfo(comp, flags, userId); 5041 if (ai == null) { 5042 continue; 5043 } 5044 } 5045 5046 // Look for any generic query activities that are duplicates 5047 // of this specific one, and remove them from the results. 5048 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5049 N = results.size(); 5050 int j; 5051 for (j=specificsPos; j<N; j++) { 5052 ResolveInfo sri = results.get(j); 5053 if ((sri.activityInfo.name.equals(comp.getClassName()) 5054 && sri.activityInfo.applicationInfo.packageName.equals( 5055 comp.getPackageName())) 5056 || (action != null && sri.filter.matchAction(action))) { 5057 results.remove(j); 5058 if (DEBUG_INTENT_MATCHING) Log.v( 5059 TAG, "Removing duplicate item from " + j 5060 + " due to specific " + specificsPos); 5061 if (ri == null) { 5062 ri = sri; 5063 } 5064 j--; 5065 N--; 5066 } 5067 } 5068 5069 // Add this specific item to its proper place. 5070 if (ri == null) { 5071 ri = new ResolveInfo(); 5072 ri.activityInfo = ai; 5073 } 5074 results.add(specificsPos, ri); 5075 ri.specificIndex = i; 5076 specificsPos++; 5077 } 5078 } 5079 5080 // Now we go through the remaining generic results and remove any 5081 // duplicate actions that are found here. 5082 N = results.size(); 5083 for (int i=specificsPos; i<N-1; i++) { 5084 final ResolveInfo rii = results.get(i); 5085 if (rii.filter == null) { 5086 continue; 5087 } 5088 5089 // Iterate over all of the actions of this result's intent 5090 // filter... typically this should be just one. 5091 final Iterator<String> it = rii.filter.actionsIterator(); 5092 if (it == null) { 5093 continue; 5094 } 5095 while (it.hasNext()) { 5096 final String action = it.next(); 5097 if (resultsAction != null && resultsAction.equals(action)) { 5098 // If this action was explicitly requested, then don't 5099 // remove things that have it. 5100 continue; 5101 } 5102 for (int j=i+1; j<N; j++) { 5103 final ResolveInfo rij = results.get(j); 5104 if (rij.filter != null && rij.filter.hasAction(action)) { 5105 results.remove(j); 5106 if (DEBUG_INTENT_MATCHING) Log.v( 5107 TAG, "Removing duplicate item from " + j 5108 + " due to action " + action + " at " + i); 5109 j--; 5110 N--; 5111 } 5112 } 5113 } 5114 5115 // If the caller didn't request filter information, drop it now 5116 // so we don't have to marshall/unmarshall it. 5117 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5118 rii.filter = null; 5119 } 5120 } 5121 5122 // Filter out the caller activity if so requested. 5123 if (caller != null) { 5124 N = results.size(); 5125 for (int i=0; i<N; i++) { 5126 ActivityInfo ainfo = results.get(i).activityInfo; 5127 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5128 && caller.getClassName().equals(ainfo.name)) { 5129 results.remove(i); 5130 break; 5131 } 5132 } 5133 } 5134 5135 // If the caller didn't request filter information, 5136 // drop them now so we don't have to 5137 // marshall/unmarshall it. 5138 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5139 N = results.size(); 5140 for (int i=0; i<N; i++) { 5141 results.get(i).filter = null; 5142 } 5143 } 5144 5145 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5146 return results; 5147 } 5148 5149 @Override 5150 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5151 int userId) { 5152 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5153 ComponentName comp = intent.getComponent(); 5154 if (comp == null) { 5155 if (intent.getSelector() != null) { 5156 intent = intent.getSelector(); 5157 comp = intent.getComponent(); 5158 } 5159 } 5160 if (comp != null) { 5161 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5162 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5163 if (ai != null) { 5164 ResolveInfo ri = new ResolveInfo(); 5165 ri.activityInfo = ai; 5166 list.add(ri); 5167 } 5168 return list; 5169 } 5170 5171 // reader 5172 synchronized (mPackages) { 5173 String pkgName = intent.getPackage(); 5174 if (pkgName == null) { 5175 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5176 } 5177 final PackageParser.Package pkg = mPackages.get(pkgName); 5178 if (pkg != null) { 5179 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5180 userId); 5181 } 5182 return null; 5183 } 5184 } 5185 5186 @Override 5187 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5188 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5189 if (!sUserManager.exists(userId)) return null; 5190 if (query != null) { 5191 if (query.size() >= 1) { 5192 // If there is more than one service with the same priority, 5193 // just arbitrarily pick the first one. 5194 return query.get(0); 5195 } 5196 } 5197 return null; 5198 } 5199 5200 @Override 5201 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5202 int userId) { 5203 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5204 ComponentName comp = intent.getComponent(); 5205 if (comp == null) { 5206 if (intent.getSelector() != null) { 5207 intent = intent.getSelector(); 5208 comp = intent.getComponent(); 5209 } 5210 } 5211 if (comp != null) { 5212 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5213 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5214 if (si != null) { 5215 final ResolveInfo ri = new ResolveInfo(); 5216 ri.serviceInfo = si; 5217 list.add(ri); 5218 } 5219 return list; 5220 } 5221 5222 // reader 5223 synchronized (mPackages) { 5224 String pkgName = intent.getPackage(); 5225 if (pkgName == null) { 5226 return mServices.queryIntent(intent, resolvedType, flags, userId); 5227 } 5228 final PackageParser.Package pkg = mPackages.get(pkgName); 5229 if (pkg != null) { 5230 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5231 userId); 5232 } 5233 return null; 5234 } 5235 } 5236 5237 @Override 5238 public List<ResolveInfo> queryIntentContentProviders( 5239 Intent intent, String resolvedType, int flags, int userId) { 5240 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5241 ComponentName comp = intent.getComponent(); 5242 if (comp == null) { 5243 if (intent.getSelector() != null) { 5244 intent = intent.getSelector(); 5245 comp = intent.getComponent(); 5246 } 5247 } 5248 if (comp != null) { 5249 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5250 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5251 if (pi != null) { 5252 final ResolveInfo ri = new ResolveInfo(); 5253 ri.providerInfo = pi; 5254 list.add(ri); 5255 } 5256 return list; 5257 } 5258 5259 // reader 5260 synchronized (mPackages) { 5261 String pkgName = intent.getPackage(); 5262 if (pkgName == null) { 5263 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5264 } 5265 final PackageParser.Package pkg = mPackages.get(pkgName); 5266 if (pkg != null) { 5267 return mProviders.queryIntentForPackage( 5268 intent, resolvedType, flags, pkg.providers, userId); 5269 } 5270 return null; 5271 } 5272 } 5273 5274 @Override 5275 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5276 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5277 5278 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5279 5280 // writer 5281 synchronized (mPackages) { 5282 ArrayList<PackageInfo> list; 5283 if (listUninstalled) { 5284 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5285 for (PackageSetting ps : mSettings.mPackages.values()) { 5286 PackageInfo pi; 5287 if (ps.pkg != null) { 5288 pi = generatePackageInfo(ps.pkg, flags, userId); 5289 } else { 5290 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5291 } 5292 if (pi != null) { 5293 list.add(pi); 5294 } 5295 } 5296 } else { 5297 list = new ArrayList<PackageInfo>(mPackages.size()); 5298 for (PackageParser.Package p : mPackages.values()) { 5299 PackageInfo pi = generatePackageInfo(p, flags, userId); 5300 if (pi != null) { 5301 list.add(pi); 5302 } 5303 } 5304 } 5305 5306 return new ParceledListSlice<PackageInfo>(list); 5307 } 5308 } 5309 5310 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5311 String[] permissions, boolean[] tmp, int flags, int userId) { 5312 int numMatch = 0; 5313 final PermissionsState permissionsState = ps.getPermissionsState(); 5314 for (int i=0; i<permissions.length; i++) { 5315 final String permission = permissions[i]; 5316 if (permissionsState.hasPermission(permission, userId)) { 5317 tmp[i] = true; 5318 numMatch++; 5319 } else { 5320 tmp[i] = false; 5321 } 5322 } 5323 if (numMatch == 0) { 5324 return; 5325 } 5326 PackageInfo pi; 5327 if (ps.pkg != null) { 5328 pi = generatePackageInfo(ps.pkg, flags, userId); 5329 } else { 5330 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5331 } 5332 // The above might return null in cases of uninstalled apps or install-state 5333 // skew across users/profiles. 5334 if (pi != null) { 5335 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5336 if (numMatch == permissions.length) { 5337 pi.requestedPermissions = permissions; 5338 } else { 5339 pi.requestedPermissions = new String[numMatch]; 5340 numMatch = 0; 5341 for (int i=0; i<permissions.length; i++) { 5342 if (tmp[i]) { 5343 pi.requestedPermissions[numMatch] = permissions[i]; 5344 numMatch++; 5345 } 5346 } 5347 } 5348 } 5349 list.add(pi); 5350 } 5351 } 5352 5353 @Override 5354 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5355 String[] permissions, int flags, int userId) { 5356 if (!sUserManager.exists(userId)) return null; 5357 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5358 5359 // writer 5360 synchronized (mPackages) { 5361 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5362 boolean[] tmpBools = new boolean[permissions.length]; 5363 if (listUninstalled) { 5364 for (PackageSetting ps : mSettings.mPackages.values()) { 5365 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5366 } 5367 } else { 5368 for (PackageParser.Package pkg : mPackages.values()) { 5369 PackageSetting ps = (PackageSetting)pkg.mExtras; 5370 if (ps != null) { 5371 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5372 userId); 5373 } 5374 } 5375 } 5376 5377 return new ParceledListSlice<PackageInfo>(list); 5378 } 5379 } 5380 5381 @Override 5382 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5383 if (!sUserManager.exists(userId)) return null; 5384 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5385 5386 // writer 5387 synchronized (mPackages) { 5388 ArrayList<ApplicationInfo> list; 5389 if (listUninstalled) { 5390 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5391 for (PackageSetting ps : mSettings.mPackages.values()) { 5392 ApplicationInfo ai; 5393 if (ps.pkg != null) { 5394 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5395 ps.readUserState(userId), userId); 5396 } else { 5397 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5398 } 5399 if (ai != null) { 5400 list.add(ai); 5401 } 5402 } 5403 } else { 5404 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5405 for (PackageParser.Package p : mPackages.values()) { 5406 if (p.mExtras != null) { 5407 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5408 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5409 if (ai != null) { 5410 list.add(ai); 5411 } 5412 } 5413 } 5414 } 5415 5416 return new ParceledListSlice<ApplicationInfo>(list); 5417 } 5418 } 5419 5420 public List<ApplicationInfo> getPersistentApplications(int flags) { 5421 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5422 5423 // reader 5424 synchronized (mPackages) { 5425 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5426 final int userId = UserHandle.getCallingUserId(); 5427 while (i.hasNext()) { 5428 final PackageParser.Package p = i.next(); 5429 if (p.applicationInfo != null 5430 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5431 && (!mSafeMode || isSystemApp(p))) { 5432 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5433 if (ps != null) { 5434 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5435 ps.readUserState(userId), userId); 5436 if (ai != null) { 5437 finalList.add(ai); 5438 } 5439 } 5440 } 5441 } 5442 } 5443 5444 return finalList; 5445 } 5446 5447 @Override 5448 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5449 if (!sUserManager.exists(userId)) return null; 5450 // reader 5451 synchronized (mPackages) { 5452 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5453 PackageSetting ps = provider != null 5454 ? mSettings.mPackages.get(provider.owner.packageName) 5455 : null; 5456 return ps != null 5457 && mSettings.isEnabledLPr(provider.info, flags, userId) 5458 && (!mSafeMode || (provider.info.applicationInfo.flags 5459 &ApplicationInfo.FLAG_SYSTEM) != 0) 5460 ? PackageParser.generateProviderInfo(provider, flags, 5461 ps.readUserState(userId), userId) 5462 : null; 5463 } 5464 } 5465 5466 /** 5467 * @deprecated 5468 */ 5469 @Deprecated 5470 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5471 // reader 5472 synchronized (mPackages) { 5473 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5474 .entrySet().iterator(); 5475 final int userId = UserHandle.getCallingUserId(); 5476 while (i.hasNext()) { 5477 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5478 PackageParser.Provider p = entry.getValue(); 5479 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5480 5481 if (ps != null && p.syncable 5482 && (!mSafeMode || (p.info.applicationInfo.flags 5483 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5484 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5485 ps.readUserState(userId), userId); 5486 if (info != null) { 5487 outNames.add(entry.getKey()); 5488 outInfo.add(info); 5489 } 5490 } 5491 } 5492 } 5493 } 5494 5495 @Override 5496 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5497 int uid, int flags) { 5498 ArrayList<ProviderInfo> finalList = null; 5499 // reader 5500 synchronized (mPackages) { 5501 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5502 final int userId = processName != null ? 5503 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5504 while (i.hasNext()) { 5505 final PackageParser.Provider p = i.next(); 5506 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5507 if (ps != null && p.info.authority != null 5508 && (processName == null 5509 || (p.info.processName.equals(processName) 5510 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5511 && mSettings.isEnabledLPr(p.info, flags, userId) 5512 && (!mSafeMode 5513 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5514 if (finalList == null) { 5515 finalList = new ArrayList<ProviderInfo>(3); 5516 } 5517 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5518 ps.readUserState(userId), userId); 5519 if (info != null) { 5520 finalList.add(info); 5521 } 5522 } 5523 } 5524 } 5525 5526 if (finalList != null) { 5527 Collections.sort(finalList, mProviderInitOrderSorter); 5528 return new ParceledListSlice<ProviderInfo>(finalList); 5529 } 5530 5531 return null; 5532 } 5533 5534 @Override 5535 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5536 int flags) { 5537 // reader 5538 synchronized (mPackages) { 5539 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5540 return PackageParser.generateInstrumentationInfo(i, flags); 5541 } 5542 } 5543 5544 @Override 5545 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5546 int flags) { 5547 ArrayList<InstrumentationInfo> finalList = 5548 new ArrayList<InstrumentationInfo>(); 5549 5550 // reader 5551 synchronized (mPackages) { 5552 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5553 while (i.hasNext()) { 5554 final PackageParser.Instrumentation p = i.next(); 5555 if (targetPackage == null 5556 || targetPackage.equals(p.info.targetPackage)) { 5557 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5558 flags); 5559 if (ii != null) { 5560 finalList.add(ii); 5561 } 5562 } 5563 } 5564 } 5565 5566 return finalList; 5567 } 5568 5569 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5570 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5571 if (overlays == null) { 5572 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5573 return; 5574 } 5575 for (PackageParser.Package opkg : overlays.values()) { 5576 // Not much to do if idmap fails: we already logged the error 5577 // and we certainly don't want to abort installation of pkg simply 5578 // because an overlay didn't fit properly. For these reasons, 5579 // ignore the return value of createIdmapForPackagePairLI. 5580 createIdmapForPackagePairLI(pkg, opkg); 5581 } 5582 } 5583 5584 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5585 PackageParser.Package opkg) { 5586 if (!opkg.mTrustedOverlay) { 5587 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5588 opkg.baseCodePath + ": overlay not trusted"); 5589 return false; 5590 } 5591 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5592 if (overlaySet == null) { 5593 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5594 opkg.baseCodePath + " but target package has no known overlays"); 5595 return false; 5596 } 5597 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5598 // TODO: generate idmap for split APKs 5599 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5600 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5601 + opkg.baseCodePath); 5602 return false; 5603 } 5604 PackageParser.Package[] overlayArray = 5605 overlaySet.values().toArray(new PackageParser.Package[0]); 5606 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5607 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5608 return p1.mOverlayPriority - p2.mOverlayPriority; 5609 } 5610 }; 5611 Arrays.sort(overlayArray, cmp); 5612 5613 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5614 int i = 0; 5615 for (PackageParser.Package p : overlayArray) { 5616 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5617 } 5618 return true; 5619 } 5620 5621 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5622 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5623 try { 5624 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5625 } finally { 5626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5627 } 5628 } 5629 5630 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5631 final File[] files = dir.listFiles(); 5632 if (ArrayUtils.isEmpty(files)) { 5633 Log.d(TAG, "No files in app dir " + dir); 5634 return; 5635 } 5636 5637 if (DEBUG_PACKAGE_SCANNING) { 5638 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5639 + " flags=0x" + Integer.toHexString(parseFlags)); 5640 } 5641 5642 for (File file : files) { 5643 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5644 && !PackageInstallerService.isStageName(file.getName()); 5645 if (!isPackage) { 5646 // Ignore entries which are not packages 5647 continue; 5648 } 5649 try { 5650 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5651 scanFlags, currentTime, null); 5652 } catch (PackageManagerException e) { 5653 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5654 5655 // Delete invalid userdata apps 5656 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5657 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5658 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5659 if (file.isDirectory()) { 5660 mInstaller.rmPackageDir(file.getAbsolutePath()); 5661 } else { 5662 file.delete(); 5663 } 5664 } 5665 } 5666 } 5667 } 5668 5669 private static File getSettingsProblemFile() { 5670 File dataDir = Environment.getDataDirectory(); 5671 File systemDir = new File(dataDir, "system"); 5672 File fname = new File(systemDir, "uiderrors.txt"); 5673 return fname; 5674 } 5675 5676 static void reportSettingsProblem(int priority, String msg) { 5677 logCriticalInfo(priority, msg); 5678 } 5679 5680 static void logCriticalInfo(int priority, String msg) { 5681 Slog.println(priority, TAG, msg); 5682 EventLogTags.writePmCriticalInfo(msg); 5683 try { 5684 File fname = getSettingsProblemFile(); 5685 FileOutputStream out = new FileOutputStream(fname, true); 5686 PrintWriter pw = new FastPrintWriter(out); 5687 SimpleDateFormat formatter = new SimpleDateFormat(); 5688 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5689 pw.println(dateString + ": " + msg); 5690 pw.close(); 5691 FileUtils.setPermissions( 5692 fname.toString(), 5693 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5694 -1, -1); 5695 } catch (java.io.IOException e) { 5696 } 5697 } 5698 5699 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5700 PackageParser.Package pkg, File srcFile, int parseFlags) 5701 throws PackageManagerException { 5702 if (ps != null 5703 && ps.codePath.equals(srcFile) 5704 && ps.timeStamp == srcFile.lastModified() 5705 && !isCompatSignatureUpdateNeeded(pkg) 5706 && !isRecoverSignatureUpdateNeeded(pkg)) { 5707 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5708 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5709 ArraySet<PublicKey> signingKs; 5710 synchronized (mPackages) { 5711 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5712 } 5713 if (ps.signatures.mSignatures != null 5714 && ps.signatures.mSignatures.length != 0 5715 && signingKs != null) { 5716 // Optimization: reuse the existing cached certificates 5717 // if the package appears to be unchanged. 5718 pkg.mSignatures = ps.signatures.mSignatures; 5719 pkg.mSigningKeys = signingKs; 5720 return; 5721 } 5722 5723 Slog.w(TAG, "PackageSetting for " + ps.name 5724 + " is missing signatures. Collecting certs again to recover them."); 5725 } else { 5726 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5727 } 5728 5729 try { 5730 pp.collectCertificates(pkg, parseFlags); 5731 pp.collectManifestDigest(pkg); 5732 } catch (PackageParserException e) { 5733 throw PackageManagerException.from(e); 5734 } 5735 } 5736 5737 /** 5738 * Traces a package scan. 5739 * @see #scanPackageLI(File, int, int, long, UserHandle) 5740 */ 5741 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5742 long currentTime, UserHandle user) throws PackageManagerException { 5743 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5744 try { 5745 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5746 } finally { 5747 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5748 } 5749 } 5750 5751 /** 5752 * Scans a package and returns the newly parsed package. 5753 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5754 */ 5755 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5756 long currentTime, UserHandle user) throws PackageManagerException { 5757 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5758 parseFlags |= mDefParseFlags; 5759 PackageParser pp = new PackageParser(); 5760 pp.setSeparateProcesses(mSeparateProcesses); 5761 pp.setOnlyCoreApps(mOnlyCore); 5762 pp.setDisplayMetrics(mMetrics); 5763 5764 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5765 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5766 } 5767 5768 final PackageParser.Package pkg; 5769 try { 5770 pkg = pp.parsePackage(scanFile, parseFlags); 5771 } catch (PackageParserException e) { 5772 throw PackageManagerException.from(e); 5773 } 5774 5775 PackageSetting ps = null; 5776 PackageSetting updatedPkg; 5777 // reader 5778 synchronized (mPackages) { 5779 // Look to see if we already know about this package. 5780 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5781 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5782 // This package has been renamed to its original name. Let's 5783 // use that. 5784 ps = mSettings.peekPackageLPr(oldName); 5785 } 5786 // If there was no original package, see one for the real package name. 5787 if (ps == null) { 5788 ps = mSettings.peekPackageLPr(pkg.packageName); 5789 } 5790 // Check to see if this package could be hiding/updating a system 5791 // package. Must look for it either under the original or real 5792 // package name depending on our state. 5793 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5794 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5795 } 5796 boolean updatedPkgBetter = false; 5797 // First check if this is a system package that may involve an update 5798 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5799 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5800 // it needs to drop FLAG_PRIVILEGED. 5801 if (locationIsPrivileged(scanFile)) { 5802 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5803 } else { 5804 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5805 } 5806 5807 if (ps != null && !ps.codePath.equals(scanFile)) { 5808 // The path has changed from what was last scanned... check the 5809 // version of the new path against what we have stored to determine 5810 // what to do. 5811 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5812 if (pkg.mVersionCode <= ps.versionCode) { 5813 // The system package has been updated and the code path does not match 5814 // Ignore entry. Skip it. 5815 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5816 + " ignored: updated version " + ps.versionCode 5817 + " better than this " + pkg.mVersionCode); 5818 if (!updatedPkg.codePath.equals(scanFile)) { 5819 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5820 + ps.name + " changing from " + updatedPkg.codePathString 5821 + " to " + scanFile); 5822 updatedPkg.codePath = scanFile; 5823 updatedPkg.codePathString = scanFile.toString(); 5824 updatedPkg.resourcePath = scanFile; 5825 updatedPkg.resourcePathString = scanFile.toString(); 5826 } 5827 updatedPkg.pkg = pkg; 5828 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5829 "Package " + ps.name + " at " + scanFile 5830 + " ignored: updated version " + ps.versionCode 5831 + " better than this " + pkg.mVersionCode); 5832 } else { 5833 // The current app on the system partition is better than 5834 // what we have updated to on the data partition; switch 5835 // back to the system partition version. 5836 // At this point, its safely assumed that package installation for 5837 // apps in system partition will go through. If not there won't be a working 5838 // version of the app 5839 // writer 5840 synchronized (mPackages) { 5841 // Just remove the loaded entries from package lists. 5842 mPackages.remove(ps.name); 5843 } 5844 5845 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5846 + " reverting from " + ps.codePathString 5847 + ": new version " + pkg.mVersionCode 5848 + " better than installed " + ps.versionCode); 5849 5850 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5851 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5852 synchronized (mInstallLock) { 5853 args.cleanUpResourcesLI(); 5854 } 5855 synchronized (mPackages) { 5856 mSettings.enableSystemPackageLPw(ps.name); 5857 } 5858 updatedPkgBetter = true; 5859 } 5860 } 5861 } 5862 5863 if (updatedPkg != null) { 5864 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5865 // initially 5866 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5867 5868 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5869 // flag set initially 5870 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5871 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5872 } 5873 } 5874 5875 // Verify certificates against what was last scanned 5876 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5877 5878 /* 5879 * A new system app appeared, but we already had a non-system one of the 5880 * same name installed earlier. 5881 */ 5882 boolean shouldHideSystemApp = false; 5883 if (updatedPkg == null && ps != null 5884 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5885 /* 5886 * Check to make sure the signatures match first. If they don't, 5887 * wipe the installed application and its data. 5888 */ 5889 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5890 != PackageManager.SIGNATURE_MATCH) { 5891 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5892 + " signatures don't match existing userdata copy; removing"); 5893 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5894 ps = null; 5895 } else { 5896 /* 5897 * If the newly-added system app is an older version than the 5898 * already installed version, hide it. It will be scanned later 5899 * and re-added like an update. 5900 */ 5901 if (pkg.mVersionCode <= ps.versionCode) { 5902 shouldHideSystemApp = true; 5903 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5904 + " but new version " + pkg.mVersionCode + " better than installed " 5905 + ps.versionCode + "; hiding system"); 5906 } else { 5907 /* 5908 * The newly found system app is a newer version that the 5909 * one previously installed. Simply remove the 5910 * already-installed application and replace it with our own 5911 * while keeping the application data. 5912 */ 5913 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5914 + " reverting from " + ps.codePathString + ": new version " 5915 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5916 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5917 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5918 synchronized (mInstallLock) { 5919 args.cleanUpResourcesLI(); 5920 } 5921 } 5922 } 5923 } 5924 5925 // The apk is forward locked (not public) if its code and resources 5926 // are kept in different files. (except for app in either system or 5927 // vendor path). 5928 // TODO grab this value from PackageSettings 5929 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5930 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5931 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5932 } 5933 } 5934 5935 // TODO: extend to support forward-locked splits 5936 String resourcePath = null; 5937 String baseResourcePath = null; 5938 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5939 if (ps != null && ps.resourcePathString != null) { 5940 resourcePath = ps.resourcePathString; 5941 baseResourcePath = ps.resourcePathString; 5942 } else { 5943 // Should not happen at all. Just log an error. 5944 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5945 } 5946 } else { 5947 resourcePath = pkg.codePath; 5948 baseResourcePath = pkg.baseCodePath; 5949 } 5950 5951 // Set application objects path explicitly. 5952 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5953 pkg.applicationInfo.setCodePath(pkg.codePath); 5954 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5955 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5956 pkg.applicationInfo.setResourcePath(resourcePath); 5957 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5958 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5959 5960 // Note that we invoke the following method only if we are about to unpack an application 5961 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5962 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5963 5964 /* 5965 * If the system app should be overridden by a previously installed 5966 * data, hide the system app now and let the /data/app scan pick it up 5967 * again. 5968 */ 5969 if (shouldHideSystemApp) { 5970 synchronized (mPackages) { 5971 /* 5972 * We have to grant systems permissions before we hide, because 5973 * grantPermissions will assume the package update is trying to 5974 * expand its permissions. 5975 */ 5976 grantPermissionsLPw(pkg, true, pkg.packageName); 5977 mSettings.disableSystemPackageLPw(pkg.packageName); 5978 } 5979 } 5980 5981 return scannedPkg; 5982 } 5983 5984 private static String fixProcessName(String defProcessName, 5985 String processName, int uid) { 5986 if (processName == null) { 5987 return defProcessName; 5988 } 5989 return processName; 5990 } 5991 5992 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5993 throws PackageManagerException { 5994 if (pkgSetting.signatures.mSignatures != null) { 5995 // Already existing package. Make sure signatures match 5996 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5997 == PackageManager.SIGNATURE_MATCH; 5998 if (!match) { 5999 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6000 == PackageManager.SIGNATURE_MATCH; 6001 } 6002 if (!match) { 6003 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6004 == PackageManager.SIGNATURE_MATCH; 6005 } 6006 if (!match) { 6007 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6008 + pkg.packageName + " signatures do not match the " 6009 + "previously installed version; ignoring!"); 6010 } 6011 } 6012 6013 // Check for shared user signatures 6014 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6015 // Already existing package. Make sure signatures match 6016 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6017 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6018 if (!match) { 6019 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6020 == PackageManager.SIGNATURE_MATCH; 6021 } 6022 if (!match) { 6023 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6024 == PackageManager.SIGNATURE_MATCH; 6025 } 6026 if (!match) { 6027 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6028 "Package " + pkg.packageName 6029 + " has no signatures that match those in shared user " 6030 + pkgSetting.sharedUser.name + "; ignoring!"); 6031 } 6032 } 6033 } 6034 6035 /** 6036 * Enforces that only the system UID or root's UID can call a method exposed 6037 * via Binder. 6038 * 6039 * @param message used as message if SecurityException is thrown 6040 * @throws SecurityException if the caller is not system or root 6041 */ 6042 private static final void enforceSystemOrRoot(String message) { 6043 final int uid = Binder.getCallingUid(); 6044 if (uid != Process.SYSTEM_UID && uid != 0) { 6045 throw new SecurityException(message); 6046 } 6047 } 6048 6049 @Override 6050 public void performBootDexOpt() { 6051 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6052 6053 // Before everything else, see whether we need to fstrim. 6054 try { 6055 IMountService ms = PackageHelper.getMountService(); 6056 if (ms != null) { 6057 final boolean isUpgrade = isUpgrade(); 6058 boolean doTrim = isUpgrade; 6059 if (doTrim) { 6060 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6061 } else { 6062 final long interval = android.provider.Settings.Global.getLong( 6063 mContext.getContentResolver(), 6064 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6065 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6066 if (interval > 0) { 6067 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6068 if (timeSinceLast > interval) { 6069 doTrim = true; 6070 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6071 + "; running immediately"); 6072 } 6073 } 6074 } 6075 if (doTrim) { 6076 if (!isFirstBoot()) { 6077 try { 6078 ActivityManagerNative.getDefault().showBootMessage( 6079 mContext.getResources().getString( 6080 R.string.android_upgrading_fstrim), true); 6081 } catch (RemoteException e) { 6082 } 6083 } 6084 ms.runMaintenance(); 6085 } 6086 } else { 6087 Slog.e(TAG, "Mount service unavailable!"); 6088 } 6089 } catch (RemoteException e) { 6090 // Can't happen; MountService is local 6091 } 6092 6093 final ArraySet<PackageParser.Package> pkgs; 6094 synchronized (mPackages) { 6095 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6096 } 6097 6098 if (pkgs != null) { 6099 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6100 // in case the device runs out of space. 6101 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6102 // Give priority to core apps. 6103 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6104 PackageParser.Package pkg = it.next(); 6105 if (pkg.coreApp) { 6106 if (DEBUG_DEXOPT) { 6107 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6108 } 6109 sortedPkgs.add(pkg); 6110 it.remove(); 6111 } 6112 } 6113 // Give priority to system apps that listen for pre boot complete. 6114 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6115 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6116 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6117 PackageParser.Package pkg = it.next(); 6118 if (pkgNames.contains(pkg.packageName)) { 6119 if (DEBUG_DEXOPT) { 6120 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6121 } 6122 sortedPkgs.add(pkg); 6123 it.remove(); 6124 } 6125 } 6126 // Give priority to system apps. 6127 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6128 PackageParser.Package pkg = it.next(); 6129 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6130 if (DEBUG_DEXOPT) { 6131 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6132 } 6133 sortedPkgs.add(pkg); 6134 it.remove(); 6135 } 6136 } 6137 // Give priority to updated system apps. 6138 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6139 PackageParser.Package pkg = it.next(); 6140 if (pkg.isUpdatedSystemApp()) { 6141 if (DEBUG_DEXOPT) { 6142 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6143 } 6144 sortedPkgs.add(pkg); 6145 it.remove(); 6146 } 6147 } 6148 // Give priority to apps that listen for boot complete. 6149 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6150 pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6151 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6152 PackageParser.Package pkg = it.next(); 6153 if (pkgNames.contains(pkg.packageName)) { 6154 if (DEBUG_DEXOPT) { 6155 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6156 } 6157 sortedPkgs.add(pkg); 6158 it.remove(); 6159 } 6160 } 6161 // Filter out packages that aren't recently used. 6162 filterRecentlyUsedApps(pkgs); 6163 // Add all remaining apps. 6164 for (PackageParser.Package pkg : pkgs) { 6165 if (DEBUG_DEXOPT) { 6166 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6167 } 6168 sortedPkgs.add(pkg); 6169 } 6170 6171 // If we want to be lazy, filter everything that wasn't recently used. 6172 if (mLazyDexOpt) { 6173 filterRecentlyUsedApps(sortedPkgs); 6174 } 6175 6176 int i = 0; 6177 int total = sortedPkgs.size(); 6178 File dataDir = Environment.getDataDirectory(); 6179 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6180 if (lowThreshold == 0) { 6181 throw new IllegalStateException("Invalid low memory threshold"); 6182 } 6183 for (PackageParser.Package pkg : sortedPkgs) { 6184 long usableSpace = dataDir.getUsableSpace(); 6185 if (usableSpace < lowThreshold) { 6186 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6187 break; 6188 } 6189 performBootDexOpt(pkg, ++i, total); 6190 } 6191 } 6192 } 6193 6194 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6195 // Filter out packages that aren't recently used. 6196 // 6197 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6198 // should do a full dexopt. 6199 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6200 int total = pkgs.size(); 6201 int skipped = 0; 6202 long now = System.currentTimeMillis(); 6203 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6204 PackageParser.Package pkg = i.next(); 6205 long then = pkg.mLastPackageUsageTimeInMills; 6206 if (then + mDexOptLRUThresholdInMills < now) { 6207 if (DEBUG_DEXOPT) { 6208 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6209 ((then == 0) ? "never" : new Date(then))); 6210 } 6211 i.remove(); 6212 skipped++; 6213 } 6214 } 6215 if (DEBUG_DEXOPT) { 6216 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6217 } 6218 } 6219 } 6220 6221 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6222 List<ResolveInfo> ris = null; 6223 try { 6224 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6225 intent, null, 0, userId); 6226 } catch (RemoteException e) { 6227 } 6228 ArraySet<String> pkgNames = new ArraySet<String>(); 6229 if (ris != null) { 6230 for (ResolveInfo ri : ris) { 6231 pkgNames.add(ri.activityInfo.packageName); 6232 } 6233 } 6234 return pkgNames; 6235 } 6236 6237 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6238 if (DEBUG_DEXOPT) { 6239 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6240 } 6241 if (!isFirstBoot()) { 6242 try { 6243 ActivityManagerNative.getDefault().showBootMessage( 6244 mContext.getResources().getString(R.string.android_upgrading_apk, 6245 curr, total), true); 6246 } catch (RemoteException e) { 6247 } 6248 } 6249 PackageParser.Package p = pkg; 6250 synchronized (mInstallLock) { 6251 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6252 false /* force dex */, false /* defer */, true /* include dependencies */); 6253 } 6254 } 6255 6256 @Override 6257 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6258 return performDexOpt(packageName, instructionSet, false); 6259 } 6260 6261 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6262 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6263 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6264 if (!dexopt && !updateUsage) { 6265 // We aren't going to dexopt or update usage, so bail early. 6266 return false; 6267 } 6268 PackageParser.Package p; 6269 final String targetInstructionSet; 6270 synchronized (mPackages) { 6271 p = mPackages.get(packageName); 6272 if (p == null) { 6273 return false; 6274 } 6275 if (updateUsage) { 6276 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6277 } 6278 mPackageUsage.write(false); 6279 if (!dexopt) { 6280 // We aren't going to dexopt, so bail early. 6281 return false; 6282 } 6283 6284 targetInstructionSet = instructionSet != null ? instructionSet : 6285 getPrimaryInstructionSet(p.applicationInfo); 6286 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6287 return false; 6288 } 6289 } 6290 long callingId = Binder.clearCallingIdentity(); 6291 try { 6292 synchronized (mInstallLock) { 6293 final String[] instructionSets = new String[] { targetInstructionSet }; 6294 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6295 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6296 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6297 } 6298 } finally { 6299 Binder.restoreCallingIdentity(callingId); 6300 } 6301 } 6302 6303 public ArraySet<String> getPackagesThatNeedDexOpt() { 6304 ArraySet<String> pkgs = null; 6305 synchronized (mPackages) { 6306 for (PackageParser.Package p : mPackages.values()) { 6307 if (DEBUG_DEXOPT) { 6308 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6309 } 6310 if (!p.mDexOptPerformed.isEmpty()) { 6311 continue; 6312 } 6313 if (pkgs == null) { 6314 pkgs = new ArraySet<String>(); 6315 } 6316 pkgs.add(p.packageName); 6317 } 6318 } 6319 return pkgs; 6320 } 6321 6322 public void shutdown() { 6323 mPackageUsage.write(true); 6324 } 6325 6326 @Override 6327 public void forceDexOpt(String packageName) { 6328 enforceSystemOrRoot("forceDexOpt"); 6329 6330 PackageParser.Package pkg; 6331 synchronized (mPackages) { 6332 pkg = mPackages.get(packageName); 6333 if (pkg == null) { 6334 throw new IllegalArgumentException("Missing package: " + packageName); 6335 } 6336 } 6337 6338 synchronized (mInstallLock) { 6339 final String[] instructionSets = new String[] { 6340 getPrimaryInstructionSet(pkg.applicationInfo) }; 6341 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6342 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6343 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6344 throw new IllegalStateException("Failed to dexopt: " + res); 6345 } 6346 } 6347 } 6348 6349 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6350 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6351 Slog.w(TAG, "Unable to update from " + oldPkg.name 6352 + " to " + newPkg.packageName 6353 + ": old package not in system partition"); 6354 return false; 6355 } else if (mPackages.get(oldPkg.name) != null) { 6356 Slog.w(TAG, "Unable to update from " + oldPkg.name 6357 + " to " + newPkg.packageName 6358 + ": old package still exists"); 6359 return false; 6360 } 6361 return true; 6362 } 6363 6364 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6365 int[] users = sUserManager.getUserIds(); 6366 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6367 if (res < 0) { 6368 return res; 6369 } 6370 for (int user : users) { 6371 if (user != 0) { 6372 res = mInstaller.createUserData(volumeUuid, packageName, 6373 UserHandle.getUid(user, uid), user, seinfo); 6374 if (res < 0) { 6375 return res; 6376 } 6377 } 6378 } 6379 return res; 6380 } 6381 6382 private int removeDataDirsLI(String volumeUuid, String packageName) { 6383 int[] users = sUserManager.getUserIds(); 6384 int res = 0; 6385 for (int user : users) { 6386 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6387 if (resInner < 0) { 6388 res = resInner; 6389 } 6390 } 6391 6392 return res; 6393 } 6394 6395 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6396 int[] users = sUserManager.getUserIds(); 6397 int res = 0; 6398 for (int user : users) { 6399 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6400 if (resInner < 0) { 6401 res = resInner; 6402 } 6403 } 6404 return res; 6405 } 6406 6407 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6408 PackageParser.Package changingLib) { 6409 if (file.path != null) { 6410 usesLibraryFiles.add(file.path); 6411 return; 6412 } 6413 PackageParser.Package p = mPackages.get(file.apk); 6414 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6415 // If we are doing this while in the middle of updating a library apk, 6416 // then we need to make sure to use that new apk for determining the 6417 // dependencies here. (We haven't yet finished committing the new apk 6418 // to the package manager state.) 6419 if (p == null || p.packageName.equals(changingLib.packageName)) { 6420 p = changingLib; 6421 } 6422 } 6423 if (p != null) { 6424 usesLibraryFiles.addAll(p.getAllCodePaths()); 6425 } 6426 } 6427 6428 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6429 PackageParser.Package changingLib) throws PackageManagerException { 6430 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6431 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6432 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6433 for (int i=0; i<N; i++) { 6434 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6435 if (file == null) { 6436 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6437 "Package " + pkg.packageName + " requires unavailable shared library " 6438 + pkg.usesLibraries.get(i) + "; failing!"); 6439 } 6440 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6441 } 6442 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6443 for (int i=0; i<N; i++) { 6444 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6445 if (file == null) { 6446 Slog.w(TAG, "Package " + pkg.packageName 6447 + " desires unavailable shared library " 6448 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6449 } else { 6450 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6451 } 6452 } 6453 N = usesLibraryFiles.size(); 6454 if (N > 0) { 6455 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6456 } else { 6457 pkg.usesLibraryFiles = null; 6458 } 6459 } 6460 } 6461 6462 private static boolean hasString(List<String> list, List<String> which) { 6463 if (list == null) { 6464 return false; 6465 } 6466 for (int i=list.size()-1; i>=0; i--) { 6467 for (int j=which.size()-1; j>=0; j--) { 6468 if (which.get(j).equals(list.get(i))) { 6469 return true; 6470 } 6471 } 6472 } 6473 return false; 6474 } 6475 6476 private void updateAllSharedLibrariesLPw() { 6477 for (PackageParser.Package pkg : mPackages.values()) { 6478 try { 6479 updateSharedLibrariesLPw(pkg, null); 6480 } catch (PackageManagerException e) { 6481 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6482 } 6483 } 6484 } 6485 6486 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6487 PackageParser.Package changingPkg) { 6488 ArrayList<PackageParser.Package> res = null; 6489 for (PackageParser.Package pkg : mPackages.values()) { 6490 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6491 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6492 if (res == null) { 6493 res = new ArrayList<PackageParser.Package>(); 6494 } 6495 res.add(pkg); 6496 try { 6497 updateSharedLibrariesLPw(pkg, changingPkg); 6498 } catch (PackageManagerException e) { 6499 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6500 } 6501 } 6502 } 6503 return res; 6504 } 6505 6506 /** 6507 * Derive the value of the {@code cpuAbiOverride} based on the provided 6508 * value and an optional stored value from the package settings. 6509 */ 6510 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6511 String cpuAbiOverride = null; 6512 6513 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6514 cpuAbiOverride = null; 6515 } else if (abiOverride != null) { 6516 cpuAbiOverride = abiOverride; 6517 } else if (settings != null) { 6518 cpuAbiOverride = settings.cpuAbiOverrideString; 6519 } 6520 6521 return cpuAbiOverride; 6522 } 6523 6524 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6525 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6526 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6527 try { 6528 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6529 } finally { 6530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6531 } 6532 } 6533 6534 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6535 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6536 boolean success = false; 6537 try { 6538 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6539 currentTime, user); 6540 success = true; 6541 return res; 6542 } finally { 6543 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6544 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6545 } 6546 } 6547 } 6548 6549 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6550 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6551 final File scanFile = new File(pkg.codePath); 6552 if (pkg.applicationInfo.getCodePath() == null || 6553 pkg.applicationInfo.getResourcePath() == null) { 6554 // Bail out. The resource and code paths haven't been set. 6555 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6556 "Code and resource paths haven't been set correctly"); 6557 } 6558 6559 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6560 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6561 } else { 6562 // Only allow system apps to be flagged as core apps. 6563 pkg.coreApp = false; 6564 } 6565 6566 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6567 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6568 } 6569 6570 if (mCustomResolverComponentName != null && 6571 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6572 setUpCustomResolverActivity(pkg); 6573 } 6574 6575 if (pkg.packageName.equals("android")) { 6576 synchronized (mPackages) { 6577 if (mAndroidApplication != null) { 6578 Slog.w(TAG, "*************************************************"); 6579 Slog.w(TAG, "Core android package being redefined. Skipping."); 6580 Slog.w(TAG, " file=" + scanFile); 6581 Slog.w(TAG, "*************************************************"); 6582 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6583 "Core android package being redefined. Skipping."); 6584 } 6585 6586 // Set up information for our fall-back user intent resolution activity. 6587 mPlatformPackage = pkg; 6588 pkg.mVersionCode = mSdkVersion; 6589 mAndroidApplication = pkg.applicationInfo; 6590 6591 if (!mResolverReplaced) { 6592 mResolveActivity.applicationInfo = mAndroidApplication; 6593 mResolveActivity.name = ResolverActivity.class.getName(); 6594 mResolveActivity.packageName = mAndroidApplication.packageName; 6595 mResolveActivity.processName = "system:ui"; 6596 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6597 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6598 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6599 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6600 mResolveActivity.exported = true; 6601 mResolveActivity.enabled = true; 6602 mResolveInfo.activityInfo = mResolveActivity; 6603 mResolveInfo.priority = 0; 6604 mResolveInfo.preferredOrder = 0; 6605 mResolveInfo.match = 0; 6606 mResolveComponentName = new ComponentName( 6607 mAndroidApplication.packageName, mResolveActivity.name); 6608 } 6609 } 6610 } 6611 6612 if (DEBUG_PACKAGE_SCANNING) { 6613 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6614 Log.d(TAG, "Scanning package " + pkg.packageName); 6615 } 6616 6617 if (mPackages.containsKey(pkg.packageName) 6618 || mSharedLibraries.containsKey(pkg.packageName)) { 6619 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6620 "Application package " + pkg.packageName 6621 + " already installed. Skipping duplicate."); 6622 } 6623 6624 // If we're only installing presumed-existing packages, require that the 6625 // scanned APK is both already known and at the path previously established 6626 // for it. Previously unknown packages we pick up normally, but if we have an 6627 // a priori expectation about this package's install presence, enforce it. 6628 // With a singular exception for new system packages. When an OTA contains 6629 // a new system package, we allow the codepath to change from a system location 6630 // to the user-installed location. If we don't allow this change, any newer, 6631 // user-installed version of the application will be ignored. 6632 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6633 if (mExpectingBetter.containsKey(pkg.packageName)) { 6634 logCriticalInfo(Log.WARN, 6635 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6636 } else { 6637 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6638 if (known != null) { 6639 if (DEBUG_PACKAGE_SCANNING) { 6640 Log.d(TAG, "Examining " + pkg.codePath 6641 + " and requiring known paths " + known.codePathString 6642 + " & " + known.resourcePathString); 6643 } 6644 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6645 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6646 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6647 "Application package " + pkg.packageName 6648 + " found at " + pkg.applicationInfo.getCodePath() 6649 + " but expected at " + known.codePathString + "; ignoring."); 6650 } 6651 } 6652 } 6653 } 6654 6655 // Initialize package source and resource directories 6656 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6657 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6658 6659 SharedUserSetting suid = null; 6660 PackageSetting pkgSetting = null; 6661 6662 if (!isSystemApp(pkg)) { 6663 // Only system apps can use these features. 6664 pkg.mOriginalPackages = null; 6665 pkg.mRealPackage = null; 6666 pkg.mAdoptPermissions = null; 6667 } 6668 6669 // writer 6670 synchronized (mPackages) { 6671 if (pkg.mSharedUserId != null) { 6672 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6673 if (suid == null) { 6674 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6675 "Creating application package " + pkg.packageName 6676 + " for shared user failed"); 6677 } 6678 if (DEBUG_PACKAGE_SCANNING) { 6679 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6680 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6681 + "): packages=" + suid.packages); 6682 } 6683 } 6684 6685 // Check if we are renaming from an original package name. 6686 PackageSetting origPackage = null; 6687 String realName = null; 6688 if (pkg.mOriginalPackages != null) { 6689 // This package may need to be renamed to a previously 6690 // installed name. Let's check on that... 6691 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6692 if (pkg.mOriginalPackages.contains(renamed)) { 6693 // This package had originally been installed as the 6694 // original name, and we have already taken care of 6695 // transitioning to the new one. Just update the new 6696 // one to continue using the old name. 6697 realName = pkg.mRealPackage; 6698 if (!pkg.packageName.equals(renamed)) { 6699 // Callers into this function may have already taken 6700 // care of renaming the package; only do it here if 6701 // it is not already done. 6702 pkg.setPackageName(renamed); 6703 } 6704 6705 } else { 6706 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6707 if ((origPackage = mSettings.peekPackageLPr( 6708 pkg.mOriginalPackages.get(i))) != null) { 6709 // We do have the package already installed under its 6710 // original name... should we use it? 6711 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6712 // New package is not compatible with original. 6713 origPackage = null; 6714 continue; 6715 } else if (origPackage.sharedUser != null) { 6716 // Make sure uid is compatible between packages. 6717 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6718 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6719 + " to " + pkg.packageName + ": old uid " 6720 + origPackage.sharedUser.name 6721 + " differs from " + pkg.mSharedUserId); 6722 origPackage = null; 6723 continue; 6724 } 6725 } else { 6726 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6727 + pkg.packageName + " to old name " + origPackage.name); 6728 } 6729 break; 6730 } 6731 } 6732 } 6733 } 6734 6735 if (mTransferedPackages.contains(pkg.packageName)) { 6736 Slog.w(TAG, "Package " + pkg.packageName 6737 + " was transferred to another, but its .apk remains"); 6738 } 6739 6740 // Just create the setting, don't add it yet. For already existing packages 6741 // the PkgSetting exists already and doesn't have to be created. 6742 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6743 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6744 pkg.applicationInfo.primaryCpuAbi, 6745 pkg.applicationInfo.secondaryCpuAbi, 6746 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6747 user, false); 6748 if (pkgSetting == null) { 6749 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6750 "Creating application package " + pkg.packageName + " failed"); 6751 } 6752 6753 if (pkgSetting.origPackage != null) { 6754 // If we are first transitioning from an original package, 6755 // fix up the new package's name now. We need to do this after 6756 // looking up the package under its new name, so getPackageLP 6757 // can take care of fiddling things correctly. 6758 pkg.setPackageName(origPackage.name); 6759 6760 // File a report about this. 6761 String msg = "New package " + pkgSetting.realName 6762 + " renamed to replace old package " + pkgSetting.name; 6763 reportSettingsProblem(Log.WARN, msg); 6764 6765 // Make a note of it. 6766 mTransferedPackages.add(origPackage.name); 6767 6768 // No longer need to retain this. 6769 pkgSetting.origPackage = null; 6770 } 6771 6772 if (realName != null) { 6773 // Make a note of it. 6774 mTransferedPackages.add(pkg.packageName); 6775 } 6776 6777 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6778 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6779 } 6780 6781 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6782 // Check all shared libraries and map to their actual file path. 6783 // We only do this here for apps not on a system dir, because those 6784 // are the only ones that can fail an install due to this. We 6785 // will take care of the system apps by updating all of their 6786 // library paths after the scan is done. 6787 updateSharedLibrariesLPw(pkg, null); 6788 } 6789 6790 if (mFoundPolicyFile) { 6791 SELinuxMMAC.assignSeinfoValue(pkg); 6792 } 6793 6794 pkg.applicationInfo.uid = pkgSetting.appId; 6795 pkg.mExtras = pkgSetting; 6796 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6797 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6798 // We just determined the app is signed correctly, so bring 6799 // over the latest parsed certs. 6800 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6801 } else { 6802 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6803 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6804 "Package " + pkg.packageName + " upgrade keys do not match the " 6805 + "previously installed version"); 6806 } else { 6807 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6808 String msg = "System package " + pkg.packageName 6809 + " signature changed; retaining data."; 6810 reportSettingsProblem(Log.WARN, msg); 6811 } 6812 } 6813 } else { 6814 try { 6815 verifySignaturesLP(pkgSetting, pkg); 6816 // We just determined the app is signed correctly, so bring 6817 // over the latest parsed certs. 6818 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6819 } catch (PackageManagerException e) { 6820 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6821 throw e; 6822 } 6823 // The signature has changed, but this package is in the system 6824 // image... let's recover! 6825 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6826 // However... if this package is part of a shared user, but it 6827 // doesn't match the signature of the shared user, let's fail. 6828 // What this means is that you can't change the signatures 6829 // associated with an overall shared user, which doesn't seem all 6830 // that unreasonable. 6831 if (pkgSetting.sharedUser != null) { 6832 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6833 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6834 throw new PackageManagerException( 6835 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6836 "Signature mismatch for shared user : " 6837 + pkgSetting.sharedUser); 6838 } 6839 } 6840 // File a report about this. 6841 String msg = "System package " + pkg.packageName 6842 + " signature changed; retaining data."; 6843 reportSettingsProblem(Log.WARN, msg); 6844 } 6845 } 6846 // Verify that this new package doesn't have any content providers 6847 // that conflict with existing packages. Only do this if the 6848 // package isn't already installed, since we don't want to break 6849 // things that are installed. 6850 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6851 final int N = pkg.providers.size(); 6852 int i; 6853 for (i=0; i<N; i++) { 6854 PackageParser.Provider p = pkg.providers.get(i); 6855 if (p.info.authority != null) { 6856 String names[] = p.info.authority.split(";"); 6857 for (int j = 0; j < names.length; j++) { 6858 if (mProvidersByAuthority.containsKey(names[j])) { 6859 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6860 final String otherPackageName = 6861 ((other != null && other.getComponentName() != null) ? 6862 other.getComponentName().getPackageName() : "?"); 6863 throw new PackageManagerException( 6864 INSTALL_FAILED_CONFLICTING_PROVIDER, 6865 "Can't install because provider name " + names[j] 6866 + " (in package " + pkg.applicationInfo.packageName 6867 + ") is already used by " + otherPackageName); 6868 } 6869 } 6870 } 6871 } 6872 } 6873 6874 if (pkg.mAdoptPermissions != null) { 6875 // This package wants to adopt ownership of permissions from 6876 // another package. 6877 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6878 final String origName = pkg.mAdoptPermissions.get(i); 6879 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6880 if (orig != null) { 6881 if (verifyPackageUpdateLPr(orig, pkg)) { 6882 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6883 + pkg.packageName); 6884 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6885 } 6886 } 6887 } 6888 } 6889 } 6890 6891 final String pkgName = pkg.packageName; 6892 6893 final long scanFileTime = scanFile.lastModified(); 6894 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6895 pkg.applicationInfo.processName = fixProcessName( 6896 pkg.applicationInfo.packageName, 6897 pkg.applicationInfo.processName, 6898 pkg.applicationInfo.uid); 6899 6900 File dataPath; 6901 if (mPlatformPackage == pkg) { 6902 // The system package is special. 6903 dataPath = new File(Environment.getDataDirectory(), "system"); 6904 6905 pkg.applicationInfo.dataDir = dataPath.getPath(); 6906 6907 } else { 6908 // This is a normal package, need to make its data directory. 6909 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6910 UserHandle.USER_OWNER, pkg.packageName); 6911 6912 boolean uidError = false; 6913 if (dataPath.exists()) { 6914 int currentUid = 0; 6915 try { 6916 StructStat stat = Os.stat(dataPath.getPath()); 6917 currentUid = stat.st_uid; 6918 } catch (ErrnoException e) { 6919 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6920 } 6921 6922 // If we have mismatched owners for the data path, we have a problem. 6923 if (currentUid != pkg.applicationInfo.uid) { 6924 boolean recovered = false; 6925 if (currentUid == 0) { 6926 // The directory somehow became owned by root. Wow. 6927 // This is probably because the system was stopped while 6928 // installd was in the middle of messing with its libs 6929 // directory. Ask installd to fix that. 6930 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6931 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6932 if (ret >= 0) { 6933 recovered = true; 6934 String msg = "Package " + pkg.packageName 6935 + " unexpectedly changed to uid 0; recovered to " + 6936 + pkg.applicationInfo.uid; 6937 reportSettingsProblem(Log.WARN, msg); 6938 } 6939 } 6940 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6941 || (scanFlags&SCAN_BOOTING) != 0)) { 6942 // If this is a system app, we can at least delete its 6943 // current data so the application will still work. 6944 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6945 if (ret >= 0) { 6946 // TODO: Kill the processes first 6947 // Old data gone! 6948 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6949 ? "System package " : "Third party package "; 6950 String msg = prefix + pkg.packageName 6951 + " has changed from uid: " 6952 + currentUid + " to " 6953 + pkg.applicationInfo.uid + "; old data erased"; 6954 reportSettingsProblem(Log.WARN, msg); 6955 recovered = true; 6956 6957 // And now re-install the app. 6958 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6959 pkg.applicationInfo.seinfo); 6960 if (ret == -1) { 6961 // Ack should not happen! 6962 msg = prefix + pkg.packageName 6963 + " could not have data directory re-created after delete."; 6964 reportSettingsProblem(Log.WARN, msg); 6965 throw new PackageManagerException( 6966 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6967 } 6968 } 6969 if (!recovered) { 6970 mHasSystemUidErrors = true; 6971 } 6972 } else if (!recovered) { 6973 // If we allow this install to proceed, we will be broken. 6974 // Abort, abort! 6975 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6976 "scanPackageLI"); 6977 } 6978 if (!recovered) { 6979 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6980 + pkg.applicationInfo.uid + "/fs_" 6981 + currentUid; 6982 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6983 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6984 String msg = "Package " + pkg.packageName 6985 + " has mismatched uid: " 6986 + currentUid + " on disk, " 6987 + pkg.applicationInfo.uid + " in settings"; 6988 // writer 6989 synchronized (mPackages) { 6990 mSettings.mReadMessages.append(msg); 6991 mSettings.mReadMessages.append('\n'); 6992 uidError = true; 6993 if (!pkgSetting.uidError) { 6994 reportSettingsProblem(Log.ERROR, msg); 6995 } 6996 } 6997 } 6998 } 6999 pkg.applicationInfo.dataDir = dataPath.getPath(); 7000 if (mShouldRestoreconData) { 7001 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7002 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7003 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7004 } 7005 } else { 7006 if (DEBUG_PACKAGE_SCANNING) { 7007 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7008 Log.v(TAG, "Want this data dir: " + dataPath); 7009 } 7010 //invoke installer to do the actual installation 7011 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7012 pkg.applicationInfo.seinfo); 7013 if (ret < 0) { 7014 // Error from installer 7015 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7016 "Unable to create data dirs [errorCode=" + ret + "]"); 7017 } 7018 7019 if (dataPath.exists()) { 7020 pkg.applicationInfo.dataDir = dataPath.getPath(); 7021 } else { 7022 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7023 pkg.applicationInfo.dataDir = null; 7024 } 7025 } 7026 7027 pkgSetting.uidError = uidError; 7028 } 7029 7030 final String path = scanFile.getPath(); 7031 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7032 7033 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7034 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7035 7036 // Some system apps still use directory structure for native libraries 7037 // in which case we might end up not detecting abi solely based on apk 7038 // structure. Try to detect abi based on directory structure. 7039 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7040 pkg.applicationInfo.primaryCpuAbi == null) { 7041 setBundledAppAbisAndRoots(pkg, pkgSetting); 7042 setNativeLibraryPaths(pkg); 7043 } 7044 7045 } else { 7046 if ((scanFlags & SCAN_MOVE) != 0) { 7047 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7048 // but we already have this packages package info in the PackageSetting. We just 7049 // use that and derive the native library path based on the new codepath. 7050 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7051 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7052 } 7053 7054 // Set native library paths again. For moves, the path will be updated based on the 7055 // ABIs we've determined above. For non-moves, the path will be updated based on the 7056 // ABIs we determined during compilation, but the path will depend on the final 7057 // package path (after the rename away from the stage path). 7058 setNativeLibraryPaths(pkg); 7059 } 7060 7061 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7062 final int[] userIds = sUserManager.getUserIds(); 7063 synchronized (mInstallLock) { 7064 // Make sure all user data directories are ready to roll; we're okay 7065 // if they already exist 7066 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7067 for (int userId : userIds) { 7068 if (userId != 0) { 7069 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7070 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7071 pkg.applicationInfo.seinfo); 7072 } 7073 } 7074 } 7075 7076 // Create a native library symlink only if we have native libraries 7077 // and if the native libraries are 32 bit libraries. We do not provide 7078 // this symlink for 64 bit libraries. 7079 if (pkg.applicationInfo.primaryCpuAbi != null && 7080 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7081 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7082 try { 7083 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7084 for (int userId : userIds) { 7085 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7086 nativeLibPath, userId) < 0) { 7087 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7088 "Failed linking native library dir (user=" + userId + ")"); 7089 } 7090 } 7091 } finally { 7092 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7093 } 7094 } 7095 } 7096 7097 // This is a special case for the "system" package, where the ABI is 7098 // dictated by the zygote configuration (and init.rc). We should keep track 7099 // of this ABI so that we can deal with "normal" applications that run under 7100 // the same UID correctly. 7101 if (mPlatformPackage == pkg) { 7102 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7103 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7104 } 7105 7106 // If there's a mismatch between the abi-override in the package setting 7107 // and the abiOverride specified for the install. Warn about this because we 7108 // would've already compiled the app without taking the package setting into 7109 // account. 7110 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7111 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7112 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7113 " for package: " + pkg.packageName); 7114 } 7115 } 7116 7117 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7118 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7119 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7120 7121 // Copy the derived override back to the parsed package, so that we can 7122 // update the package settings accordingly. 7123 pkg.cpuAbiOverride = cpuAbiOverride; 7124 7125 if (DEBUG_ABI_SELECTION) { 7126 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7127 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7128 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7129 } 7130 7131 // Push the derived path down into PackageSettings so we know what to 7132 // clean up at uninstall time. 7133 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7134 7135 if (DEBUG_ABI_SELECTION) { 7136 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7137 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7138 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7139 } 7140 7141 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7142 // We don't do this here during boot because we can do it all 7143 // at once after scanning all existing packages. 7144 // 7145 // We also do this *before* we perform dexopt on this package, so that 7146 // we can avoid redundant dexopts, and also to make sure we've got the 7147 // code and package path correct. 7148 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7149 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7150 } 7151 7152 if ((scanFlags & SCAN_NO_DEX) == 0) { 7153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7154 7155 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7156 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7157 7158 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7159 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7160 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7161 } 7162 } 7163 if (mFactoryTest && pkg.requestedPermissions.contains( 7164 android.Manifest.permission.FACTORY_TEST)) { 7165 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7166 } 7167 7168 ArrayList<PackageParser.Package> clientLibPkgs = null; 7169 7170 // writer 7171 synchronized (mPackages) { 7172 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7173 // Only system apps can add new shared libraries. 7174 if (pkg.libraryNames != null) { 7175 for (int i=0; i<pkg.libraryNames.size(); i++) { 7176 String name = pkg.libraryNames.get(i); 7177 boolean allowed = false; 7178 if (pkg.isUpdatedSystemApp()) { 7179 // New library entries can only be added through the 7180 // system image. This is important to get rid of a lot 7181 // of nasty edge cases: for example if we allowed a non- 7182 // system update of the app to add a library, then uninstalling 7183 // the update would make the library go away, and assumptions 7184 // we made such as through app install filtering would now 7185 // have allowed apps on the device which aren't compatible 7186 // with it. Better to just have the restriction here, be 7187 // conservative, and create many fewer cases that can negatively 7188 // impact the user experience. 7189 final PackageSetting sysPs = mSettings 7190 .getDisabledSystemPkgLPr(pkg.packageName); 7191 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7192 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7193 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7194 allowed = true; 7195 allowed = true; 7196 break; 7197 } 7198 } 7199 } 7200 } else { 7201 allowed = true; 7202 } 7203 if (allowed) { 7204 if (!mSharedLibraries.containsKey(name)) { 7205 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7206 } else if (!name.equals(pkg.packageName)) { 7207 Slog.w(TAG, "Package " + pkg.packageName + " library " 7208 + name + " already exists; skipping"); 7209 } 7210 } else { 7211 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7212 + name + " that is not declared on system image; skipping"); 7213 } 7214 } 7215 if ((scanFlags&SCAN_BOOTING) == 0) { 7216 // If we are not booting, we need to update any applications 7217 // that are clients of our shared library. If we are booting, 7218 // this will all be done once the scan is complete. 7219 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7220 } 7221 } 7222 } 7223 } 7224 7225 // We also need to dexopt any apps that are dependent on this library. Note that 7226 // if these fail, we should abort the install since installing the library will 7227 // result in some apps being broken. 7228 if (clientLibPkgs != null) { 7229 if ((scanFlags & SCAN_NO_DEX) == 0) { 7230 for (int i = 0; i < clientLibPkgs.size(); i++) { 7231 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7232 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7233 null /* instruction sets */, forceDex, 7234 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7235 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7236 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7237 "scanPackageLI failed to dexopt clientLibPkgs"); 7238 } 7239 } 7240 } 7241 } 7242 7243 // Request the ActivityManager to kill the process(only for existing packages) 7244 // so that we do not end up in a confused state while the user is still using the older 7245 // version of the application while the new one gets installed. 7246 if ((scanFlags & SCAN_REPLACING) != 0) { 7247 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7248 7249 killApplication(pkg.applicationInfo.packageName, 7250 pkg.applicationInfo.uid, "replace pkg"); 7251 7252 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7253 } 7254 7255 // Also need to kill any apps that are dependent on the library. 7256 if (clientLibPkgs != null) { 7257 for (int i=0; i<clientLibPkgs.size(); i++) { 7258 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7259 killApplication(clientPkg.applicationInfo.packageName, 7260 clientPkg.applicationInfo.uid, "update lib"); 7261 } 7262 } 7263 7264 // Make sure we're not adding any bogus keyset info 7265 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7266 ksms.assertScannedPackageValid(pkg); 7267 7268 // writer 7269 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7270 7271 boolean createIdmapFailed = false; 7272 synchronized (mPackages) { 7273 // We don't expect installation to fail beyond this point 7274 7275 // Add the new setting to mSettings 7276 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7277 // Add the new setting to mPackages 7278 mPackages.put(pkg.applicationInfo.packageName, pkg); 7279 // Make sure we don't accidentally delete its data. 7280 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7281 while (iter.hasNext()) { 7282 PackageCleanItem item = iter.next(); 7283 if (pkgName.equals(item.packageName)) { 7284 iter.remove(); 7285 } 7286 } 7287 7288 // Take care of first install / last update times. 7289 if (currentTime != 0) { 7290 if (pkgSetting.firstInstallTime == 0) { 7291 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7292 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7293 pkgSetting.lastUpdateTime = currentTime; 7294 } 7295 } else if (pkgSetting.firstInstallTime == 0) { 7296 // We need *something*. Take time time stamp of the file. 7297 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7298 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7299 if (scanFileTime != pkgSetting.timeStamp) { 7300 // A package on the system image has changed; consider this 7301 // to be an update. 7302 pkgSetting.lastUpdateTime = scanFileTime; 7303 } 7304 } 7305 7306 // Add the package's KeySets to the global KeySetManagerService 7307 ksms.addScannedPackageLPw(pkg); 7308 7309 int N = pkg.providers.size(); 7310 StringBuilder r = null; 7311 int i; 7312 for (i=0; i<N; i++) { 7313 PackageParser.Provider p = pkg.providers.get(i); 7314 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7315 p.info.processName, pkg.applicationInfo.uid); 7316 mProviders.addProvider(p); 7317 p.syncable = p.info.isSyncable; 7318 if (p.info.authority != null) { 7319 String names[] = p.info.authority.split(";"); 7320 p.info.authority = null; 7321 for (int j = 0; j < names.length; j++) { 7322 if (j == 1 && p.syncable) { 7323 // We only want the first authority for a provider to possibly be 7324 // syncable, so if we already added this provider using a different 7325 // authority clear the syncable flag. We copy the provider before 7326 // changing it because the mProviders object contains a reference 7327 // to a provider that we don't want to change. 7328 // Only do this for the second authority since the resulting provider 7329 // object can be the same for all future authorities for this provider. 7330 p = new PackageParser.Provider(p); 7331 p.syncable = false; 7332 } 7333 if (!mProvidersByAuthority.containsKey(names[j])) { 7334 mProvidersByAuthority.put(names[j], p); 7335 if (p.info.authority == null) { 7336 p.info.authority = names[j]; 7337 } else { 7338 p.info.authority = p.info.authority + ";" + names[j]; 7339 } 7340 if (DEBUG_PACKAGE_SCANNING) { 7341 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7342 Log.d(TAG, "Registered content provider: " + names[j] 7343 + ", className = " + p.info.name + ", isSyncable = " 7344 + p.info.isSyncable); 7345 } 7346 } else { 7347 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7348 Slog.w(TAG, "Skipping provider name " + names[j] + 7349 " (in package " + pkg.applicationInfo.packageName + 7350 "): name already used by " 7351 + ((other != null && other.getComponentName() != null) 7352 ? other.getComponentName().getPackageName() : "?")); 7353 } 7354 } 7355 } 7356 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7357 if (r == null) { 7358 r = new StringBuilder(256); 7359 } else { 7360 r.append(' '); 7361 } 7362 r.append(p.info.name); 7363 } 7364 } 7365 if (r != null) { 7366 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7367 } 7368 7369 N = pkg.services.size(); 7370 r = null; 7371 for (i=0; i<N; i++) { 7372 PackageParser.Service s = pkg.services.get(i); 7373 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7374 s.info.processName, pkg.applicationInfo.uid); 7375 mServices.addService(s); 7376 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7377 if (r == null) { 7378 r = new StringBuilder(256); 7379 } else { 7380 r.append(' '); 7381 } 7382 r.append(s.info.name); 7383 } 7384 } 7385 if (r != null) { 7386 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7387 } 7388 7389 N = pkg.receivers.size(); 7390 r = null; 7391 for (i=0; i<N; i++) { 7392 PackageParser.Activity a = pkg.receivers.get(i); 7393 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7394 a.info.processName, pkg.applicationInfo.uid); 7395 mReceivers.addActivity(a, "receiver"); 7396 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7397 if (r == null) { 7398 r = new StringBuilder(256); 7399 } else { 7400 r.append(' '); 7401 } 7402 r.append(a.info.name); 7403 } 7404 } 7405 if (r != null) { 7406 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7407 } 7408 7409 N = pkg.activities.size(); 7410 r = null; 7411 for (i=0; i<N; i++) { 7412 PackageParser.Activity a = pkg.activities.get(i); 7413 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7414 a.info.processName, pkg.applicationInfo.uid); 7415 mActivities.addActivity(a, "activity"); 7416 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7417 if (r == null) { 7418 r = new StringBuilder(256); 7419 } else { 7420 r.append(' '); 7421 } 7422 r.append(a.info.name); 7423 } 7424 } 7425 if (r != null) { 7426 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7427 } 7428 7429 N = pkg.permissionGroups.size(); 7430 r = null; 7431 for (i=0; i<N; i++) { 7432 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7433 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7434 if (cur == null) { 7435 mPermissionGroups.put(pg.info.name, pg); 7436 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7437 if (r == null) { 7438 r = new StringBuilder(256); 7439 } else { 7440 r.append(' '); 7441 } 7442 r.append(pg.info.name); 7443 } 7444 } else { 7445 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7446 + pg.info.packageName + " ignored: original from " 7447 + cur.info.packageName); 7448 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7449 if (r == null) { 7450 r = new StringBuilder(256); 7451 } else { 7452 r.append(' '); 7453 } 7454 r.append("DUP:"); 7455 r.append(pg.info.name); 7456 } 7457 } 7458 } 7459 if (r != null) { 7460 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7461 } 7462 7463 N = pkg.permissions.size(); 7464 r = null; 7465 for (i=0; i<N; i++) { 7466 PackageParser.Permission p = pkg.permissions.get(i); 7467 7468 // Assume by default that we did not install this permission into the system. 7469 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7470 7471 // Now that permission groups have a special meaning, we ignore permission 7472 // groups for legacy apps to prevent unexpected behavior. In particular, 7473 // permissions for one app being granted to someone just becuase they happen 7474 // to be in a group defined by another app (before this had no implications). 7475 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7476 p.group = mPermissionGroups.get(p.info.group); 7477 // Warn for a permission in an unknown group. 7478 if (p.info.group != null && p.group == null) { 7479 Slog.w(TAG, "Permission " + p.info.name + " from package " 7480 + p.info.packageName + " in an unknown group " + p.info.group); 7481 } 7482 } 7483 7484 ArrayMap<String, BasePermission> permissionMap = 7485 p.tree ? mSettings.mPermissionTrees 7486 : mSettings.mPermissions; 7487 BasePermission bp = permissionMap.get(p.info.name); 7488 7489 // Allow system apps to redefine non-system permissions 7490 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7491 final boolean currentOwnerIsSystem = (bp.perm != null 7492 && isSystemApp(bp.perm.owner)); 7493 if (isSystemApp(p.owner)) { 7494 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7495 // It's a built-in permission and no owner, take ownership now 7496 bp.packageSetting = pkgSetting; 7497 bp.perm = p; 7498 bp.uid = pkg.applicationInfo.uid; 7499 bp.sourcePackage = p.info.packageName; 7500 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7501 } else if (!currentOwnerIsSystem) { 7502 String msg = "New decl " + p.owner + " of permission " 7503 + p.info.name + " is system; overriding " + bp.sourcePackage; 7504 reportSettingsProblem(Log.WARN, msg); 7505 bp = null; 7506 } 7507 } 7508 } 7509 7510 if (bp == null) { 7511 bp = new BasePermission(p.info.name, p.info.packageName, 7512 BasePermission.TYPE_NORMAL); 7513 permissionMap.put(p.info.name, bp); 7514 } 7515 7516 if (bp.perm == null) { 7517 if (bp.sourcePackage == null 7518 || bp.sourcePackage.equals(p.info.packageName)) { 7519 BasePermission tree = findPermissionTreeLP(p.info.name); 7520 if (tree == null 7521 || tree.sourcePackage.equals(p.info.packageName)) { 7522 bp.packageSetting = pkgSetting; 7523 bp.perm = p; 7524 bp.uid = pkg.applicationInfo.uid; 7525 bp.sourcePackage = p.info.packageName; 7526 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7527 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7528 if (r == null) { 7529 r = new StringBuilder(256); 7530 } else { 7531 r.append(' '); 7532 } 7533 r.append(p.info.name); 7534 } 7535 } else { 7536 Slog.w(TAG, "Permission " + p.info.name + " from package " 7537 + p.info.packageName + " ignored: base tree " 7538 + tree.name + " is from package " 7539 + tree.sourcePackage); 7540 } 7541 } else { 7542 Slog.w(TAG, "Permission " + p.info.name + " from package " 7543 + p.info.packageName + " ignored: original from " 7544 + bp.sourcePackage); 7545 } 7546 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7547 if (r == null) { 7548 r = new StringBuilder(256); 7549 } else { 7550 r.append(' '); 7551 } 7552 r.append("DUP:"); 7553 r.append(p.info.name); 7554 } 7555 if (bp.perm == p) { 7556 bp.protectionLevel = p.info.protectionLevel; 7557 } 7558 } 7559 7560 if (r != null) { 7561 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7562 } 7563 7564 N = pkg.instrumentation.size(); 7565 r = null; 7566 for (i=0; i<N; i++) { 7567 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7568 a.info.packageName = pkg.applicationInfo.packageName; 7569 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7570 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7571 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7572 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7573 a.info.dataDir = pkg.applicationInfo.dataDir; 7574 7575 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7576 // need other information about the application, like the ABI and what not ? 7577 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7578 mInstrumentation.put(a.getComponentName(), a); 7579 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7580 if (r == null) { 7581 r = new StringBuilder(256); 7582 } else { 7583 r.append(' '); 7584 } 7585 r.append(a.info.name); 7586 } 7587 } 7588 if (r != null) { 7589 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7590 } 7591 7592 if (pkg.protectedBroadcasts != null) { 7593 N = pkg.protectedBroadcasts.size(); 7594 for (i=0; i<N; i++) { 7595 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7596 } 7597 } 7598 7599 pkgSetting.setTimeStamp(scanFileTime); 7600 7601 // Create idmap files for pairs of (packages, overlay packages). 7602 // Note: "android", ie framework-res.apk, is handled by native layers. 7603 if (pkg.mOverlayTarget != null) { 7604 // This is an overlay package. 7605 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7606 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7607 mOverlays.put(pkg.mOverlayTarget, 7608 new ArrayMap<String, PackageParser.Package>()); 7609 } 7610 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7611 map.put(pkg.packageName, pkg); 7612 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7613 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7614 createIdmapFailed = true; 7615 } 7616 } 7617 } else if (mOverlays.containsKey(pkg.packageName) && 7618 !pkg.packageName.equals("android")) { 7619 // This is a regular package, with one or more known overlay packages. 7620 createIdmapsForPackageLI(pkg); 7621 } 7622 } 7623 7624 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7625 7626 if (createIdmapFailed) { 7627 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7628 "scanPackageLI failed to createIdmap"); 7629 } 7630 return pkg; 7631 } 7632 7633 /** 7634 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7635 * is derived purely on the basis of the contents of {@code scanFile} and 7636 * {@code cpuAbiOverride}. 7637 * 7638 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7639 */ 7640 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7641 String cpuAbiOverride, boolean extractLibs) 7642 throws PackageManagerException { 7643 // TODO: We can probably be smarter about this stuff. For installed apps, 7644 // we can calculate this information at install time once and for all. For 7645 // system apps, we can probably assume that this information doesn't change 7646 // after the first boot scan. As things stand, we do lots of unnecessary work. 7647 7648 // Give ourselves some initial paths; we'll come back for another 7649 // pass once we've determined ABI below. 7650 setNativeLibraryPaths(pkg); 7651 7652 // We would never need to extract libs for forward-locked and external packages, 7653 // since the container service will do it for us. We shouldn't attempt to 7654 // extract libs from system app when it was not updated. 7655 if (pkg.isForwardLocked() || isExternal(pkg) || 7656 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7657 extractLibs = false; 7658 } 7659 7660 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7661 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7662 7663 NativeLibraryHelper.Handle handle = null; 7664 try { 7665 handle = NativeLibraryHelper.Handle.create(pkg); 7666 // TODO(multiArch): This can be null for apps that didn't go through the 7667 // usual installation process. We can calculate it again, like we 7668 // do during install time. 7669 // 7670 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7671 // unnecessary. 7672 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7673 7674 // Null out the abis so that they can be recalculated. 7675 pkg.applicationInfo.primaryCpuAbi = null; 7676 pkg.applicationInfo.secondaryCpuAbi = null; 7677 if (isMultiArch(pkg.applicationInfo)) { 7678 // Warn if we've set an abiOverride for multi-lib packages.. 7679 // By definition, we need to copy both 32 and 64 bit libraries for 7680 // such packages. 7681 if (pkg.cpuAbiOverride != null 7682 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7683 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7684 } 7685 7686 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7687 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7688 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7689 if (extractLibs) { 7690 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7691 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7692 useIsaSpecificSubdirs); 7693 } else { 7694 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7695 } 7696 } 7697 7698 maybeThrowExceptionForMultiArchCopy( 7699 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7700 7701 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7702 if (extractLibs) { 7703 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7704 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7705 useIsaSpecificSubdirs); 7706 } else { 7707 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7708 } 7709 } 7710 7711 maybeThrowExceptionForMultiArchCopy( 7712 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7713 7714 if (abi64 >= 0) { 7715 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7716 } 7717 7718 if (abi32 >= 0) { 7719 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7720 if (abi64 >= 0) { 7721 pkg.applicationInfo.secondaryCpuAbi = abi; 7722 } else { 7723 pkg.applicationInfo.primaryCpuAbi = abi; 7724 } 7725 } 7726 } else { 7727 String[] abiList = (cpuAbiOverride != null) ? 7728 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7729 7730 // Enable gross and lame hacks for apps that are built with old 7731 // SDK tools. We must scan their APKs for renderscript bitcode and 7732 // not launch them if it's present. Don't bother checking on devices 7733 // that don't have 64 bit support. 7734 boolean needsRenderScriptOverride = false; 7735 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7736 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7737 abiList = Build.SUPPORTED_32_BIT_ABIS; 7738 needsRenderScriptOverride = true; 7739 } 7740 7741 final int copyRet; 7742 if (extractLibs) { 7743 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7744 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7745 } else { 7746 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7747 } 7748 7749 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7750 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7751 "Error unpackaging native libs for app, errorCode=" + copyRet); 7752 } 7753 7754 if (copyRet >= 0) { 7755 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7756 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7757 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7758 } else if (needsRenderScriptOverride) { 7759 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7760 } 7761 } 7762 } catch (IOException ioe) { 7763 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7764 } finally { 7765 IoUtils.closeQuietly(handle); 7766 } 7767 7768 // Now that we've calculated the ABIs and determined if it's an internal app, 7769 // we will go ahead and populate the nativeLibraryPath. 7770 setNativeLibraryPaths(pkg); 7771 } 7772 7773 /** 7774 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7775 * i.e, so that all packages can be run inside a single process if required. 7776 * 7777 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7778 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7779 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7780 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7781 * updating a package that belongs to a shared user. 7782 * 7783 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7784 * adds unnecessary complexity. 7785 */ 7786 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7787 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7788 String requiredInstructionSet = null; 7789 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7790 requiredInstructionSet = VMRuntime.getInstructionSet( 7791 scannedPackage.applicationInfo.primaryCpuAbi); 7792 } 7793 7794 PackageSetting requirer = null; 7795 for (PackageSetting ps : packagesForUser) { 7796 // If packagesForUser contains scannedPackage, we skip it. This will happen 7797 // when scannedPackage is an update of an existing package. Without this check, 7798 // we will never be able to change the ABI of any package belonging to a shared 7799 // user, even if it's compatible with other packages. 7800 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7801 if (ps.primaryCpuAbiString == null) { 7802 continue; 7803 } 7804 7805 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7806 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7807 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7808 // this but there's not much we can do. 7809 String errorMessage = "Instruction set mismatch, " 7810 + ((requirer == null) ? "[caller]" : requirer) 7811 + " requires " + requiredInstructionSet + " whereas " + ps 7812 + " requires " + instructionSet; 7813 Slog.w(TAG, errorMessage); 7814 } 7815 7816 if (requiredInstructionSet == null) { 7817 requiredInstructionSet = instructionSet; 7818 requirer = ps; 7819 } 7820 } 7821 } 7822 7823 if (requiredInstructionSet != null) { 7824 String adjustedAbi; 7825 if (requirer != null) { 7826 // requirer != null implies that either scannedPackage was null or that scannedPackage 7827 // did not require an ABI, in which case we have to adjust scannedPackage to match 7828 // the ABI of the set (which is the same as requirer's ABI) 7829 adjustedAbi = requirer.primaryCpuAbiString; 7830 if (scannedPackage != null) { 7831 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7832 } 7833 } else { 7834 // requirer == null implies that we're updating all ABIs in the set to 7835 // match scannedPackage. 7836 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7837 } 7838 7839 for (PackageSetting ps : packagesForUser) { 7840 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7841 if (ps.primaryCpuAbiString != null) { 7842 continue; 7843 } 7844 7845 ps.primaryCpuAbiString = adjustedAbi; 7846 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7847 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7848 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7849 7850 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7851 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7852 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7853 ps.primaryCpuAbiString = null; 7854 ps.pkg.applicationInfo.primaryCpuAbi = null; 7855 return; 7856 } else { 7857 mInstaller.rmdex(ps.codePathString, 7858 getDexCodeInstructionSet(getPreferredInstructionSet())); 7859 } 7860 } 7861 } 7862 } 7863 } 7864 } 7865 7866 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7867 synchronized (mPackages) { 7868 mResolverReplaced = true; 7869 // Set up information for custom user intent resolution activity. 7870 mResolveActivity.applicationInfo = pkg.applicationInfo; 7871 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7872 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7873 mResolveActivity.processName = pkg.applicationInfo.packageName; 7874 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7875 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7876 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7877 mResolveActivity.theme = 0; 7878 mResolveActivity.exported = true; 7879 mResolveActivity.enabled = true; 7880 mResolveInfo.activityInfo = mResolveActivity; 7881 mResolveInfo.priority = 0; 7882 mResolveInfo.preferredOrder = 0; 7883 mResolveInfo.match = 0; 7884 mResolveComponentName = mCustomResolverComponentName; 7885 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7886 mResolveComponentName); 7887 } 7888 } 7889 7890 private static String calculateBundledApkRoot(final String codePathString) { 7891 final File codePath = new File(codePathString); 7892 final File codeRoot; 7893 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7894 codeRoot = Environment.getRootDirectory(); 7895 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7896 codeRoot = Environment.getOemDirectory(); 7897 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7898 codeRoot = Environment.getVendorDirectory(); 7899 } else { 7900 // Unrecognized code path; take its top real segment as the apk root: 7901 // e.g. /something/app/blah.apk => /something 7902 try { 7903 File f = codePath.getCanonicalFile(); 7904 File parent = f.getParentFile(); // non-null because codePath is a file 7905 File tmp; 7906 while ((tmp = parent.getParentFile()) != null) { 7907 f = parent; 7908 parent = tmp; 7909 } 7910 codeRoot = f; 7911 Slog.w(TAG, "Unrecognized code path " 7912 + codePath + " - using " + codeRoot); 7913 } catch (IOException e) { 7914 // Can't canonicalize the code path -- shenanigans? 7915 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7916 return Environment.getRootDirectory().getPath(); 7917 } 7918 } 7919 return codeRoot.getPath(); 7920 } 7921 7922 /** 7923 * Derive and set the location of native libraries for the given package, 7924 * which varies depending on where and how the package was installed. 7925 */ 7926 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7927 final ApplicationInfo info = pkg.applicationInfo; 7928 final String codePath = pkg.codePath; 7929 final File codeFile = new File(codePath); 7930 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7931 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7932 7933 info.nativeLibraryRootDir = null; 7934 info.nativeLibraryRootRequiresIsa = false; 7935 info.nativeLibraryDir = null; 7936 info.secondaryNativeLibraryDir = null; 7937 7938 if (isApkFile(codeFile)) { 7939 // Monolithic install 7940 if (bundledApp) { 7941 // If "/system/lib64/apkname" exists, assume that is the per-package 7942 // native library directory to use; otherwise use "/system/lib/apkname". 7943 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7944 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7945 getPrimaryInstructionSet(info)); 7946 7947 // This is a bundled system app so choose the path based on the ABI. 7948 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7949 // is just the default path. 7950 final String apkName = deriveCodePathName(codePath); 7951 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7952 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7953 apkName).getAbsolutePath(); 7954 7955 if (info.secondaryCpuAbi != null) { 7956 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7957 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7958 secondaryLibDir, apkName).getAbsolutePath(); 7959 } 7960 } else if (asecApp) { 7961 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7962 .getAbsolutePath(); 7963 } else { 7964 final String apkName = deriveCodePathName(codePath); 7965 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7966 .getAbsolutePath(); 7967 } 7968 7969 info.nativeLibraryRootRequiresIsa = false; 7970 info.nativeLibraryDir = info.nativeLibraryRootDir; 7971 } else { 7972 // Cluster install 7973 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7974 info.nativeLibraryRootRequiresIsa = true; 7975 7976 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7977 getPrimaryInstructionSet(info)).getAbsolutePath(); 7978 7979 if (info.secondaryCpuAbi != null) { 7980 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7981 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7982 } 7983 } 7984 } 7985 7986 /** 7987 * Calculate the abis and roots for a bundled app. These can uniquely 7988 * be determined from the contents of the system partition, i.e whether 7989 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7990 * of this information, and instead assume that the system was built 7991 * sensibly. 7992 */ 7993 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7994 PackageSetting pkgSetting) { 7995 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7996 7997 // If "/system/lib64/apkname" exists, assume that is the per-package 7998 // native library directory to use; otherwise use "/system/lib/apkname". 7999 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8000 setBundledAppAbi(pkg, apkRoot, apkName); 8001 // pkgSetting might be null during rescan following uninstall of updates 8002 // to a bundled app, so accommodate that possibility. The settings in 8003 // that case will be established later from the parsed package. 8004 // 8005 // If the settings aren't null, sync them up with what we've just derived. 8006 // note that apkRoot isn't stored in the package settings. 8007 if (pkgSetting != null) { 8008 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8009 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8010 } 8011 } 8012 8013 /** 8014 * Deduces the ABI of a bundled app and sets the relevant fields on the 8015 * parsed pkg object. 8016 * 8017 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8018 * under which system libraries are installed. 8019 * @param apkName the name of the installed package. 8020 */ 8021 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8022 final File codeFile = new File(pkg.codePath); 8023 8024 final boolean has64BitLibs; 8025 final boolean has32BitLibs; 8026 if (isApkFile(codeFile)) { 8027 // Monolithic install 8028 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8029 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8030 } else { 8031 // Cluster install 8032 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8033 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8034 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8035 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8036 has64BitLibs = (new File(rootDir, isa)).exists(); 8037 } else { 8038 has64BitLibs = false; 8039 } 8040 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8041 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8042 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8043 has32BitLibs = (new File(rootDir, isa)).exists(); 8044 } else { 8045 has32BitLibs = false; 8046 } 8047 } 8048 8049 if (has64BitLibs && !has32BitLibs) { 8050 // The package has 64 bit libs, but not 32 bit libs. Its primary 8051 // ABI should be 64 bit. We can safely assume here that the bundled 8052 // native libraries correspond to the most preferred ABI in the list. 8053 8054 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8055 pkg.applicationInfo.secondaryCpuAbi = null; 8056 } else if (has32BitLibs && !has64BitLibs) { 8057 // The package has 32 bit libs but not 64 bit libs. Its primary 8058 // ABI should be 32 bit. 8059 8060 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8061 pkg.applicationInfo.secondaryCpuAbi = null; 8062 } else if (has32BitLibs && has64BitLibs) { 8063 // The application has both 64 and 32 bit bundled libraries. We check 8064 // here that the app declares multiArch support, and warn if it doesn't. 8065 // 8066 // We will be lenient here and record both ABIs. The primary will be the 8067 // ABI that's higher on the list, i.e, a device that's configured to prefer 8068 // 64 bit apps will see a 64 bit primary ABI, 8069 8070 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8071 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8072 } 8073 8074 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8075 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8076 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8077 } else { 8078 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8079 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8080 } 8081 } else { 8082 pkg.applicationInfo.primaryCpuAbi = null; 8083 pkg.applicationInfo.secondaryCpuAbi = null; 8084 } 8085 } 8086 8087 private void killApplication(String pkgName, int appId, String reason) { 8088 // Request the ActivityManager to kill the process(only for existing packages) 8089 // so that we do not end up in a confused state while the user is still using the older 8090 // version of the application while the new one gets installed. 8091 IActivityManager am = ActivityManagerNative.getDefault(); 8092 if (am != null) { 8093 try { 8094 am.killApplicationWithAppId(pkgName, appId, reason); 8095 } catch (RemoteException e) { 8096 } 8097 } 8098 } 8099 8100 void removePackageLI(PackageSetting ps, boolean chatty) { 8101 if (DEBUG_INSTALL) { 8102 if (chatty) 8103 Log.d(TAG, "Removing package " + ps.name); 8104 } 8105 8106 // writer 8107 synchronized (mPackages) { 8108 mPackages.remove(ps.name); 8109 final PackageParser.Package pkg = ps.pkg; 8110 if (pkg != null) { 8111 cleanPackageDataStructuresLILPw(pkg, chatty); 8112 } 8113 } 8114 } 8115 8116 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8117 if (DEBUG_INSTALL) { 8118 if (chatty) 8119 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8120 } 8121 8122 // writer 8123 synchronized (mPackages) { 8124 mPackages.remove(pkg.applicationInfo.packageName); 8125 cleanPackageDataStructuresLILPw(pkg, chatty); 8126 } 8127 } 8128 8129 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8130 int N = pkg.providers.size(); 8131 StringBuilder r = null; 8132 int i; 8133 for (i=0; i<N; i++) { 8134 PackageParser.Provider p = pkg.providers.get(i); 8135 mProviders.removeProvider(p); 8136 if (p.info.authority == null) { 8137 8138 /* There was another ContentProvider with this authority when 8139 * this app was installed so this authority is null, 8140 * Ignore it as we don't have to unregister the provider. 8141 */ 8142 continue; 8143 } 8144 String names[] = p.info.authority.split(";"); 8145 for (int j = 0; j < names.length; j++) { 8146 if (mProvidersByAuthority.get(names[j]) == p) { 8147 mProvidersByAuthority.remove(names[j]); 8148 if (DEBUG_REMOVE) { 8149 if (chatty) 8150 Log.d(TAG, "Unregistered content provider: " + names[j] 8151 + ", className = " + p.info.name + ", isSyncable = " 8152 + p.info.isSyncable); 8153 } 8154 } 8155 } 8156 if (DEBUG_REMOVE && chatty) { 8157 if (r == null) { 8158 r = new StringBuilder(256); 8159 } else { 8160 r.append(' '); 8161 } 8162 r.append(p.info.name); 8163 } 8164 } 8165 if (r != null) { 8166 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8167 } 8168 8169 N = pkg.services.size(); 8170 r = null; 8171 for (i=0; i<N; i++) { 8172 PackageParser.Service s = pkg.services.get(i); 8173 mServices.removeService(s); 8174 if (chatty) { 8175 if (r == null) { 8176 r = new StringBuilder(256); 8177 } else { 8178 r.append(' '); 8179 } 8180 r.append(s.info.name); 8181 } 8182 } 8183 if (r != null) { 8184 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8185 } 8186 8187 N = pkg.receivers.size(); 8188 r = null; 8189 for (i=0; i<N; i++) { 8190 PackageParser.Activity a = pkg.receivers.get(i); 8191 mReceivers.removeActivity(a, "receiver"); 8192 if (DEBUG_REMOVE && chatty) { 8193 if (r == null) { 8194 r = new StringBuilder(256); 8195 } else { 8196 r.append(' '); 8197 } 8198 r.append(a.info.name); 8199 } 8200 } 8201 if (r != null) { 8202 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8203 } 8204 8205 N = pkg.activities.size(); 8206 r = null; 8207 for (i=0; i<N; i++) { 8208 PackageParser.Activity a = pkg.activities.get(i); 8209 mActivities.removeActivity(a, "activity"); 8210 if (DEBUG_REMOVE && chatty) { 8211 if (r == null) { 8212 r = new StringBuilder(256); 8213 } else { 8214 r.append(' '); 8215 } 8216 r.append(a.info.name); 8217 } 8218 } 8219 if (r != null) { 8220 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8221 } 8222 8223 N = pkg.permissions.size(); 8224 r = null; 8225 for (i=0; i<N; i++) { 8226 PackageParser.Permission p = pkg.permissions.get(i); 8227 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8228 if (bp == null) { 8229 bp = mSettings.mPermissionTrees.get(p.info.name); 8230 } 8231 if (bp != null && bp.perm == p) { 8232 bp.perm = null; 8233 if (DEBUG_REMOVE && chatty) { 8234 if (r == null) { 8235 r = new StringBuilder(256); 8236 } else { 8237 r.append(' '); 8238 } 8239 r.append(p.info.name); 8240 } 8241 } 8242 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8243 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8244 if (appOpPerms != null) { 8245 appOpPerms.remove(pkg.packageName); 8246 } 8247 } 8248 } 8249 if (r != null) { 8250 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8251 } 8252 8253 N = pkg.requestedPermissions.size(); 8254 r = null; 8255 for (i=0; i<N; i++) { 8256 String perm = pkg.requestedPermissions.get(i); 8257 BasePermission bp = mSettings.mPermissions.get(perm); 8258 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8259 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8260 if (appOpPerms != null) { 8261 appOpPerms.remove(pkg.packageName); 8262 if (appOpPerms.isEmpty()) { 8263 mAppOpPermissionPackages.remove(perm); 8264 } 8265 } 8266 } 8267 } 8268 if (r != null) { 8269 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8270 } 8271 8272 N = pkg.instrumentation.size(); 8273 r = null; 8274 for (i=0; i<N; i++) { 8275 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8276 mInstrumentation.remove(a.getComponentName()); 8277 if (DEBUG_REMOVE && chatty) { 8278 if (r == null) { 8279 r = new StringBuilder(256); 8280 } else { 8281 r.append(' '); 8282 } 8283 r.append(a.info.name); 8284 } 8285 } 8286 if (r != null) { 8287 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8288 } 8289 8290 r = null; 8291 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8292 // Only system apps can hold shared libraries. 8293 if (pkg.libraryNames != null) { 8294 for (i=0; i<pkg.libraryNames.size(); i++) { 8295 String name = pkg.libraryNames.get(i); 8296 SharedLibraryEntry cur = mSharedLibraries.get(name); 8297 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8298 mSharedLibraries.remove(name); 8299 if (DEBUG_REMOVE && chatty) { 8300 if (r == null) { 8301 r = new StringBuilder(256); 8302 } else { 8303 r.append(' '); 8304 } 8305 r.append(name); 8306 } 8307 } 8308 } 8309 } 8310 } 8311 if (r != null) { 8312 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8313 } 8314 } 8315 8316 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8317 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8318 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8319 return true; 8320 } 8321 } 8322 return false; 8323 } 8324 8325 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8326 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8327 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8328 8329 private void updatePermissionsLPw(String changingPkg, 8330 PackageParser.Package pkgInfo, int flags) { 8331 // Make sure there are no dangling permission trees. 8332 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8333 while (it.hasNext()) { 8334 final BasePermission bp = it.next(); 8335 if (bp.packageSetting == null) { 8336 // We may not yet have parsed the package, so just see if 8337 // we still know about its settings. 8338 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8339 } 8340 if (bp.packageSetting == null) { 8341 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8342 + " from package " + bp.sourcePackage); 8343 it.remove(); 8344 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8345 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8346 Slog.i(TAG, "Removing old permission tree: " + bp.name 8347 + " from package " + bp.sourcePackage); 8348 flags |= UPDATE_PERMISSIONS_ALL; 8349 it.remove(); 8350 } 8351 } 8352 } 8353 8354 // Make sure all dynamic permissions have been assigned to a package, 8355 // and make sure there are no dangling permissions. 8356 it = mSettings.mPermissions.values().iterator(); 8357 while (it.hasNext()) { 8358 final BasePermission bp = it.next(); 8359 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8360 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8361 + bp.name + " pkg=" + bp.sourcePackage 8362 + " info=" + bp.pendingInfo); 8363 if (bp.packageSetting == null && bp.pendingInfo != null) { 8364 final BasePermission tree = findPermissionTreeLP(bp.name); 8365 if (tree != null && tree.perm != null) { 8366 bp.packageSetting = tree.packageSetting; 8367 bp.perm = new PackageParser.Permission(tree.perm.owner, 8368 new PermissionInfo(bp.pendingInfo)); 8369 bp.perm.info.packageName = tree.perm.info.packageName; 8370 bp.perm.info.name = bp.name; 8371 bp.uid = tree.uid; 8372 } 8373 } 8374 } 8375 if (bp.packageSetting == null) { 8376 // We may not yet have parsed the package, so just see if 8377 // we still know about its settings. 8378 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8379 } 8380 if (bp.packageSetting == null) { 8381 Slog.w(TAG, "Removing dangling permission: " + bp.name 8382 + " from package " + bp.sourcePackage); 8383 it.remove(); 8384 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8385 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8386 Slog.i(TAG, "Removing old permission: " + bp.name 8387 + " from package " + bp.sourcePackage); 8388 flags |= UPDATE_PERMISSIONS_ALL; 8389 it.remove(); 8390 } 8391 } 8392 } 8393 8394 // Now update the permissions for all packages, in particular 8395 // replace the granted permissions of the system packages. 8396 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8397 for (PackageParser.Package pkg : mPackages.values()) { 8398 if (pkg != pkgInfo) { 8399 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8400 changingPkg); 8401 } 8402 } 8403 } 8404 8405 if (pkgInfo != null) { 8406 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8407 } 8408 } 8409 8410 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8411 String packageOfInterest) { 8412 // IMPORTANT: There are two types of permissions: install and runtime. 8413 // Install time permissions are granted when the app is installed to 8414 // all device users and users added in the future. Runtime permissions 8415 // are granted at runtime explicitly to specific users. Normal and signature 8416 // protected permissions are install time permissions. Dangerous permissions 8417 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8418 // otherwise they are runtime permissions. This function does not manage 8419 // runtime permissions except for the case an app targeting Lollipop MR1 8420 // being upgraded to target a newer SDK, in which case dangerous permissions 8421 // are transformed from install time to runtime ones. 8422 8423 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8424 if (ps == null) { 8425 return; 8426 } 8427 8428 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8429 8430 PermissionsState permissionsState = ps.getPermissionsState(); 8431 PermissionsState origPermissions = permissionsState; 8432 8433 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8434 8435 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8436 8437 boolean changedInstallPermission = false; 8438 8439 if (replace) { 8440 ps.installPermissionsFixed = false; 8441 if (!ps.isSharedUser()) { 8442 origPermissions = new PermissionsState(permissionsState); 8443 permissionsState.reset(); 8444 } 8445 } 8446 8447 permissionsState.setGlobalGids(mGlobalGids); 8448 8449 final int N = pkg.requestedPermissions.size(); 8450 for (int i=0; i<N; i++) { 8451 final String name = pkg.requestedPermissions.get(i); 8452 final BasePermission bp = mSettings.mPermissions.get(name); 8453 8454 if (DEBUG_INSTALL) { 8455 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8456 } 8457 8458 if (bp == null || bp.packageSetting == null) { 8459 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8460 Slog.w(TAG, "Unknown permission " + name 8461 + " in package " + pkg.packageName); 8462 } 8463 continue; 8464 } 8465 8466 final String perm = bp.name; 8467 boolean allowedSig = false; 8468 int grant = GRANT_DENIED; 8469 8470 // Keep track of app op permissions. 8471 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8472 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8473 if (pkgs == null) { 8474 pkgs = new ArraySet<>(); 8475 mAppOpPermissionPackages.put(bp.name, pkgs); 8476 } 8477 pkgs.add(pkg.packageName); 8478 } 8479 8480 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8481 switch (level) { 8482 case PermissionInfo.PROTECTION_NORMAL: { 8483 // For all apps normal permissions are install time ones. 8484 grant = GRANT_INSTALL; 8485 } break; 8486 8487 case PermissionInfo.PROTECTION_DANGEROUS: { 8488 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8489 // For legacy apps dangerous permissions are install time ones. 8490 grant = GRANT_INSTALL_LEGACY; 8491 } else if (origPermissions.hasInstallPermission(bp.name)) { 8492 // For legacy apps that became modern, install becomes runtime. 8493 grant = GRANT_UPGRADE; 8494 } else if (mPromoteSystemApps 8495 && isSystemApp(ps) 8496 && mExistingSystemPackages.contains(ps.name)) { 8497 // For legacy system apps, install becomes runtime. 8498 // We cannot check hasInstallPermission() for system apps since those 8499 // permissions were granted implicitly and not persisted pre-M. 8500 grant = GRANT_UPGRADE; 8501 } else { 8502 // For modern apps keep runtime permissions unchanged. 8503 grant = GRANT_RUNTIME; 8504 } 8505 } break; 8506 8507 case PermissionInfo.PROTECTION_SIGNATURE: { 8508 // For all apps signature permissions are install time ones. 8509 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8510 if (allowedSig) { 8511 grant = GRANT_INSTALL; 8512 } 8513 } break; 8514 } 8515 8516 if (DEBUG_INSTALL) { 8517 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8518 } 8519 8520 if (grant != GRANT_DENIED) { 8521 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8522 // If this is an existing, non-system package, then 8523 // we can't add any new permissions to it. 8524 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8525 // Except... if this is a permission that was added 8526 // to the platform (note: need to only do this when 8527 // updating the platform). 8528 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8529 grant = GRANT_DENIED; 8530 } 8531 } 8532 } 8533 8534 switch (grant) { 8535 case GRANT_INSTALL: { 8536 // Revoke this as runtime permission to handle the case of 8537 // a runtime permission being downgraded to an install one. 8538 for (int userId : UserManagerService.getInstance().getUserIds()) { 8539 if (origPermissions.getRuntimePermissionState( 8540 bp.name, userId) != null) { 8541 // Revoke the runtime permission and clear the flags. 8542 origPermissions.revokeRuntimePermission(bp, userId); 8543 origPermissions.updatePermissionFlags(bp, userId, 8544 PackageManager.MASK_PERMISSION_FLAGS, 0); 8545 // If we revoked a permission permission, we have to write. 8546 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8547 changedRuntimePermissionUserIds, userId); 8548 } 8549 } 8550 // Grant an install permission. 8551 if (permissionsState.grantInstallPermission(bp) != 8552 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8553 changedInstallPermission = true; 8554 } 8555 } break; 8556 8557 case GRANT_INSTALL_LEGACY: { 8558 // Grant an install permission. 8559 if (permissionsState.grantInstallPermission(bp) != 8560 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8561 changedInstallPermission = true; 8562 } 8563 } break; 8564 8565 case GRANT_RUNTIME: { 8566 // Grant previously granted runtime permissions. 8567 for (int userId : UserManagerService.getInstance().getUserIds()) { 8568 PermissionState permissionState = origPermissions 8569 .getRuntimePermissionState(bp.name, userId); 8570 final int flags = permissionState != null 8571 ? permissionState.getFlags() : 0; 8572 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8573 if (permissionsState.grantRuntimePermission(bp, userId) == 8574 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8575 // If we cannot put the permission as it was, we have to write. 8576 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8577 changedRuntimePermissionUserIds, userId); 8578 } 8579 } 8580 // Propagate the permission flags. 8581 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8582 } 8583 } break; 8584 8585 case GRANT_UPGRADE: { 8586 // Grant runtime permissions for a previously held install permission. 8587 PermissionState permissionState = origPermissions 8588 .getInstallPermissionState(bp.name); 8589 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8590 8591 if (origPermissions.revokeInstallPermission(bp) 8592 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8593 // We will be transferring the permission flags, so clear them. 8594 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8595 PackageManager.MASK_PERMISSION_FLAGS, 0); 8596 changedInstallPermission = true; 8597 } 8598 8599 // If the permission is not to be promoted to runtime we ignore it and 8600 // also its other flags as they are not applicable to install permissions. 8601 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8602 for (int userId : currentUserIds) { 8603 if (permissionsState.grantRuntimePermission(bp, userId) != 8604 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8605 // Transfer the permission flags. 8606 permissionsState.updatePermissionFlags(bp, userId, 8607 flags, flags); 8608 // If we granted the permission, we have to write. 8609 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8610 changedRuntimePermissionUserIds, userId); 8611 } 8612 } 8613 } 8614 } break; 8615 8616 default: { 8617 if (packageOfInterest == null 8618 || packageOfInterest.equals(pkg.packageName)) { 8619 Slog.w(TAG, "Not granting permission " + perm 8620 + " to package " + pkg.packageName 8621 + " because it was previously installed without"); 8622 } 8623 } break; 8624 } 8625 } else { 8626 if (permissionsState.revokeInstallPermission(bp) != 8627 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8628 // Also drop the permission flags. 8629 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8630 PackageManager.MASK_PERMISSION_FLAGS, 0); 8631 changedInstallPermission = true; 8632 Slog.i(TAG, "Un-granting permission " + perm 8633 + " from package " + pkg.packageName 8634 + " (protectionLevel=" + bp.protectionLevel 8635 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8636 + ")"); 8637 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8638 // Don't print warning for app op permissions, since it is fine for them 8639 // not to be granted, there is a UI for the user to decide. 8640 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8641 Slog.w(TAG, "Not granting permission " + perm 8642 + " to package " + pkg.packageName 8643 + " (protectionLevel=" + bp.protectionLevel 8644 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8645 + ")"); 8646 } 8647 } 8648 } 8649 } 8650 8651 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8652 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8653 // This is the first that we have heard about this package, so the 8654 // permissions we have now selected are fixed until explicitly 8655 // changed. 8656 ps.installPermissionsFixed = true; 8657 } 8658 8659 // Persist the runtime permissions state for users with changes. 8660 for (int userId : changedRuntimePermissionUserIds) { 8661 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8662 } 8663 8664 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8665 } 8666 8667 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8668 boolean allowed = false; 8669 final int NP = PackageParser.NEW_PERMISSIONS.length; 8670 for (int ip=0; ip<NP; ip++) { 8671 final PackageParser.NewPermissionInfo npi 8672 = PackageParser.NEW_PERMISSIONS[ip]; 8673 if (npi.name.equals(perm) 8674 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8675 allowed = true; 8676 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8677 + pkg.packageName); 8678 break; 8679 } 8680 } 8681 return allowed; 8682 } 8683 8684 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8685 BasePermission bp, PermissionsState origPermissions) { 8686 boolean allowed; 8687 allowed = (compareSignatures( 8688 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8689 == PackageManager.SIGNATURE_MATCH) 8690 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8691 == PackageManager.SIGNATURE_MATCH); 8692 if (!allowed && (bp.protectionLevel 8693 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8694 if (isSystemApp(pkg)) { 8695 // For updated system applications, a system permission 8696 // is granted only if it had been defined by the original application. 8697 if (pkg.isUpdatedSystemApp()) { 8698 final PackageSetting sysPs = mSettings 8699 .getDisabledSystemPkgLPr(pkg.packageName); 8700 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8701 // If the original was granted this permission, we take 8702 // that grant decision as read and propagate it to the 8703 // update. 8704 if (sysPs.isPrivileged()) { 8705 allowed = true; 8706 } 8707 } else { 8708 // The system apk may have been updated with an older 8709 // version of the one on the data partition, but which 8710 // granted a new system permission that it didn't have 8711 // before. In this case we do want to allow the app to 8712 // now get the new permission if the ancestral apk is 8713 // privileged to get it. 8714 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8715 for (int j=0; 8716 j<sysPs.pkg.requestedPermissions.size(); j++) { 8717 if (perm.equals( 8718 sysPs.pkg.requestedPermissions.get(j))) { 8719 allowed = true; 8720 break; 8721 } 8722 } 8723 } 8724 } 8725 } else { 8726 allowed = isPrivilegedApp(pkg); 8727 } 8728 } 8729 } 8730 if (!allowed) { 8731 if (!allowed && (bp.protectionLevel 8732 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8733 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8734 // If this was a previously normal/dangerous permission that got moved 8735 // to a system permission as part of the runtime permission redesign, then 8736 // we still want to blindly grant it to old apps. 8737 allowed = true; 8738 } 8739 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8740 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8741 // If this permission is to be granted to the system installer and 8742 // this app is an installer, then it gets the permission. 8743 allowed = true; 8744 } 8745 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8746 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8747 // If this permission is to be granted to the system verifier and 8748 // this app is a verifier, then it gets the permission. 8749 allowed = true; 8750 } 8751 if (!allowed && (bp.protectionLevel 8752 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8753 && isSystemApp(pkg)) { 8754 // Any pre-installed system app is allowed to get this permission. 8755 allowed = true; 8756 } 8757 if (!allowed && (bp.protectionLevel 8758 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8759 // For development permissions, a development permission 8760 // is granted only if it was already granted. 8761 allowed = origPermissions.hasInstallPermission(perm); 8762 } 8763 } 8764 return allowed; 8765 } 8766 8767 final class ActivityIntentResolver 8768 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8769 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8770 boolean defaultOnly, int userId) { 8771 if (!sUserManager.exists(userId)) return null; 8772 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8773 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8774 } 8775 8776 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8777 int userId) { 8778 if (!sUserManager.exists(userId)) return null; 8779 mFlags = flags; 8780 return super.queryIntent(intent, resolvedType, 8781 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8782 } 8783 8784 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8785 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8786 if (!sUserManager.exists(userId)) return null; 8787 if (packageActivities == null) { 8788 return null; 8789 } 8790 mFlags = flags; 8791 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8792 final int N = packageActivities.size(); 8793 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8794 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8795 8796 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8797 for (int i = 0; i < N; ++i) { 8798 intentFilters = packageActivities.get(i).intents; 8799 if (intentFilters != null && intentFilters.size() > 0) { 8800 PackageParser.ActivityIntentInfo[] array = 8801 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8802 intentFilters.toArray(array); 8803 listCut.add(array); 8804 } 8805 } 8806 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8807 } 8808 8809 public final void addActivity(PackageParser.Activity a, String type) { 8810 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8811 mActivities.put(a.getComponentName(), a); 8812 if (DEBUG_SHOW_INFO) 8813 Log.v( 8814 TAG, " " + type + " " + 8815 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8816 if (DEBUG_SHOW_INFO) 8817 Log.v(TAG, " Class=" + a.info.name); 8818 final int NI = a.intents.size(); 8819 for (int j=0; j<NI; j++) { 8820 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8821 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8822 intent.setPriority(0); 8823 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8824 + a.className + " with priority > 0, forcing to 0"); 8825 } 8826 if (DEBUG_SHOW_INFO) { 8827 Log.v(TAG, " IntentFilter:"); 8828 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8829 } 8830 if (!intent.debugCheck()) { 8831 Log.w(TAG, "==> For Activity " + a.info.name); 8832 } 8833 addFilter(intent); 8834 } 8835 } 8836 8837 public final void removeActivity(PackageParser.Activity a, String type) { 8838 mActivities.remove(a.getComponentName()); 8839 if (DEBUG_SHOW_INFO) { 8840 Log.v(TAG, " " + type + " " 8841 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8842 : a.info.name) + ":"); 8843 Log.v(TAG, " Class=" + a.info.name); 8844 } 8845 final int NI = a.intents.size(); 8846 for (int j=0; j<NI; j++) { 8847 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8848 if (DEBUG_SHOW_INFO) { 8849 Log.v(TAG, " IntentFilter:"); 8850 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8851 } 8852 removeFilter(intent); 8853 } 8854 } 8855 8856 @Override 8857 protected boolean allowFilterResult( 8858 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8859 ActivityInfo filterAi = filter.activity.info; 8860 for (int i=dest.size()-1; i>=0; i--) { 8861 ActivityInfo destAi = dest.get(i).activityInfo; 8862 if (destAi.name == filterAi.name 8863 && destAi.packageName == filterAi.packageName) { 8864 return false; 8865 } 8866 } 8867 return true; 8868 } 8869 8870 @Override 8871 protected ActivityIntentInfo[] newArray(int size) { 8872 return new ActivityIntentInfo[size]; 8873 } 8874 8875 @Override 8876 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8877 if (!sUserManager.exists(userId)) return true; 8878 PackageParser.Package p = filter.activity.owner; 8879 if (p != null) { 8880 PackageSetting ps = (PackageSetting)p.mExtras; 8881 if (ps != null) { 8882 // System apps are never considered stopped for purposes of 8883 // filtering, because there may be no way for the user to 8884 // actually re-launch them. 8885 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8886 && ps.getStopped(userId); 8887 } 8888 } 8889 return false; 8890 } 8891 8892 @Override 8893 protected boolean isPackageForFilter(String packageName, 8894 PackageParser.ActivityIntentInfo info) { 8895 return packageName.equals(info.activity.owner.packageName); 8896 } 8897 8898 @Override 8899 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8900 int match, int userId) { 8901 if (!sUserManager.exists(userId)) return null; 8902 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8903 return null; 8904 } 8905 final PackageParser.Activity activity = info.activity; 8906 if (mSafeMode && (activity.info.applicationInfo.flags 8907 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8908 return null; 8909 } 8910 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8911 if (ps == null) { 8912 return null; 8913 } 8914 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8915 ps.readUserState(userId), userId); 8916 if (ai == null) { 8917 return null; 8918 } 8919 final ResolveInfo res = new ResolveInfo(); 8920 res.activityInfo = ai; 8921 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8922 res.filter = info; 8923 } 8924 if (info != null) { 8925 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8926 } 8927 res.priority = info.getPriority(); 8928 res.preferredOrder = activity.owner.mPreferredOrder; 8929 //System.out.println("Result: " + res.activityInfo.className + 8930 // " = " + res.priority); 8931 res.match = match; 8932 res.isDefault = info.hasDefault; 8933 res.labelRes = info.labelRes; 8934 res.nonLocalizedLabel = info.nonLocalizedLabel; 8935 if (userNeedsBadging(userId)) { 8936 res.noResourceId = true; 8937 } else { 8938 res.icon = info.icon; 8939 } 8940 res.iconResourceId = info.icon; 8941 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8942 return res; 8943 } 8944 8945 @Override 8946 protected void sortResults(List<ResolveInfo> results) { 8947 Collections.sort(results, mResolvePrioritySorter); 8948 } 8949 8950 @Override 8951 protected void dumpFilter(PrintWriter out, String prefix, 8952 PackageParser.ActivityIntentInfo filter) { 8953 out.print(prefix); out.print( 8954 Integer.toHexString(System.identityHashCode(filter.activity))); 8955 out.print(' '); 8956 filter.activity.printComponentShortName(out); 8957 out.print(" filter "); 8958 out.println(Integer.toHexString(System.identityHashCode(filter))); 8959 } 8960 8961 @Override 8962 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8963 return filter.activity; 8964 } 8965 8966 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8967 PackageParser.Activity activity = (PackageParser.Activity)label; 8968 out.print(prefix); out.print( 8969 Integer.toHexString(System.identityHashCode(activity))); 8970 out.print(' '); 8971 activity.printComponentShortName(out); 8972 if (count > 1) { 8973 out.print(" ("); out.print(count); out.print(" filters)"); 8974 } 8975 out.println(); 8976 } 8977 8978// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8979// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8980// final List<ResolveInfo> retList = Lists.newArrayList(); 8981// while (i.hasNext()) { 8982// final ResolveInfo resolveInfo = i.next(); 8983// if (isEnabledLP(resolveInfo.activityInfo)) { 8984// retList.add(resolveInfo); 8985// } 8986// } 8987// return retList; 8988// } 8989 8990 // Keys are String (activity class name), values are Activity. 8991 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8992 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8993 private int mFlags; 8994 } 8995 8996 private final class ServiceIntentResolver 8997 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8998 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8999 boolean defaultOnly, int userId) { 9000 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9001 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9002 } 9003 9004 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9005 int userId) { 9006 if (!sUserManager.exists(userId)) return null; 9007 mFlags = flags; 9008 return super.queryIntent(intent, resolvedType, 9009 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9010 } 9011 9012 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9013 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9014 if (!sUserManager.exists(userId)) return null; 9015 if (packageServices == null) { 9016 return null; 9017 } 9018 mFlags = flags; 9019 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9020 final int N = packageServices.size(); 9021 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9022 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9023 9024 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9025 for (int i = 0; i < N; ++i) { 9026 intentFilters = packageServices.get(i).intents; 9027 if (intentFilters != null && intentFilters.size() > 0) { 9028 PackageParser.ServiceIntentInfo[] array = 9029 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9030 intentFilters.toArray(array); 9031 listCut.add(array); 9032 } 9033 } 9034 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9035 } 9036 9037 public final void addService(PackageParser.Service s) { 9038 mServices.put(s.getComponentName(), s); 9039 if (DEBUG_SHOW_INFO) { 9040 Log.v(TAG, " " 9041 + (s.info.nonLocalizedLabel != null 9042 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9043 Log.v(TAG, " Class=" + s.info.name); 9044 } 9045 final int NI = s.intents.size(); 9046 int j; 9047 for (j=0; j<NI; j++) { 9048 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9049 if (DEBUG_SHOW_INFO) { 9050 Log.v(TAG, " IntentFilter:"); 9051 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9052 } 9053 if (!intent.debugCheck()) { 9054 Log.w(TAG, "==> For Service " + s.info.name); 9055 } 9056 addFilter(intent); 9057 } 9058 } 9059 9060 public final void removeService(PackageParser.Service s) { 9061 mServices.remove(s.getComponentName()); 9062 if (DEBUG_SHOW_INFO) { 9063 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9064 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9065 Log.v(TAG, " Class=" + s.info.name); 9066 } 9067 final int NI = s.intents.size(); 9068 int j; 9069 for (j=0; j<NI; j++) { 9070 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9071 if (DEBUG_SHOW_INFO) { 9072 Log.v(TAG, " IntentFilter:"); 9073 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9074 } 9075 removeFilter(intent); 9076 } 9077 } 9078 9079 @Override 9080 protected boolean allowFilterResult( 9081 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9082 ServiceInfo filterSi = filter.service.info; 9083 for (int i=dest.size()-1; i>=0; i--) { 9084 ServiceInfo destAi = dest.get(i).serviceInfo; 9085 if (destAi.name == filterSi.name 9086 && destAi.packageName == filterSi.packageName) { 9087 return false; 9088 } 9089 } 9090 return true; 9091 } 9092 9093 @Override 9094 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9095 return new PackageParser.ServiceIntentInfo[size]; 9096 } 9097 9098 @Override 9099 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9100 if (!sUserManager.exists(userId)) return true; 9101 PackageParser.Package p = filter.service.owner; 9102 if (p != null) { 9103 PackageSetting ps = (PackageSetting)p.mExtras; 9104 if (ps != null) { 9105 // System apps are never considered stopped for purposes of 9106 // filtering, because there may be no way for the user to 9107 // actually re-launch them. 9108 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9109 && ps.getStopped(userId); 9110 } 9111 } 9112 return false; 9113 } 9114 9115 @Override 9116 protected boolean isPackageForFilter(String packageName, 9117 PackageParser.ServiceIntentInfo info) { 9118 return packageName.equals(info.service.owner.packageName); 9119 } 9120 9121 @Override 9122 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9123 int match, int userId) { 9124 if (!sUserManager.exists(userId)) return null; 9125 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9126 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9127 return null; 9128 } 9129 final PackageParser.Service service = info.service; 9130 if (mSafeMode && (service.info.applicationInfo.flags 9131 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9132 return null; 9133 } 9134 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9135 if (ps == null) { 9136 return null; 9137 } 9138 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9139 ps.readUserState(userId), userId); 9140 if (si == null) { 9141 return null; 9142 } 9143 final ResolveInfo res = new ResolveInfo(); 9144 res.serviceInfo = si; 9145 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9146 res.filter = filter; 9147 } 9148 res.priority = info.getPriority(); 9149 res.preferredOrder = service.owner.mPreferredOrder; 9150 res.match = match; 9151 res.isDefault = info.hasDefault; 9152 res.labelRes = info.labelRes; 9153 res.nonLocalizedLabel = info.nonLocalizedLabel; 9154 res.icon = info.icon; 9155 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9156 return res; 9157 } 9158 9159 @Override 9160 protected void sortResults(List<ResolveInfo> results) { 9161 Collections.sort(results, mResolvePrioritySorter); 9162 } 9163 9164 @Override 9165 protected void dumpFilter(PrintWriter out, String prefix, 9166 PackageParser.ServiceIntentInfo filter) { 9167 out.print(prefix); out.print( 9168 Integer.toHexString(System.identityHashCode(filter.service))); 9169 out.print(' '); 9170 filter.service.printComponentShortName(out); 9171 out.print(" filter "); 9172 out.println(Integer.toHexString(System.identityHashCode(filter))); 9173 } 9174 9175 @Override 9176 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9177 return filter.service; 9178 } 9179 9180 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9181 PackageParser.Service service = (PackageParser.Service)label; 9182 out.print(prefix); out.print( 9183 Integer.toHexString(System.identityHashCode(service))); 9184 out.print(' '); 9185 service.printComponentShortName(out); 9186 if (count > 1) { 9187 out.print(" ("); out.print(count); out.print(" filters)"); 9188 } 9189 out.println(); 9190 } 9191 9192// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9193// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9194// final List<ResolveInfo> retList = Lists.newArrayList(); 9195// while (i.hasNext()) { 9196// final ResolveInfo resolveInfo = (ResolveInfo) i; 9197// if (isEnabledLP(resolveInfo.serviceInfo)) { 9198// retList.add(resolveInfo); 9199// } 9200// } 9201// return retList; 9202// } 9203 9204 // Keys are String (activity class name), values are Activity. 9205 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9206 = new ArrayMap<ComponentName, PackageParser.Service>(); 9207 private int mFlags; 9208 }; 9209 9210 private final class ProviderIntentResolver 9211 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9212 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9213 boolean defaultOnly, int userId) { 9214 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9215 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9216 } 9217 9218 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9219 int userId) { 9220 if (!sUserManager.exists(userId)) 9221 return null; 9222 mFlags = flags; 9223 return super.queryIntent(intent, resolvedType, 9224 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9225 } 9226 9227 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9228 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9229 if (!sUserManager.exists(userId)) 9230 return null; 9231 if (packageProviders == null) { 9232 return null; 9233 } 9234 mFlags = flags; 9235 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9236 final int N = packageProviders.size(); 9237 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9238 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9239 9240 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9241 for (int i = 0; i < N; ++i) { 9242 intentFilters = packageProviders.get(i).intents; 9243 if (intentFilters != null && intentFilters.size() > 0) { 9244 PackageParser.ProviderIntentInfo[] array = 9245 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9246 intentFilters.toArray(array); 9247 listCut.add(array); 9248 } 9249 } 9250 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9251 } 9252 9253 public final void addProvider(PackageParser.Provider p) { 9254 if (mProviders.containsKey(p.getComponentName())) { 9255 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9256 return; 9257 } 9258 9259 mProviders.put(p.getComponentName(), p); 9260 if (DEBUG_SHOW_INFO) { 9261 Log.v(TAG, " " 9262 + (p.info.nonLocalizedLabel != null 9263 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9264 Log.v(TAG, " Class=" + p.info.name); 9265 } 9266 final int NI = p.intents.size(); 9267 int j; 9268 for (j = 0; j < NI; j++) { 9269 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9270 if (DEBUG_SHOW_INFO) { 9271 Log.v(TAG, " IntentFilter:"); 9272 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9273 } 9274 if (!intent.debugCheck()) { 9275 Log.w(TAG, "==> For Provider " + p.info.name); 9276 } 9277 addFilter(intent); 9278 } 9279 } 9280 9281 public final void removeProvider(PackageParser.Provider p) { 9282 mProviders.remove(p.getComponentName()); 9283 if (DEBUG_SHOW_INFO) { 9284 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9285 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9286 Log.v(TAG, " Class=" + p.info.name); 9287 } 9288 final int NI = p.intents.size(); 9289 int j; 9290 for (j = 0; j < NI; j++) { 9291 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9292 if (DEBUG_SHOW_INFO) { 9293 Log.v(TAG, " IntentFilter:"); 9294 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9295 } 9296 removeFilter(intent); 9297 } 9298 } 9299 9300 @Override 9301 protected boolean allowFilterResult( 9302 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9303 ProviderInfo filterPi = filter.provider.info; 9304 for (int i = dest.size() - 1; i >= 0; i--) { 9305 ProviderInfo destPi = dest.get(i).providerInfo; 9306 if (destPi.name == filterPi.name 9307 && destPi.packageName == filterPi.packageName) { 9308 return false; 9309 } 9310 } 9311 return true; 9312 } 9313 9314 @Override 9315 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9316 return new PackageParser.ProviderIntentInfo[size]; 9317 } 9318 9319 @Override 9320 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9321 if (!sUserManager.exists(userId)) 9322 return true; 9323 PackageParser.Package p = filter.provider.owner; 9324 if (p != null) { 9325 PackageSetting ps = (PackageSetting) p.mExtras; 9326 if (ps != null) { 9327 // System apps are never considered stopped for purposes of 9328 // filtering, because there may be no way for the user to 9329 // actually re-launch them. 9330 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9331 && ps.getStopped(userId); 9332 } 9333 } 9334 return false; 9335 } 9336 9337 @Override 9338 protected boolean isPackageForFilter(String packageName, 9339 PackageParser.ProviderIntentInfo info) { 9340 return packageName.equals(info.provider.owner.packageName); 9341 } 9342 9343 @Override 9344 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9345 int match, int userId) { 9346 if (!sUserManager.exists(userId)) 9347 return null; 9348 final PackageParser.ProviderIntentInfo info = filter; 9349 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9350 return null; 9351 } 9352 final PackageParser.Provider provider = info.provider; 9353 if (mSafeMode && (provider.info.applicationInfo.flags 9354 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9355 return null; 9356 } 9357 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9358 if (ps == null) { 9359 return null; 9360 } 9361 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9362 ps.readUserState(userId), userId); 9363 if (pi == null) { 9364 return null; 9365 } 9366 final ResolveInfo res = new ResolveInfo(); 9367 res.providerInfo = pi; 9368 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9369 res.filter = filter; 9370 } 9371 res.priority = info.getPriority(); 9372 res.preferredOrder = provider.owner.mPreferredOrder; 9373 res.match = match; 9374 res.isDefault = info.hasDefault; 9375 res.labelRes = info.labelRes; 9376 res.nonLocalizedLabel = info.nonLocalizedLabel; 9377 res.icon = info.icon; 9378 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9379 return res; 9380 } 9381 9382 @Override 9383 protected void sortResults(List<ResolveInfo> results) { 9384 Collections.sort(results, mResolvePrioritySorter); 9385 } 9386 9387 @Override 9388 protected void dumpFilter(PrintWriter out, String prefix, 9389 PackageParser.ProviderIntentInfo filter) { 9390 out.print(prefix); 9391 out.print( 9392 Integer.toHexString(System.identityHashCode(filter.provider))); 9393 out.print(' '); 9394 filter.provider.printComponentShortName(out); 9395 out.print(" filter "); 9396 out.println(Integer.toHexString(System.identityHashCode(filter))); 9397 } 9398 9399 @Override 9400 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9401 return filter.provider; 9402 } 9403 9404 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9405 PackageParser.Provider provider = (PackageParser.Provider)label; 9406 out.print(prefix); out.print( 9407 Integer.toHexString(System.identityHashCode(provider))); 9408 out.print(' '); 9409 provider.printComponentShortName(out); 9410 if (count > 1) { 9411 out.print(" ("); out.print(count); out.print(" filters)"); 9412 } 9413 out.println(); 9414 } 9415 9416 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9417 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9418 private int mFlags; 9419 }; 9420 9421 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9422 new Comparator<ResolveInfo>() { 9423 public int compare(ResolveInfo r1, ResolveInfo r2) { 9424 int v1 = r1.priority; 9425 int v2 = r2.priority; 9426 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9427 if (v1 != v2) { 9428 return (v1 > v2) ? -1 : 1; 9429 } 9430 v1 = r1.preferredOrder; 9431 v2 = r2.preferredOrder; 9432 if (v1 != v2) { 9433 return (v1 > v2) ? -1 : 1; 9434 } 9435 if (r1.isDefault != r2.isDefault) { 9436 return r1.isDefault ? -1 : 1; 9437 } 9438 v1 = r1.match; 9439 v2 = r2.match; 9440 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9441 if (v1 != v2) { 9442 return (v1 > v2) ? -1 : 1; 9443 } 9444 if (r1.system != r2.system) { 9445 return r1.system ? -1 : 1; 9446 } 9447 return 0; 9448 } 9449 }; 9450 9451 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9452 new Comparator<ProviderInfo>() { 9453 public int compare(ProviderInfo p1, ProviderInfo p2) { 9454 final int v1 = p1.initOrder; 9455 final int v2 = p2.initOrder; 9456 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9457 } 9458 }; 9459 9460 final void sendPackageBroadcast(final String action, final String pkg, 9461 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9462 final int[] userIds) { 9463 mHandler.post(new Runnable() { 9464 @Override 9465 public void run() { 9466 try { 9467 final IActivityManager am = ActivityManagerNative.getDefault(); 9468 if (am == null) return; 9469 final int[] resolvedUserIds; 9470 if (userIds == null) { 9471 resolvedUserIds = am.getRunningUserIds(); 9472 } else { 9473 resolvedUserIds = userIds; 9474 } 9475 for (int id : resolvedUserIds) { 9476 final Intent intent = new Intent(action, 9477 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9478 if (extras != null) { 9479 intent.putExtras(extras); 9480 } 9481 if (targetPkg != null) { 9482 intent.setPackage(targetPkg); 9483 } 9484 // Modify the UID when posting to other users 9485 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9486 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9487 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9488 intent.putExtra(Intent.EXTRA_UID, uid); 9489 } 9490 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9491 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9492 if (DEBUG_BROADCASTS) { 9493 RuntimeException here = new RuntimeException("here"); 9494 here.fillInStackTrace(); 9495 Slog.d(TAG, "Sending to user " + id + ": " 9496 + intent.toShortString(false, true, false, false) 9497 + " " + intent.getExtras(), here); 9498 } 9499 am.broadcastIntent(null, intent, null, finishedReceiver, 9500 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9501 null, finishedReceiver != null, false, id); 9502 } 9503 } catch (RemoteException ex) { 9504 } 9505 } 9506 }); 9507 } 9508 9509 /** 9510 * Check if the external storage media is available. This is true if there 9511 * is a mounted external storage medium or if the external storage is 9512 * emulated. 9513 */ 9514 private boolean isExternalMediaAvailable() { 9515 return mMediaMounted || Environment.isExternalStorageEmulated(); 9516 } 9517 9518 @Override 9519 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9520 // writer 9521 synchronized (mPackages) { 9522 if (!isExternalMediaAvailable()) { 9523 // If the external storage is no longer mounted at this point, 9524 // the caller may not have been able to delete all of this 9525 // packages files and can not delete any more. Bail. 9526 return null; 9527 } 9528 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9529 if (lastPackage != null) { 9530 pkgs.remove(lastPackage); 9531 } 9532 if (pkgs.size() > 0) { 9533 return pkgs.get(0); 9534 } 9535 } 9536 return null; 9537 } 9538 9539 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9540 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9541 userId, andCode ? 1 : 0, packageName); 9542 if (mSystemReady) { 9543 msg.sendToTarget(); 9544 } else { 9545 if (mPostSystemReadyMessages == null) { 9546 mPostSystemReadyMessages = new ArrayList<>(); 9547 } 9548 mPostSystemReadyMessages.add(msg); 9549 } 9550 } 9551 9552 void startCleaningPackages() { 9553 // reader 9554 synchronized (mPackages) { 9555 if (!isExternalMediaAvailable()) { 9556 return; 9557 } 9558 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9559 return; 9560 } 9561 } 9562 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9563 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9564 IActivityManager am = ActivityManagerNative.getDefault(); 9565 if (am != null) { 9566 try { 9567 am.startService(null, intent, null, mContext.getOpPackageName(), 9568 UserHandle.USER_OWNER); 9569 } catch (RemoteException e) { 9570 } 9571 } 9572 } 9573 9574 @Override 9575 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9576 int installFlags, String installerPackageName, VerificationParams verificationParams, 9577 String packageAbiOverride) { 9578 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9579 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9580 } 9581 9582 @Override 9583 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9584 int installFlags, String installerPackageName, VerificationParams verificationParams, 9585 String packageAbiOverride, int userId) { 9586 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9587 9588 final int callingUid = Binder.getCallingUid(); 9589 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9590 9591 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9592 try { 9593 if (observer != null) { 9594 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9595 } 9596 } catch (RemoteException re) { 9597 } 9598 return; 9599 } 9600 9601 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9602 installFlags |= PackageManager.INSTALL_FROM_ADB; 9603 9604 } else { 9605 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9606 // about installerPackageName. 9607 9608 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9609 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9610 } 9611 9612 UserHandle user; 9613 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9614 user = UserHandle.ALL; 9615 } else { 9616 user = new UserHandle(userId); 9617 } 9618 9619 // Only system components can circumvent runtime permissions when installing. 9620 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9621 && mContext.checkCallingOrSelfPermission(Manifest.permission 9622 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9623 throw new SecurityException("You need the " 9624 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9625 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9626 } 9627 9628 verificationParams.setInstallerUid(callingUid); 9629 9630 final File originFile = new File(originPath); 9631 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9632 9633 final Message msg = mHandler.obtainMessage(INIT_COPY); 9634 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9635 null, verificationParams, user, packageAbiOverride, null); 9636 mHandler.sendMessage(msg); 9637 } 9638 9639 void installStage(String packageName, File stagedDir, String stagedCid, 9640 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9641 String installerPackageName, int installerUid, UserHandle user) { 9642 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9643 params.referrerUri, installerUid, null); 9644 verifParams.setInstallerUid(installerUid); 9645 9646 final OriginInfo origin; 9647 if (stagedDir != null) { 9648 origin = OriginInfo.fromStagedFile(stagedDir); 9649 } else { 9650 origin = OriginInfo.fromStagedContainer(stagedCid); 9651 } 9652 9653 final Message msg = mHandler.obtainMessage(INIT_COPY); 9654 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9655 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9656 params.grantedRuntimePermissions); 9657 9658 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9659 System.identityHashCode(msg.obj)); 9660 9661 mHandler.sendMessage(msg); 9662 } 9663 9664 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9665 Bundle extras = new Bundle(1); 9666 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9667 9668 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9669 packageName, extras, null, null, new int[] {userId}); 9670 try { 9671 IActivityManager am = ActivityManagerNative.getDefault(); 9672 final boolean isSystem = 9673 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9674 if (isSystem && am.isUserRunning(userId, false)) { 9675 // The just-installed/enabled app is bundled on the system, so presumed 9676 // to be able to run automatically without needing an explicit launch. 9677 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9678 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9679 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9680 .setPackage(packageName); 9681 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9682 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9683 } 9684 } catch (RemoteException e) { 9685 // shouldn't happen 9686 Slog.w(TAG, "Unable to bootstrap installed package", e); 9687 } 9688 } 9689 9690 @Override 9691 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9692 int userId) { 9693 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9694 PackageSetting pkgSetting; 9695 final int uid = Binder.getCallingUid(); 9696 enforceCrossUserPermission(uid, userId, true, true, 9697 "setApplicationHiddenSetting for user " + userId); 9698 9699 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9700 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9701 return false; 9702 } 9703 9704 long callingId = Binder.clearCallingIdentity(); 9705 try { 9706 boolean sendAdded = false; 9707 boolean sendRemoved = false; 9708 // writer 9709 synchronized (mPackages) { 9710 pkgSetting = mSettings.mPackages.get(packageName); 9711 if (pkgSetting == null) { 9712 return false; 9713 } 9714 if (pkgSetting.getHidden(userId) != hidden) { 9715 pkgSetting.setHidden(hidden, userId); 9716 mSettings.writePackageRestrictionsLPr(userId); 9717 if (hidden) { 9718 sendRemoved = true; 9719 } else { 9720 sendAdded = true; 9721 } 9722 } 9723 } 9724 if (sendAdded) { 9725 sendPackageAddedForUser(packageName, pkgSetting, userId); 9726 return true; 9727 } 9728 if (sendRemoved) { 9729 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9730 "hiding pkg"); 9731 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9732 return true; 9733 } 9734 } finally { 9735 Binder.restoreCallingIdentity(callingId); 9736 } 9737 return false; 9738 } 9739 9740 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9741 int userId) { 9742 final PackageRemovedInfo info = new PackageRemovedInfo(); 9743 info.removedPackage = packageName; 9744 info.removedUsers = new int[] {userId}; 9745 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9746 info.sendBroadcast(false, false, false); 9747 } 9748 9749 /** 9750 * Returns true if application is not found or there was an error. Otherwise it returns 9751 * the hidden state of the package for the given user. 9752 */ 9753 @Override 9754 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9755 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9756 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9757 false, "getApplicationHidden for user " + userId); 9758 PackageSetting pkgSetting; 9759 long callingId = Binder.clearCallingIdentity(); 9760 try { 9761 // writer 9762 synchronized (mPackages) { 9763 pkgSetting = mSettings.mPackages.get(packageName); 9764 if (pkgSetting == null) { 9765 return true; 9766 } 9767 return pkgSetting.getHidden(userId); 9768 } 9769 } finally { 9770 Binder.restoreCallingIdentity(callingId); 9771 } 9772 } 9773 9774 /** 9775 * @hide 9776 */ 9777 @Override 9778 public int installExistingPackageAsUser(String packageName, int userId) { 9779 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9780 null); 9781 PackageSetting pkgSetting; 9782 final int uid = Binder.getCallingUid(); 9783 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9784 + userId); 9785 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9786 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9787 } 9788 9789 long callingId = Binder.clearCallingIdentity(); 9790 try { 9791 boolean sendAdded = false; 9792 9793 // writer 9794 synchronized (mPackages) { 9795 pkgSetting = mSettings.mPackages.get(packageName); 9796 if (pkgSetting == null) { 9797 return PackageManager.INSTALL_FAILED_INVALID_URI; 9798 } 9799 if (!pkgSetting.getInstalled(userId)) { 9800 pkgSetting.setInstalled(true, userId); 9801 pkgSetting.setHidden(false, userId); 9802 mSettings.writePackageRestrictionsLPr(userId); 9803 sendAdded = true; 9804 } 9805 } 9806 9807 if (sendAdded) { 9808 sendPackageAddedForUser(packageName, pkgSetting, userId); 9809 } 9810 } finally { 9811 Binder.restoreCallingIdentity(callingId); 9812 } 9813 9814 return PackageManager.INSTALL_SUCCEEDED; 9815 } 9816 9817 boolean isUserRestricted(int userId, String restrictionKey) { 9818 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9819 if (restrictions.getBoolean(restrictionKey, false)) { 9820 Log.w(TAG, "User is restricted: " + restrictionKey); 9821 return true; 9822 } 9823 return false; 9824 } 9825 9826 @Override 9827 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9828 mContext.enforceCallingOrSelfPermission( 9829 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9830 "Only package verification agents can verify applications"); 9831 9832 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9833 final PackageVerificationResponse response = new PackageVerificationResponse( 9834 verificationCode, Binder.getCallingUid()); 9835 msg.arg1 = id; 9836 msg.obj = response; 9837 mHandler.sendMessage(msg); 9838 } 9839 9840 @Override 9841 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9842 long millisecondsToDelay) { 9843 mContext.enforceCallingOrSelfPermission( 9844 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9845 "Only package verification agents can extend verification timeouts"); 9846 9847 final PackageVerificationState state = mPendingVerification.get(id); 9848 final PackageVerificationResponse response = new PackageVerificationResponse( 9849 verificationCodeAtTimeout, Binder.getCallingUid()); 9850 9851 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9852 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9853 } 9854 if (millisecondsToDelay < 0) { 9855 millisecondsToDelay = 0; 9856 } 9857 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9858 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9859 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9860 } 9861 9862 if ((state != null) && !state.timeoutExtended()) { 9863 state.extendTimeout(); 9864 9865 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9866 msg.arg1 = id; 9867 msg.obj = response; 9868 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9869 } 9870 } 9871 9872 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9873 int verificationCode, UserHandle user) { 9874 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9875 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9876 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9877 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9878 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9879 9880 mContext.sendBroadcastAsUser(intent, user, 9881 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9882 } 9883 9884 private ComponentName matchComponentForVerifier(String packageName, 9885 List<ResolveInfo> receivers) { 9886 ActivityInfo targetReceiver = null; 9887 9888 final int NR = receivers.size(); 9889 for (int i = 0; i < NR; i++) { 9890 final ResolveInfo info = receivers.get(i); 9891 if (info.activityInfo == null) { 9892 continue; 9893 } 9894 9895 if (packageName.equals(info.activityInfo.packageName)) { 9896 targetReceiver = info.activityInfo; 9897 break; 9898 } 9899 } 9900 9901 if (targetReceiver == null) { 9902 return null; 9903 } 9904 9905 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9906 } 9907 9908 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9909 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9910 if (pkgInfo.verifiers.length == 0) { 9911 return null; 9912 } 9913 9914 final int N = pkgInfo.verifiers.length; 9915 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9916 for (int i = 0; i < N; i++) { 9917 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9918 9919 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9920 receivers); 9921 if (comp == null) { 9922 continue; 9923 } 9924 9925 final int verifierUid = getUidForVerifier(verifierInfo); 9926 if (verifierUid == -1) { 9927 continue; 9928 } 9929 9930 if (DEBUG_VERIFY) { 9931 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9932 + " with the correct signature"); 9933 } 9934 sufficientVerifiers.add(comp); 9935 verificationState.addSufficientVerifier(verifierUid); 9936 } 9937 9938 return sufficientVerifiers; 9939 } 9940 9941 private int getUidForVerifier(VerifierInfo verifierInfo) { 9942 synchronized (mPackages) { 9943 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9944 if (pkg == null) { 9945 return -1; 9946 } else if (pkg.mSignatures.length != 1) { 9947 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9948 + " has more than one signature; ignoring"); 9949 return -1; 9950 } 9951 9952 /* 9953 * If the public key of the package's signature does not match 9954 * our expected public key, then this is a different package and 9955 * we should skip. 9956 */ 9957 9958 final byte[] expectedPublicKey; 9959 try { 9960 final Signature verifierSig = pkg.mSignatures[0]; 9961 final PublicKey publicKey = verifierSig.getPublicKey(); 9962 expectedPublicKey = publicKey.getEncoded(); 9963 } catch (CertificateException e) { 9964 return -1; 9965 } 9966 9967 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9968 9969 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9970 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9971 + " does not have the expected public key; ignoring"); 9972 return -1; 9973 } 9974 9975 return pkg.applicationInfo.uid; 9976 } 9977 } 9978 9979 @Override 9980 public void finishPackageInstall(int token) { 9981 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9982 9983 if (DEBUG_INSTALL) { 9984 Slog.v(TAG, "BM finishing package install for " + token); 9985 } 9986 9987 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9988 mHandler.sendMessage(msg); 9989 } 9990 9991 /** 9992 * Get the verification agent timeout. 9993 * 9994 * @return verification timeout in milliseconds 9995 */ 9996 private long getVerificationTimeout() { 9997 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9998 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9999 DEFAULT_VERIFICATION_TIMEOUT); 10000 } 10001 10002 /** 10003 * Get the default verification agent response code. 10004 * 10005 * @return default verification response code 10006 */ 10007 private int getDefaultVerificationResponse() { 10008 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10009 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10010 DEFAULT_VERIFICATION_RESPONSE); 10011 } 10012 10013 /** 10014 * Check whether or not package verification has been enabled. 10015 * 10016 * @return true if verification should be performed 10017 */ 10018 private boolean isVerificationEnabled(int userId, int installFlags) { 10019 if (!DEFAULT_VERIFY_ENABLE) { 10020 return false; 10021 } 10022 10023 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10024 10025 // Check if installing from ADB 10026 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10027 // Do not run verification in a test harness environment 10028 if (ActivityManager.isRunningInTestHarness()) { 10029 return false; 10030 } 10031 if (ensureVerifyAppsEnabled) { 10032 return true; 10033 } 10034 // Check if the developer does not want package verification for ADB installs 10035 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10036 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10037 return false; 10038 } 10039 } 10040 10041 if (ensureVerifyAppsEnabled) { 10042 return true; 10043 } 10044 10045 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10046 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10047 } 10048 10049 @Override 10050 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10051 throws RemoteException { 10052 mContext.enforceCallingOrSelfPermission( 10053 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10054 "Only intentfilter verification agents can verify applications"); 10055 10056 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10057 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10058 Binder.getCallingUid(), verificationCode, failedDomains); 10059 msg.arg1 = id; 10060 msg.obj = response; 10061 mHandler.sendMessage(msg); 10062 } 10063 10064 @Override 10065 public int getIntentVerificationStatus(String packageName, int userId) { 10066 synchronized (mPackages) { 10067 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10068 } 10069 } 10070 10071 @Override 10072 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10073 mContext.enforceCallingOrSelfPermission( 10074 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10075 10076 boolean result = false; 10077 synchronized (mPackages) { 10078 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10079 } 10080 if (result) { 10081 scheduleWritePackageRestrictionsLocked(userId); 10082 } 10083 return result; 10084 } 10085 10086 @Override 10087 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10088 synchronized (mPackages) { 10089 return mSettings.getIntentFilterVerificationsLPr(packageName); 10090 } 10091 } 10092 10093 @Override 10094 public List<IntentFilter> getAllIntentFilters(String packageName) { 10095 if (TextUtils.isEmpty(packageName)) { 10096 return Collections.<IntentFilter>emptyList(); 10097 } 10098 synchronized (mPackages) { 10099 PackageParser.Package pkg = mPackages.get(packageName); 10100 if (pkg == null || pkg.activities == null) { 10101 return Collections.<IntentFilter>emptyList(); 10102 } 10103 final int count = pkg.activities.size(); 10104 ArrayList<IntentFilter> result = new ArrayList<>(); 10105 for (int n=0; n<count; n++) { 10106 PackageParser.Activity activity = pkg.activities.get(n); 10107 if (activity.intents != null || activity.intents.size() > 0) { 10108 result.addAll(activity.intents); 10109 } 10110 } 10111 return result; 10112 } 10113 } 10114 10115 @Override 10116 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10117 mContext.enforceCallingOrSelfPermission( 10118 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10119 10120 synchronized (mPackages) { 10121 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10122 if (packageName != null) { 10123 result |= updateIntentVerificationStatus(packageName, 10124 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10125 userId); 10126 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10127 packageName, userId); 10128 } 10129 return result; 10130 } 10131 } 10132 10133 @Override 10134 public String getDefaultBrowserPackageName(int userId) { 10135 synchronized (mPackages) { 10136 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10137 } 10138 } 10139 10140 /** 10141 * Get the "allow unknown sources" setting. 10142 * 10143 * @return the current "allow unknown sources" setting 10144 */ 10145 private int getUnknownSourcesSettings() { 10146 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10147 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10148 -1); 10149 } 10150 10151 @Override 10152 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10153 final int uid = Binder.getCallingUid(); 10154 // writer 10155 synchronized (mPackages) { 10156 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10157 if (targetPackageSetting == null) { 10158 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10159 } 10160 10161 PackageSetting installerPackageSetting; 10162 if (installerPackageName != null) { 10163 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10164 if (installerPackageSetting == null) { 10165 throw new IllegalArgumentException("Unknown installer package: " 10166 + installerPackageName); 10167 } 10168 } else { 10169 installerPackageSetting = null; 10170 } 10171 10172 Signature[] callerSignature; 10173 Object obj = mSettings.getUserIdLPr(uid); 10174 if (obj != null) { 10175 if (obj instanceof SharedUserSetting) { 10176 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10177 } else if (obj instanceof PackageSetting) { 10178 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10179 } else { 10180 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10181 } 10182 } else { 10183 throw new SecurityException("Unknown calling uid " + uid); 10184 } 10185 10186 // Verify: can't set installerPackageName to a package that is 10187 // not signed with the same cert as the caller. 10188 if (installerPackageSetting != null) { 10189 if (compareSignatures(callerSignature, 10190 installerPackageSetting.signatures.mSignatures) 10191 != PackageManager.SIGNATURE_MATCH) { 10192 throw new SecurityException( 10193 "Caller does not have same cert as new installer package " 10194 + installerPackageName); 10195 } 10196 } 10197 10198 // Verify: if target already has an installer package, it must 10199 // be signed with the same cert as the caller. 10200 if (targetPackageSetting.installerPackageName != null) { 10201 PackageSetting setting = mSettings.mPackages.get( 10202 targetPackageSetting.installerPackageName); 10203 // If the currently set package isn't valid, then it's always 10204 // okay to change it. 10205 if (setting != null) { 10206 if (compareSignatures(callerSignature, 10207 setting.signatures.mSignatures) 10208 != PackageManager.SIGNATURE_MATCH) { 10209 throw new SecurityException( 10210 "Caller does not have same cert as old installer package " 10211 + targetPackageSetting.installerPackageName); 10212 } 10213 } 10214 } 10215 10216 // Okay! 10217 targetPackageSetting.installerPackageName = installerPackageName; 10218 scheduleWriteSettingsLocked(); 10219 } 10220 } 10221 10222 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10223 // Queue up an async operation since the package installation may take a little while. 10224 mHandler.post(new Runnable() { 10225 public void run() { 10226 mHandler.removeCallbacks(this); 10227 // Result object to be returned 10228 PackageInstalledInfo res = new PackageInstalledInfo(); 10229 res.returnCode = currentStatus; 10230 res.uid = -1; 10231 res.pkg = null; 10232 res.removedInfo = new PackageRemovedInfo(); 10233 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10234 args.doPreInstall(res.returnCode); 10235 synchronized (mInstallLock) { 10236 installPackageTracedLI(args, res); 10237 } 10238 args.doPostInstall(res.returnCode, res.uid); 10239 } 10240 10241 // A restore should be performed at this point if (a) the install 10242 // succeeded, (b) the operation is not an update, and (c) the new 10243 // package has not opted out of backup participation. 10244 final boolean update = res.removedInfo.removedPackage != null; 10245 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10246 boolean doRestore = !update 10247 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10248 10249 // Set up the post-install work request bookkeeping. This will be used 10250 // and cleaned up by the post-install event handling regardless of whether 10251 // there's a restore pass performed. Token values are >= 1. 10252 int token; 10253 if (mNextInstallToken < 0) mNextInstallToken = 1; 10254 token = mNextInstallToken++; 10255 10256 PostInstallData data = new PostInstallData(args, res); 10257 mRunningInstalls.put(token, data); 10258 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10259 10260 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10261 // Pass responsibility to the Backup Manager. It will perform a 10262 // restore if appropriate, then pass responsibility back to the 10263 // Package Manager to run the post-install observer callbacks 10264 // and broadcasts. 10265 IBackupManager bm = IBackupManager.Stub.asInterface( 10266 ServiceManager.getService(Context.BACKUP_SERVICE)); 10267 if (bm != null) { 10268 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10269 + " to BM for possible restore"); 10270 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10271 try { 10272 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10273 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10274 } else { 10275 doRestore = false; 10276 } 10277 } catch (RemoteException e) { 10278 // can't happen; the backup manager is local 10279 } catch (Exception e) { 10280 Slog.e(TAG, "Exception trying to enqueue restore", e); 10281 doRestore = false; 10282 } finally { 10283 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10284 } 10285 } else { 10286 Slog.e(TAG, "Backup Manager not found!"); 10287 doRestore = false; 10288 } 10289 } 10290 10291 if (!doRestore) { 10292 // No restore possible, or the Backup Manager was mysteriously not 10293 // available -- just fire the post-install work request directly. 10294 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10295 10296 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10297 10298 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10299 mHandler.sendMessage(msg); 10300 } 10301 } 10302 }); 10303 } 10304 10305 private abstract class HandlerParams { 10306 private static final int MAX_RETRIES = 4; 10307 10308 /** 10309 * Number of times startCopy() has been attempted and had a non-fatal 10310 * error. 10311 */ 10312 private int mRetries = 0; 10313 10314 /** User handle for the user requesting the information or installation. */ 10315 private final UserHandle mUser; 10316 10317 HandlerParams(UserHandle user) { 10318 mUser = user; 10319 } 10320 10321 UserHandle getUser() { 10322 return mUser; 10323 } 10324 10325 final boolean startCopy() { 10326 boolean res; 10327 try { 10328 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10329 10330 if (++mRetries > MAX_RETRIES) { 10331 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10332 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10333 handleServiceError(); 10334 return false; 10335 } else { 10336 handleStartCopy(); 10337 res = true; 10338 } 10339 } catch (RemoteException e) { 10340 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10341 mHandler.sendEmptyMessage(MCS_RECONNECT); 10342 res = false; 10343 } 10344 handleReturnCode(); 10345 return res; 10346 } 10347 10348 final void serviceError() { 10349 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10350 handleServiceError(); 10351 handleReturnCode(); 10352 } 10353 10354 abstract void handleStartCopy() throws RemoteException; 10355 abstract void handleServiceError(); 10356 abstract void handleReturnCode(); 10357 } 10358 10359 class MeasureParams extends HandlerParams { 10360 private final PackageStats mStats; 10361 private boolean mSuccess; 10362 10363 private final IPackageStatsObserver mObserver; 10364 10365 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10366 super(new UserHandle(stats.userHandle)); 10367 mObserver = observer; 10368 mStats = stats; 10369 } 10370 10371 @Override 10372 public String toString() { 10373 return "MeasureParams{" 10374 + Integer.toHexString(System.identityHashCode(this)) 10375 + " " + mStats.packageName + "}"; 10376 } 10377 10378 @Override 10379 void handleStartCopy() throws RemoteException { 10380 synchronized (mInstallLock) { 10381 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10382 } 10383 10384 if (mSuccess) { 10385 final boolean mounted; 10386 if (Environment.isExternalStorageEmulated()) { 10387 mounted = true; 10388 } else { 10389 final String status = Environment.getExternalStorageState(); 10390 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10391 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10392 } 10393 10394 if (mounted) { 10395 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10396 10397 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10398 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10399 10400 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10401 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10402 10403 // Always subtract cache size, since it's a subdirectory 10404 mStats.externalDataSize -= mStats.externalCacheSize; 10405 10406 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10407 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10408 10409 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10410 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10411 } 10412 } 10413 } 10414 10415 @Override 10416 void handleReturnCode() { 10417 if (mObserver != null) { 10418 try { 10419 mObserver.onGetStatsCompleted(mStats, mSuccess); 10420 } catch (RemoteException e) { 10421 Slog.i(TAG, "Observer no longer exists."); 10422 } 10423 } 10424 } 10425 10426 @Override 10427 void handleServiceError() { 10428 Slog.e(TAG, "Could not measure application " + mStats.packageName 10429 + " external storage"); 10430 } 10431 } 10432 10433 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10434 throws RemoteException { 10435 long result = 0; 10436 for (File path : paths) { 10437 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10438 } 10439 return result; 10440 } 10441 10442 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10443 for (File path : paths) { 10444 try { 10445 mcs.clearDirectory(path.getAbsolutePath()); 10446 } catch (RemoteException e) { 10447 } 10448 } 10449 } 10450 10451 static class OriginInfo { 10452 /** 10453 * Location where install is coming from, before it has been 10454 * copied/renamed into place. This could be a single monolithic APK 10455 * file, or a cluster directory. This location may be untrusted. 10456 */ 10457 final File file; 10458 final String cid; 10459 10460 /** 10461 * Flag indicating that {@link #file} or {@link #cid} has already been 10462 * staged, meaning downstream users don't need to defensively copy the 10463 * contents. 10464 */ 10465 final boolean staged; 10466 10467 /** 10468 * Flag indicating that {@link #file} or {@link #cid} is an already 10469 * installed app that is being moved. 10470 */ 10471 final boolean existing; 10472 10473 final String resolvedPath; 10474 final File resolvedFile; 10475 10476 static OriginInfo fromNothing() { 10477 return new OriginInfo(null, null, false, false); 10478 } 10479 10480 static OriginInfo fromUntrustedFile(File file) { 10481 return new OriginInfo(file, null, false, false); 10482 } 10483 10484 static OriginInfo fromExistingFile(File file) { 10485 return new OriginInfo(file, null, false, true); 10486 } 10487 10488 static OriginInfo fromStagedFile(File file) { 10489 return new OriginInfo(file, null, true, false); 10490 } 10491 10492 static OriginInfo fromStagedContainer(String cid) { 10493 return new OriginInfo(null, cid, true, false); 10494 } 10495 10496 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10497 this.file = file; 10498 this.cid = cid; 10499 this.staged = staged; 10500 this.existing = existing; 10501 10502 if (cid != null) { 10503 resolvedPath = PackageHelper.getSdDir(cid); 10504 resolvedFile = new File(resolvedPath); 10505 } else if (file != null) { 10506 resolvedPath = file.getAbsolutePath(); 10507 resolvedFile = file; 10508 } else { 10509 resolvedPath = null; 10510 resolvedFile = null; 10511 } 10512 } 10513 } 10514 10515 class MoveInfo { 10516 final int moveId; 10517 final String fromUuid; 10518 final String toUuid; 10519 final String packageName; 10520 final String dataAppName; 10521 final int appId; 10522 final String seinfo; 10523 10524 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10525 String dataAppName, int appId, String seinfo) { 10526 this.moveId = moveId; 10527 this.fromUuid = fromUuid; 10528 this.toUuid = toUuid; 10529 this.packageName = packageName; 10530 this.dataAppName = dataAppName; 10531 this.appId = appId; 10532 this.seinfo = seinfo; 10533 } 10534 } 10535 10536 class InstallParams extends HandlerParams { 10537 final OriginInfo origin; 10538 final MoveInfo move; 10539 final IPackageInstallObserver2 observer; 10540 int installFlags; 10541 final String installerPackageName; 10542 final String volumeUuid; 10543 final VerificationParams verificationParams; 10544 private InstallArgs mArgs; 10545 private int mRet; 10546 final String packageAbiOverride; 10547 final String[] grantedRuntimePermissions; 10548 10549 10550 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10551 int installFlags, String installerPackageName, String volumeUuid, 10552 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10553 String[] grantedPermissions) { 10554 super(user); 10555 this.origin = origin; 10556 this.move = move; 10557 this.observer = observer; 10558 this.installFlags = installFlags; 10559 this.installerPackageName = installerPackageName; 10560 this.volumeUuid = volumeUuid; 10561 this.verificationParams = verificationParams; 10562 this.packageAbiOverride = packageAbiOverride; 10563 this.grantedRuntimePermissions = grantedPermissions; 10564 } 10565 10566 @Override 10567 public String toString() { 10568 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10569 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10570 } 10571 10572 public ManifestDigest getManifestDigest() { 10573 if (verificationParams == null) { 10574 return null; 10575 } 10576 return verificationParams.getManifestDigest(); 10577 } 10578 10579 private int installLocationPolicy(PackageInfoLite pkgLite) { 10580 String packageName = pkgLite.packageName; 10581 int installLocation = pkgLite.installLocation; 10582 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10583 // reader 10584 synchronized (mPackages) { 10585 PackageParser.Package pkg = mPackages.get(packageName); 10586 if (pkg != null) { 10587 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10588 // Check for downgrading. 10589 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10590 try { 10591 checkDowngrade(pkg, pkgLite); 10592 } catch (PackageManagerException e) { 10593 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10594 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10595 } 10596 } 10597 // Check for updated system application. 10598 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10599 if (onSd) { 10600 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10601 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10602 } 10603 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10604 } else { 10605 if (onSd) { 10606 // Install flag overrides everything. 10607 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10608 } 10609 // If current upgrade specifies particular preference 10610 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10611 // Application explicitly specified internal. 10612 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10613 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10614 // App explictly prefers external. Let policy decide 10615 } else { 10616 // Prefer previous location 10617 if (isExternal(pkg)) { 10618 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10619 } 10620 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10621 } 10622 } 10623 } else { 10624 // Invalid install. Return error code 10625 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10626 } 10627 } 10628 } 10629 // All the special cases have been taken care of. 10630 // Return result based on recommended install location. 10631 if (onSd) { 10632 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10633 } 10634 return pkgLite.recommendedInstallLocation; 10635 } 10636 10637 /* 10638 * Invoke remote method to get package information and install 10639 * location values. Override install location based on default 10640 * policy if needed and then create install arguments based 10641 * on the install location. 10642 */ 10643 public void handleStartCopy() throws RemoteException { 10644 int ret = PackageManager.INSTALL_SUCCEEDED; 10645 10646 // If we're already staged, we've firmly committed to an install location 10647 if (origin.staged) { 10648 if (origin.file != null) { 10649 installFlags |= PackageManager.INSTALL_INTERNAL; 10650 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10651 } else if (origin.cid != null) { 10652 installFlags |= PackageManager.INSTALL_EXTERNAL; 10653 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10654 } else { 10655 throw new IllegalStateException("Invalid stage location"); 10656 } 10657 } 10658 10659 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10660 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10661 PackageInfoLite pkgLite = null; 10662 10663 if (onInt && onSd) { 10664 // Check if both bits are set. 10665 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10666 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10667 } else { 10668 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10669 packageAbiOverride); 10670 10671 /* 10672 * If we have too little free space, try to free cache 10673 * before giving up. 10674 */ 10675 if (!origin.staged && pkgLite.recommendedInstallLocation 10676 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10677 // TODO: focus freeing disk space on the target device 10678 final StorageManager storage = StorageManager.from(mContext); 10679 final long lowThreshold = storage.getStorageLowBytes( 10680 Environment.getDataDirectory()); 10681 10682 final long sizeBytes = mContainerService.calculateInstalledSize( 10683 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10684 10685 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10686 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10687 installFlags, packageAbiOverride); 10688 } 10689 10690 /* 10691 * The cache free must have deleted the file we 10692 * downloaded to install. 10693 * 10694 * TODO: fix the "freeCache" call to not delete 10695 * the file we care about. 10696 */ 10697 if (pkgLite.recommendedInstallLocation 10698 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10699 pkgLite.recommendedInstallLocation 10700 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10701 } 10702 } 10703 } 10704 10705 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10706 int loc = pkgLite.recommendedInstallLocation; 10707 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10708 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10709 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10710 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10711 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10712 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10713 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10714 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10715 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10716 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10717 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10718 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10719 } else { 10720 // Override with defaults if needed. 10721 loc = installLocationPolicy(pkgLite); 10722 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10723 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10724 } else if (!onSd && !onInt) { 10725 // Override install location with flags 10726 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10727 // Set the flag to install on external media. 10728 installFlags |= PackageManager.INSTALL_EXTERNAL; 10729 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10730 } else { 10731 // Make sure the flag for installing on external 10732 // media is unset 10733 installFlags |= PackageManager.INSTALL_INTERNAL; 10734 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10735 } 10736 } 10737 } 10738 } 10739 10740 final InstallArgs args = createInstallArgs(this); 10741 mArgs = args; 10742 10743 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10744 /* 10745 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10746 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10747 */ 10748 int userIdentifier = getUser().getIdentifier(); 10749 if (userIdentifier == UserHandle.USER_ALL 10750 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10751 userIdentifier = UserHandle.USER_OWNER; 10752 } 10753 10754 /* 10755 * Determine if we have any installed package verifiers. If we 10756 * do, then we'll defer to them to verify the packages. 10757 */ 10758 final int requiredUid = mRequiredVerifierPackage == null ? -1 10759 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10760 if (!origin.existing && requiredUid != -1 10761 && isVerificationEnabled(userIdentifier, installFlags)) { 10762 final Intent verification = new Intent( 10763 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10764 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10765 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10766 PACKAGE_MIME_TYPE); 10767 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10768 10769 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10770 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10771 0 /* TODO: Which userId? */); 10772 10773 if (DEBUG_VERIFY) { 10774 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10775 + verification.toString() + " with " + pkgLite.verifiers.length 10776 + " optional verifiers"); 10777 } 10778 10779 final int verificationId = mPendingVerificationToken++; 10780 10781 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10782 10783 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10784 installerPackageName); 10785 10786 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10787 installFlags); 10788 10789 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10790 pkgLite.packageName); 10791 10792 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10793 pkgLite.versionCode); 10794 10795 if (verificationParams != null) { 10796 if (verificationParams.getVerificationURI() != null) { 10797 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10798 verificationParams.getVerificationURI()); 10799 } 10800 if (verificationParams.getOriginatingURI() != null) { 10801 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10802 verificationParams.getOriginatingURI()); 10803 } 10804 if (verificationParams.getReferrer() != null) { 10805 verification.putExtra(Intent.EXTRA_REFERRER, 10806 verificationParams.getReferrer()); 10807 } 10808 if (verificationParams.getOriginatingUid() >= 0) { 10809 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10810 verificationParams.getOriginatingUid()); 10811 } 10812 if (verificationParams.getInstallerUid() >= 0) { 10813 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10814 verificationParams.getInstallerUid()); 10815 } 10816 } 10817 10818 final PackageVerificationState verificationState = new PackageVerificationState( 10819 requiredUid, args); 10820 10821 mPendingVerification.append(verificationId, verificationState); 10822 10823 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10824 receivers, verificationState); 10825 10826 // Apps installed for "all" users use the device owner to verify the app 10827 UserHandle verifierUser = getUser(); 10828 if (verifierUser == UserHandle.ALL) { 10829 verifierUser = UserHandle.OWNER; 10830 } 10831 10832 /* 10833 * If any sufficient verifiers were listed in the package 10834 * manifest, attempt to ask them. 10835 */ 10836 if (sufficientVerifiers != null) { 10837 final int N = sufficientVerifiers.size(); 10838 if (N == 0) { 10839 Slog.i(TAG, "Additional verifiers required, but none installed."); 10840 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10841 } else { 10842 for (int i = 0; i < N; i++) { 10843 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10844 10845 final Intent sufficientIntent = new Intent(verification); 10846 sufficientIntent.setComponent(verifierComponent); 10847 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10848 } 10849 } 10850 } 10851 10852 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10853 mRequiredVerifierPackage, receivers); 10854 if (ret == PackageManager.INSTALL_SUCCEEDED 10855 && mRequiredVerifierPackage != null) { 10856 Trace.asyncTraceBegin( 10857 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 10858 /* 10859 * Send the intent to the required verification agent, 10860 * but only start the verification timeout after the 10861 * target BroadcastReceivers have run. 10862 */ 10863 verification.setComponent(requiredVerifierComponent); 10864 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10865 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10866 new BroadcastReceiver() { 10867 @Override 10868 public void onReceive(Context context, Intent intent) { 10869 final Message msg = mHandler 10870 .obtainMessage(CHECK_PENDING_VERIFICATION); 10871 msg.arg1 = verificationId; 10872 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10873 } 10874 }, null, 0, null, null); 10875 10876 /* 10877 * We don't want the copy to proceed until verification 10878 * succeeds, so null out this field. 10879 */ 10880 mArgs = null; 10881 } 10882 } else { 10883 /* 10884 * No package verification is enabled, so immediately start 10885 * the remote call to initiate copy using temporary file. 10886 */ 10887 ret = args.copyApk(mContainerService, true); 10888 } 10889 } 10890 10891 mRet = ret; 10892 } 10893 10894 @Override 10895 void handleReturnCode() { 10896 // If mArgs is null, then MCS couldn't be reached. When it 10897 // reconnects, it will try again to install. At that point, this 10898 // will succeed. 10899 if (mArgs != null) { 10900 processPendingInstall(mArgs, mRet); 10901 } 10902 } 10903 10904 @Override 10905 void handleServiceError() { 10906 mArgs = createInstallArgs(this); 10907 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10908 } 10909 10910 public boolean isForwardLocked() { 10911 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10912 } 10913 } 10914 10915 /** 10916 * Used during creation of InstallArgs 10917 * 10918 * @param installFlags package installation flags 10919 * @return true if should be installed on external storage 10920 */ 10921 private static boolean installOnExternalAsec(int installFlags) { 10922 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10923 return false; 10924 } 10925 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10926 return true; 10927 } 10928 return false; 10929 } 10930 10931 /** 10932 * Used during creation of InstallArgs 10933 * 10934 * @param installFlags package installation flags 10935 * @return true if should be installed as forward locked 10936 */ 10937 private static boolean installForwardLocked(int installFlags) { 10938 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10939 } 10940 10941 private InstallArgs createInstallArgs(InstallParams params) { 10942 if (params.move != null) { 10943 return new MoveInstallArgs(params); 10944 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10945 return new AsecInstallArgs(params); 10946 } else { 10947 return new FileInstallArgs(params); 10948 } 10949 } 10950 10951 /** 10952 * Create args that describe an existing installed package. Typically used 10953 * when cleaning up old installs, or used as a move source. 10954 */ 10955 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10956 String resourcePath, String[] instructionSets) { 10957 final boolean isInAsec; 10958 if (installOnExternalAsec(installFlags)) { 10959 /* Apps on SD card are always in ASEC containers. */ 10960 isInAsec = true; 10961 } else if (installForwardLocked(installFlags) 10962 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10963 /* 10964 * Forward-locked apps are only in ASEC containers if they're the 10965 * new style 10966 */ 10967 isInAsec = true; 10968 } else { 10969 isInAsec = false; 10970 } 10971 10972 if (isInAsec) { 10973 return new AsecInstallArgs(codePath, instructionSets, 10974 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10975 } else { 10976 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10977 } 10978 } 10979 10980 static abstract class InstallArgs { 10981 /** @see InstallParams#origin */ 10982 final OriginInfo origin; 10983 /** @see InstallParams#move */ 10984 final MoveInfo move; 10985 10986 final IPackageInstallObserver2 observer; 10987 // Always refers to PackageManager flags only 10988 final int installFlags; 10989 final String installerPackageName; 10990 final String volumeUuid; 10991 final ManifestDigest manifestDigest; 10992 final UserHandle user; 10993 final String abiOverride; 10994 final String[] installGrantPermissions; 10995 10996 // The list of instruction sets supported by this app. This is currently 10997 // only used during the rmdex() phase to clean up resources. We can get rid of this 10998 // if we move dex files under the common app path. 10999 /* nullable */ String[] instructionSets; 11000 11001 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11002 int installFlags, String installerPackageName, String volumeUuid, 11003 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11004 String abiOverride, String[] installGrantPermissions) { 11005 this.origin = origin; 11006 this.move = move; 11007 this.installFlags = installFlags; 11008 this.observer = observer; 11009 this.installerPackageName = installerPackageName; 11010 this.volumeUuid = volumeUuid; 11011 this.manifestDigest = manifestDigest; 11012 this.user = user; 11013 this.instructionSets = instructionSets; 11014 this.abiOverride = abiOverride; 11015 this.installGrantPermissions = installGrantPermissions; 11016 } 11017 11018 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11019 abstract int doPreInstall(int status); 11020 11021 /** 11022 * Rename package into final resting place. All paths on the given 11023 * scanned package should be updated to reflect the rename. 11024 */ 11025 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11026 abstract int doPostInstall(int status, int uid); 11027 11028 /** @see PackageSettingBase#codePathString */ 11029 abstract String getCodePath(); 11030 /** @see PackageSettingBase#resourcePathString */ 11031 abstract String getResourcePath(); 11032 11033 // Need installer lock especially for dex file removal. 11034 abstract void cleanUpResourcesLI(); 11035 abstract boolean doPostDeleteLI(boolean delete); 11036 11037 /** 11038 * Called before the source arguments are copied. This is used mostly 11039 * for MoveParams when it needs to read the source file to put it in the 11040 * destination. 11041 */ 11042 int doPreCopy() { 11043 return PackageManager.INSTALL_SUCCEEDED; 11044 } 11045 11046 /** 11047 * Called after the source arguments are copied. This is used mostly for 11048 * MoveParams when it needs to read the source file to put it in the 11049 * destination. 11050 * 11051 * @return 11052 */ 11053 int doPostCopy(int uid) { 11054 return PackageManager.INSTALL_SUCCEEDED; 11055 } 11056 11057 protected boolean isFwdLocked() { 11058 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11059 } 11060 11061 protected boolean isExternalAsec() { 11062 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11063 } 11064 11065 UserHandle getUser() { 11066 return user; 11067 } 11068 } 11069 11070 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11071 if (!allCodePaths.isEmpty()) { 11072 if (instructionSets == null) { 11073 throw new IllegalStateException("instructionSet == null"); 11074 } 11075 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11076 for (String codePath : allCodePaths) { 11077 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11078 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11079 if (retCode < 0) { 11080 Slog.w(TAG, "Couldn't remove dex file for package: " 11081 + " at location " + codePath + ", retcode=" + retCode); 11082 // we don't consider this to be a failure of the core package deletion 11083 } 11084 } 11085 } 11086 } 11087 } 11088 11089 /** 11090 * Logic to handle installation of non-ASEC applications, including copying 11091 * and renaming logic. 11092 */ 11093 class FileInstallArgs extends InstallArgs { 11094 private File codeFile; 11095 private File resourceFile; 11096 11097 // Example topology: 11098 // /data/app/com.example/base.apk 11099 // /data/app/com.example/split_foo.apk 11100 // /data/app/com.example/lib/arm/libfoo.so 11101 // /data/app/com.example/lib/arm64/libfoo.so 11102 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11103 11104 /** New install */ 11105 FileInstallArgs(InstallParams params) { 11106 super(params.origin, params.move, params.observer, params.installFlags, 11107 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11108 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11109 params.grantedRuntimePermissions); 11110 if (isFwdLocked()) { 11111 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11112 } 11113 } 11114 11115 /** Existing install */ 11116 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11117 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11118 null, null); 11119 this.codeFile = (codePath != null) ? new File(codePath) : null; 11120 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11121 } 11122 11123 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11124 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11125 try { 11126 return doCopyApk(imcs, temp); 11127 } finally { 11128 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11129 } 11130 } 11131 11132 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11133 if (origin.staged) { 11134 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11135 codeFile = origin.file; 11136 resourceFile = origin.file; 11137 return PackageManager.INSTALL_SUCCEEDED; 11138 } 11139 11140 try { 11141 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11142 codeFile = tempDir; 11143 resourceFile = tempDir; 11144 } catch (IOException e) { 11145 Slog.w(TAG, "Failed to create copy file: " + e); 11146 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11147 } 11148 11149 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11150 @Override 11151 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11152 if (!FileUtils.isValidExtFilename(name)) { 11153 throw new IllegalArgumentException("Invalid filename: " + name); 11154 } 11155 try { 11156 final File file = new File(codeFile, name); 11157 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11158 O_RDWR | O_CREAT, 0644); 11159 Os.chmod(file.getAbsolutePath(), 0644); 11160 return new ParcelFileDescriptor(fd); 11161 } catch (ErrnoException e) { 11162 throw new RemoteException("Failed to open: " + e.getMessage()); 11163 } 11164 } 11165 }; 11166 11167 int ret = PackageManager.INSTALL_SUCCEEDED; 11168 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11169 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11170 Slog.e(TAG, "Failed to copy package"); 11171 return ret; 11172 } 11173 11174 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11175 NativeLibraryHelper.Handle handle = null; 11176 try { 11177 handle = NativeLibraryHelper.Handle.create(codeFile); 11178 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11179 abiOverride); 11180 } catch (IOException e) { 11181 Slog.e(TAG, "Copying native libraries failed", e); 11182 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11183 } finally { 11184 IoUtils.closeQuietly(handle); 11185 } 11186 11187 return ret; 11188 } 11189 11190 int doPreInstall(int status) { 11191 if (status != PackageManager.INSTALL_SUCCEEDED) { 11192 cleanUp(); 11193 } 11194 return status; 11195 } 11196 11197 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11198 if (status != PackageManager.INSTALL_SUCCEEDED) { 11199 cleanUp(); 11200 return false; 11201 } 11202 11203 final File targetDir = codeFile.getParentFile(); 11204 final File beforeCodeFile = codeFile; 11205 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11206 11207 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11208 try { 11209 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11210 } catch (ErrnoException e) { 11211 Slog.w(TAG, "Failed to rename", e); 11212 return false; 11213 } 11214 11215 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11216 Slog.w(TAG, "Failed to restorecon"); 11217 return false; 11218 } 11219 11220 // Reflect the rename internally 11221 codeFile = afterCodeFile; 11222 resourceFile = afterCodeFile; 11223 11224 // Reflect the rename in scanned details 11225 pkg.codePath = afterCodeFile.getAbsolutePath(); 11226 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11227 pkg.baseCodePath); 11228 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11229 pkg.splitCodePaths); 11230 11231 // Reflect the rename in app info 11232 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11233 pkg.applicationInfo.setCodePath(pkg.codePath); 11234 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11235 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11236 pkg.applicationInfo.setResourcePath(pkg.codePath); 11237 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11238 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11239 11240 return true; 11241 } 11242 11243 int doPostInstall(int status, int uid) { 11244 if (status != PackageManager.INSTALL_SUCCEEDED) { 11245 cleanUp(); 11246 } 11247 return status; 11248 } 11249 11250 @Override 11251 String getCodePath() { 11252 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11253 } 11254 11255 @Override 11256 String getResourcePath() { 11257 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11258 } 11259 11260 private boolean cleanUp() { 11261 if (codeFile == null || !codeFile.exists()) { 11262 return false; 11263 } 11264 11265 if (codeFile.isDirectory()) { 11266 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11267 } else { 11268 codeFile.delete(); 11269 } 11270 11271 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11272 resourceFile.delete(); 11273 } 11274 11275 return true; 11276 } 11277 11278 void cleanUpResourcesLI() { 11279 // Try enumerating all code paths before deleting 11280 List<String> allCodePaths = Collections.EMPTY_LIST; 11281 if (codeFile != null && codeFile.exists()) { 11282 try { 11283 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11284 allCodePaths = pkg.getAllCodePaths(); 11285 } catch (PackageParserException e) { 11286 // Ignored; we tried our best 11287 } 11288 } 11289 11290 cleanUp(); 11291 removeDexFiles(allCodePaths, instructionSets); 11292 } 11293 11294 boolean doPostDeleteLI(boolean delete) { 11295 // XXX err, shouldn't we respect the delete flag? 11296 cleanUpResourcesLI(); 11297 return true; 11298 } 11299 } 11300 11301 private boolean isAsecExternal(String cid) { 11302 final String asecPath = PackageHelper.getSdFilesystem(cid); 11303 return !asecPath.startsWith(mAsecInternalPath); 11304 } 11305 11306 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11307 PackageManagerException { 11308 if (copyRet < 0) { 11309 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11310 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11311 throw new PackageManagerException(copyRet, message); 11312 } 11313 } 11314 } 11315 11316 /** 11317 * Extract the MountService "container ID" from the full code path of an 11318 * .apk. 11319 */ 11320 static String cidFromCodePath(String fullCodePath) { 11321 int eidx = fullCodePath.lastIndexOf("/"); 11322 String subStr1 = fullCodePath.substring(0, eidx); 11323 int sidx = subStr1.lastIndexOf("/"); 11324 return subStr1.substring(sidx+1, eidx); 11325 } 11326 11327 /** 11328 * Logic to handle installation of ASEC applications, including copying and 11329 * renaming logic. 11330 */ 11331 class AsecInstallArgs extends InstallArgs { 11332 static final String RES_FILE_NAME = "pkg.apk"; 11333 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11334 11335 String cid; 11336 String packagePath; 11337 String resourcePath; 11338 11339 /** New install */ 11340 AsecInstallArgs(InstallParams params) { 11341 super(params.origin, params.move, params.observer, params.installFlags, 11342 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11343 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11344 params.grantedRuntimePermissions); 11345 } 11346 11347 /** Existing install */ 11348 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11349 boolean isExternal, boolean isForwardLocked) { 11350 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11351 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11352 instructionSets, null, null); 11353 // Hackily pretend we're still looking at a full code path 11354 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11355 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11356 } 11357 11358 // Extract cid from fullCodePath 11359 int eidx = fullCodePath.lastIndexOf("/"); 11360 String subStr1 = fullCodePath.substring(0, eidx); 11361 int sidx = subStr1.lastIndexOf("/"); 11362 cid = subStr1.substring(sidx+1, eidx); 11363 setMountPath(subStr1); 11364 } 11365 11366 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11367 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11368 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11369 instructionSets, null, null); 11370 this.cid = cid; 11371 setMountPath(PackageHelper.getSdDir(cid)); 11372 } 11373 11374 void createCopyFile() { 11375 cid = mInstallerService.allocateExternalStageCidLegacy(); 11376 } 11377 11378 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11379 if (origin.staged) { 11380 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11381 cid = origin.cid; 11382 setMountPath(PackageHelper.getSdDir(cid)); 11383 return PackageManager.INSTALL_SUCCEEDED; 11384 } 11385 11386 if (temp) { 11387 createCopyFile(); 11388 } else { 11389 /* 11390 * Pre-emptively destroy the container since it's destroyed if 11391 * copying fails due to it existing anyway. 11392 */ 11393 PackageHelper.destroySdDir(cid); 11394 } 11395 11396 final String newMountPath = imcs.copyPackageToContainer( 11397 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11398 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11399 11400 if (newMountPath != null) { 11401 setMountPath(newMountPath); 11402 return PackageManager.INSTALL_SUCCEEDED; 11403 } else { 11404 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11405 } 11406 } 11407 11408 @Override 11409 String getCodePath() { 11410 return packagePath; 11411 } 11412 11413 @Override 11414 String getResourcePath() { 11415 return resourcePath; 11416 } 11417 11418 int doPreInstall(int status) { 11419 if (status != PackageManager.INSTALL_SUCCEEDED) { 11420 // Destroy container 11421 PackageHelper.destroySdDir(cid); 11422 } else { 11423 boolean mounted = PackageHelper.isContainerMounted(cid); 11424 if (!mounted) { 11425 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11426 Process.SYSTEM_UID); 11427 if (newMountPath != null) { 11428 setMountPath(newMountPath); 11429 } else { 11430 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11431 } 11432 } 11433 } 11434 return status; 11435 } 11436 11437 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11438 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11439 String newMountPath = null; 11440 if (PackageHelper.isContainerMounted(cid)) { 11441 // Unmount the container 11442 if (!PackageHelper.unMountSdDir(cid)) { 11443 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11444 return false; 11445 } 11446 } 11447 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11448 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11449 " which might be stale. Will try to clean up."); 11450 // Clean up the stale container and proceed to recreate. 11451 if (!PackageHelper.destroySdDir(newCacheId)) { 11452 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11453 return false; 11454 } 11455 // Successfully cleaned up stale container. Try to rename again. 11456 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11457 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11458 + " inspite of cleaning it up."); 11459 return false; 11460 } 11461 } 11462 if (!PackageHelper.isContainerMounted(newCacheId)) { 11463 Slog.w(TAG, "Mounting container " + newCacheId); 11464 newMountPath = PackageHelper.mountSdDir(newCacheId, 11465 getEncryptKey(), Process.SYSTEM_UID); 11466 } else { 11467 newMountPath = PackageHelper.getSdDir(newCacheId); 11468 } 11469 if (newMountPath == null) { 11470 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11471 return false; 11472 } 11473 Log.i(TAG, "Succesfully renamed " + cid + 11474 " to " + newCacheId + 11475 " at new path: " + newMountPath); 11476 cid = newCacheId; 11477 11478 final File beforeCodeFile = new File(packagePath); 11479 setMountPath(newMountPath); 11480 final File afterCodeFile = new File(packagePath); 11481 11482 // Reflect the rename in scanned details 11483 pkg.codePath = afterCodeFile.getAbsolutePath(); 11484 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11485 pkg.baseCodePath); 11486 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11487 pkg.splitCodePaths); 11488 11489 // Reflect the rename in app info 11490 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11491 pkg.applicationInfo.setCodePath(pkg.codePath); 11492 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11493 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11494 pkg.applicationInfo.setResourcePath(pkg.codePath); 11495 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11496 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11497 11498 return true; 11499 } 11500 11501 private void setMountPath(String mountPath) { 11502 final File mountFile = new File(mountPath); 11503 11504 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11505 if (monolithicFile.exists()) { 11506 packagePath = monolithicFile.getAbsolutePath(); 11507 if (isFwdLocked()) { 11508 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11509 } else { 11510 resourcePath = packagePath; 11511 } 11512 } else { 11513 packagePath = mountFile.getAbsolutePath(); 11514 resourcePath = packagePath; 11515 } 11516 } 11517 11518 int doPostInstall(int status, int uid) { 11519 if (status != PackageManager.INSTALL_SUCCEEDED) { 11520 cleanUp(); 11521 } else { 11522 final int groupOwner; 11523 final String protectedFile; 11524 if (isFwdLocked()) { 11525 groupOwner = UserHandle.getSharedAppGid(uid); 11526 protectedFile = RES_FILE_NAME; 11527 } else { 11528 groupOwner = -1; 11529 protectedFile = null; 11530 } 11531 11532 if (uid < Process.FIRST_APPLICATION_UID 11533 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11534 Slog.e(TAG, "Failed to finalize " + cid); 11535 PackageHelper.destroySdDir(cid); 11536 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11537 } 11538 11539 boolean mounted = PackageHelper.isContainerMounted(cid); 11540 if (!mounted) { 11541 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11542 } 11543 } 11544 return status; 11545 } 11546 11547 private void cleanUp() { 11548 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11549 11550 // Destroy secure container 11551 PackageHelper.destroySdDir(cid); 11552 } 11553 11554 private List<String> getAllCodePaths() { 11555 final File codeFile = new File(getCodePath()); 11556 if (codeFile != null && codeFile.exists()) { 11557 try { 11558 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11559 return pkg.getAllCodePaths(); 11560 } catch (PackageParserException e) { 11561 // Ignored; we tried our best 11562 } 11563 } 11564 return Collections.EMPTY_LIST; 11565 } 11566 11567 void cleanUpResourcesLI() { 11568 // Enumerate all code paths before deleting 11569 cleanUpResourcesLI(getAllCodePaths()); 11570 } 11571 11572 private void cleanUpResourcesLI(List<String> allCodePaths) { 11573 cleanUp(); 11574 removeDexFiles(allCodePaths, instructionSets); 11575 } 11576 11577 String getPackageName() { 11578 return getAsecPackageName(cid); 11579 } 11580 11581 boolean doPostDeleteLI(boolean delete) { 11582 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11583 final List<String> allCodePaths = getAllCodePaths(); 11584 boolean mounted = PackageHelper.isContainerMounted(cid); 11585 if (mounted) { 11586 // Unmount first 11587 if (PackageHelper.unMountSdDir(cid)) { 11588 mounted = false; 11589 } 11590 } 11591 if (!mounted && delete) { 11592 cleanUpResourcesLI(allCodePaths); 11593 } 11594 return !mounted; 11595 } 11596 11597 @Override 11598 int doPreCopy() { 11599 if (isFwdLocked()) { 11600 if (!PackageHelper.fixSdPermissions(cid, 11601 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11602 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11603 } 11604 } 11605 11606 return PackageManager.INSTALL_SUCCEEDED; 11607 } 11608 11609 @Override 11610 int doPostCopy(int uid) { 11611 if (isFwdLocked()) { 11612 if (uid < Process.FIRST_APPLICATION_UID 11613 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11614 RES_FILE_NAME)) { 11615 Slog.e(TAG, "Failed to finalize " + cid); 11616 PackageHelper.destroySdDir(cid); 11617 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11618 } 11619 } 11620 11621 return PackageManager.INSTALL_SUCCEEDED; 11622 } 11623 } 11624 11625 /** 11626 * Logic to handle movement of existing installed applications. 11627 */ 11628 class MoveInstallArgs extends InstallArgs { 11629 private File codeFile; 11630 private File resourceFile; 11631 11632 /** New install */ 11633 MoveInstallArgs(InstallParams params) { 11634 super(params.origin, params.move, params.observer, params.installFlags, 11635 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11636 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11637 params.grantedRuntimePermissions); 11638 } 11639 11640 int copyApk(IMediaContainerService imcs, boolean temp) { 11641 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11642 + move.fromUuid + " to " + move.toUuid); 11643 synchronized (mInstaller) { 11644 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11645 move.dataAppName, move.appId, move.seinfo) != 0) { 11646 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11647 } 11648 } 11649 11650 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11651 resourceFile = codeFile; 11652 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11653 11654 return PackageManager.INSTALL_SUCCEEDED; 11655 } 11656 11657 int doPreInstall(int status) { 11658 if (status != PackageManager.INSTALL_SUCCEEDED) { 11659 cleanUp(move.toUuid); 11660 } 11661 return status; 11662 } 11663 11664 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11665 if (status != PackageManager.INSTALL_SUCCEEDED) { 11666 cleanUp(move.toUuid); 11667 return false; 11668 } 11669 11670 // Reflect the move in app info 11671 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11672 pkg.applicationInfo.setCodePath(pkg.codePath); 11673 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11674 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11675 pkg.applicationInfo.setResourcePath(pkg.codePath); 11676 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11677 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11678 11679 return true; 11680 } 11681 11682 int doPostInstall(int status, int uid) { 11683 if (status == PackageManager.INSTALL_SUCCEEDED) { 11684 cleanUp(move.fromUuid); 11685 } else { 11686 cleanUp(move.toUuid); 11687 } 11688 return status; 11689 } 11690 11691 @Override 11692 String getCodePath() { 11693 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11694 } 11695 11696 @Override 11697 String getResourcePath() { 11698 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11699 } 11700 11701 private boolean cleanUp(String volumeUuid) { 11702 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11703 move.dataAppName); 11704 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11705 synchronized (mInstallLock) { 11706 // Clean up both app data and code 11707 removeDataDirsLI(volumeUuid, move.packageName); 11708 if (codeFile.isDirectory()) { 11709 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11710 } else { 11711 codeFile.delete(); 11712 } 11713 } 11714 return true; 11715 } 11716 11717 void cleanUpResourcesLI() { 11718 throw new UnsupportedOperationException(); 11719 } 11720 11721 boolean doPostDeleteLI(boolean delete) { 11722 throw new UnsupportedOperationException(); 11723 } 11724 } 11725 11726 static String getAsecPackageName(String packageCid) { 11727 int idx = packageCid.lastIndexOf("-"); 11728 if (idx == -1) { 11729 return packageCid; 11730 } 11731 return packageCid.substring(0, idx); 11732 } 11733 11734 // Utility method used to create code paths based on package name and available index. 11735 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11736 String idxStr = ""; 11737 int idx = 1; 11738 // Fall back to default value of idx=1 if prefix is not 11739 // part of oldCodePath 11740 if (oldCodePath != null) { 11741 String subStr = oldCodePath; 11742 // Drop the suffix right away 11743 if (suffix != null && subStr.endsWith(suffix)) { 11744 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11745 } 11746 // If oldCodePath already contains prefix find out the 11747 // ending index to either increment or decrement. 11748 int sidx = subStr.lastIndexOf(prefix); 11749 if (sidx != -1) { 11750 subStr = subStr.substring(sidx + prefix.length()); 11751 if (subStr != null) { 11752 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11753 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11754 } 11755 try { 11756 idx = Integer.parseInt(subStr); 11757 if (idx <= 1) { 11758 idx++; 11759 } else { 11760 idx--; 11761 } 11762 } catch(NumberFormatException e) { 11763 } 11764 } 11765 } 11766 } 11767 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11768 return prefix + idxStr; 11769 } 11770 11771 private File getNextCodePath(File targetDir, String packageName) { 11772 int suffix = 1; 11773 File result; 11774 do { 11775 result = new File(targetDir, packageName + "-" + suffix); 11776 suffix++; 11777 } while (result.exists()); 11778 return result; 11779 } 11780 11781 // Utility method that returns the relative package path with respect 11782 // to the installation directory. Like say for /data/data/com.test-1.apk 11783 // string com.test-1 is returned. 11784 static String deriveCodePathName(String codePath) { 11785 if (codePath == null) { 11786 return null; 11787 } 11788 final File codeFile = new File(codePath); 11789 final String name = codeFile.getName(); 11790 if (codeFile.isDirectory()) { 11791 return name; 11792 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11793 final int lastDot = name.lastIndexOf('.'); 11794 return name.substring(0, lastDot); 11795 } else { 11796 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11797 return null; 11798 } 11799 } 11800 11801 class PackageInstalledInfo { 11802 String name; 11803 int uid; 11804 // The set of users that originally had this package installed. 11805 int[] origUsers; 11806 // The set of users that now have this package installed. 11807 int[] newUsers; 11808 PackageParser.Package pkg; 11809 int returnCode; 11810 String returnMsg; 11811 PackageRemovedInfo removedInfo; 11812 11813 public void setError(int code, String msg) { 11814 returnCode = code; 11815 returnMsg = msg; 11816 Slog.w(TAG, msg); 11817 } 11818 11819 public void setError(String msg, PackageParserException e) { 11820 returnCode = e.error; 11821 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11822 Slog.w(TAG, msg, e); 11823 } 11824 11825 public void setError(String msg, PackageManagerException e) { 11826 returnCode = e.error; 11827 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11828 Slog.w(TAG, msg, e); 11829 } 11830 11831 // In some error cases we want to convey more info back to the observer 11832 String origPackage; 11833 String origPermission; 11834 } 11835 11836 /* 11837 * Install a non-existing package. 11838 */ 11839 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11840 UserHandle user, String installerPackageName, String volumeUuid, 11841 PackageInstalledInfo res) { 11842 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11843 11844 // Remember this for later, in case we need to rollback this install 11845 String pkgName = pkg.packageName; 11846 11847 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11848 // TODO: b/23350563 11849 final boolean dataDirExists = Environment 11850 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11851 11852 synchronized(mPackages) { 11853 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11854 // A package with the same name is already installed, though 11855 // it has been renamed to an older name. The package we 11856 // are trying to install should be installed as an update to 11857 // the existing one, but that has not been requested, so bail. 11858 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11859 + " without first uninstalling package running as " 11860 + mSettings.mRenamedPackages.get(pkgName)); 11861 return; 11862 } 11863 if (mPackages.containsKey(pkgName)) { 11864 // Don't allow installation over an existing package with the same name. 11865 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11866 + " without first uninstalling."); 11867 return; 11868 } 11869 } 11870 11871 try { 11872 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11873 System.currentTimeMillis(), user); 11874 11875 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11876 // delete the partially installed application. the data directory will have to be 11877 // restored if it was already existing 11878 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11879 // remove package from internal structures. Note that we want deletePackageX to 11880 // delete the package data and cache directories that it created in 11881 // scanPackageLocked, unless those directories existed before we even tried to 11882 // install. 11883 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11884 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11885 res.removedInfo, true); 11886 } 11887 11888 } catch (PackageManagerException e) { 11889 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11890 } 11891 11892 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11893 } 11894 11895 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11896 // Can't rotate keys during boot or if sharedUser. 11897 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11898 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11899 return false; 11900 } 11901 // app is using upgradeKeySets; make sure all are valid 11902 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11903 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11904 for (int i = 0; i < upgradeKeySets.length; i++) { 11905 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11906 Slog.wtf(TAG, "Package " 11907 + (oldPs.name != null ? oldPs.name : "<null>") 11908 + " contains upgrade-key-set reference to unknown key-set: " 11909 + upgradeKeySets[i] 11910 + " reverting to signatures check."); 11911 return false; 11912 } 11913 } 11914 return true; 11915 } 11916 11917 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11918 // Upgrade keysets are being used. Determine if new package has a superset of the 11919 // required keys. 11920 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11921 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11922 for (int i = 0; i < upgradeKeySets.length; i++) { 11923 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11924 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11925 return true; 11926 } 11927 } 11928 return false; 11929 } 11930 11931 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11932 UserHandle user, String installerPackageName, String volumeUuid, 11933 PackageInstalledInfo res) { 11934 final PackageParser.Package oldPackage; 11935 final String pkgName = pkg.packageName; 11936 final int[] allUsers; 11937 final boolean[] perUserInstalled; 11938 11939 // First find the old package info and check signatures 11940 synchronized(mPackages) { 11941 oldPackage = mPackages.get(pkgName); 11942 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11943 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11944 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11945 if(!checkUpgradeKeySetLP(ps, pkg)) { 11946 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11947 "New package not signed by keys specified by upgrade-keysets: " 11948 + pkgName); 11949 return; 11950 } 11951 } else { 11952 // default to original signature matching 11953 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11954 != PackageManager.SIGNATURE_MATCH) { 11955 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11956 "New package has a different signature: " + pkgName); 11957 return; 11958 } 11959 } 11960 11961 // In case of rollback, remember per-user/profile install state 11962 allUsers = sUserManager.getUserIds(); 11963 perUserInstalled = new boolean[allUsers.length]; 11964 for (int i = 0; i < allUsers.length; i++) { 11965 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11966 } 11967 } 11968 11969 boolean sysPkg = (isSystemApp(oldPackage)); 11970 if (sysPkg) { 11971 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11972 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11973 } else { 11974 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11975 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11976 } 11977 } 11978 11979 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11980 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11981 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11982 String volumeUuid, PackageInstalledInfo res) { 11983 String pkgName = deletedPackage.packageName; 11984 boolean deletedPkg = true; 11985 boolean updatedSettings = false; 11986 11987 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11988 + deletedPackage); 11989 long origUpdateTime; 11990 if (pkg.mExtras != null) { 11991 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11992 } else { 11993 origUpdateTime = 0; 11994 } 11995 11996 // First delete the existing package while retaining the data directory 11997 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11998 res.removedInfo, true)) { 11999 // If the existing package wasn't successfully deleted 12000 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12001 deletedPkg = false; 12002 } else { 12003 // Successfully deleted the old package; proceed with replace. 12004 12005 // If deleted package lived in a container, give users a chance to 12006 // relinquish resources before killing. 12007 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12008 if (DEBUG_INSTALL) { 12009 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12010 } 12011 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12012 final ArrayList<String> pkgList = new ArrayList<String>(1); 12013 pkgList.add(deletedPackage.applicationInfo.packageName); 12014 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12015 } 12016 12017 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12018 try { 12019 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12020 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12021 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12022 perUserInstalled, res, user); 12023 updatedSettings = true; 12024 } catch (PackageManagerException e) { 12025 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12026 } 12027 } 12028 12029 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12030 // remove package from internal structures. Note that we want deletePackageX to 12031 // delete the package data and cache directories that it created in 12032 // scanPackageLocked, unless those directories existed before we even tried to 12033 // install. 12034 if(updatedSettings) { 12035 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12036 deletePackageLI( 12037 pkgName, null, true, allUsers, perUserInstalled, 12038 PackageManager.DELETE_KEEP_DATA, 12039 res.removedInfo, true); 12040 } 12041 // Since we failed to install the new package we need to restore the old 12042 // package that we deleted. 12043 if (deletedPkg) { 12044 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12045 File restoreFile = new File(deletedPackage.codePath); 12046 // Parse old package 12047 boolean oldExternal = isExternal(deletedPackage); 12048 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12049 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12050 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12051 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12052 try { 12053 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 12054 } catch (PackageManagerException e) { 12055 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12056 + e.getMessage()); 12057 return; 12058 } 12059 // Restore of old package succeeded. Update permissions. 12060 // writer 12061 synchronized (mPackages) { 12062 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12063 UPDATE_PERMISSIONS_ALL); 12064 // can downgrade to reader 12065 mSettings.writeLPr(); 12066 } 12067 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12068 } 12069 } 12070 } 12071 12072 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12073 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12074 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12075 String volumeUuid, PackageInstalledInfo res) { 12076 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12077 + ", old=" + deletedPackage); 12078 boolean disabledSystem = false; 12079 boolean updatedSettings = false; 12080 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12081 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12082 != 0) { 12083 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12084 } 12085 String packageName = deletedPackage.packageName; 12086 if (packageName == null) { 12087 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12088 "Attempt to delete null packageName."); 12089 return; 12090 } 12091 PackageParser.Package oldPkg; 12092 PackageSetting oldPkgSetting; 12093 // reader 12094 synchronized (mPackages) { 12095 oldPkg = mPackages.get(packageName); 12096 oldPkgSetting = mSettings.mPackages.get(packageName); 12097 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12098 (oldPkgSetting == null)) { 12099 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12100 "Couldn't find package:" + packageName + " information"); 12101 return; 12102 } 12103 } 12104 12105 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12106 12107 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12108 res.removedInfo.removedPackage = packageName; 12109 // Remove existing system package 12110 removePackageLI(oldPkgSetting, true); 12111 // writer 12112 synchronized (mPackages) { 12113 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12114 if (!disabledSystem && deletedPackage != null) { 12115 // We didn't need to disable the .apk as a current system package, 12116 // which means we are replacing another update that is already 12117 // installed. We need to make sure to delete the older one's .apk. 12118 res.removedInfo.args = createInstallArgsForExisting(0, 12119 deletedPackage.applicationInfo.getCodePath(), 12120 deletedPackage.applicationInfo.getResourcePath(), 12121 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12122 } else { 12123 res.removedInfo.args = null; 12124 } 12125 } 12126 12127 // Successfully disabled the old package. Now proceed with re-installation 12128 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12129 12130 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12131 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12132 12133 PackageParser.Package newPackage = null; 12134 try { 12135 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12136 if (newPackage.mExtras != null) { 12137 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12138 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12139 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12140 12141 // is the update attempting to change shared user? that isn't going to work... 12142 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12143 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12144 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12145 + " to " + newPkgSetting.sharedUser); 12146 updatedSettings = true; 12147 } 12148 } 12149 12150 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12151 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12152 perUserInstalled, res, user); 12153 updatedSettings = true; 12154 } 12155 12156 } catch (PackageManagerException e) { 12157 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12158 } 12159 12160 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12161 // Re installation failed. Restore old information 12162 // Remove new pkg information 12163 if (newPackage != null) { 12164 removeInstalledPackageLI(newPackage, true); 12165 } 12166 // Add back the old system package 12167 try { 12168 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12169 } catch (PackageManagerException e) { 12170 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12171 } 12172 // Restore the old system information in Settings 12173 synchronized (mPackages) { 12174 if (disabledSystem) { 12175 mSettings.enableSystemPackageLPw(packageName); 12176 } 12177 if (updatedSettings) { 12178 mSettings.setInstallerPackageName(packageName, 12179 oldPkgSetting.installerPackageName); 12180 } 12181 mSettings.writeLPr(); 12182 } 12183 } 12184 } 12185 12186 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12187 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12188 UserHandle user) { 12189 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12190 12191 String pkgName = newPackage.packageName; 12192 synchronized (mPackages) { 12193 //write settings. the installStatus will be incomplete at this stage. 12194 //note that the new package setting would have already been 12195 //added to mPackages. It hasn't been persisted yet. 12196 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12197 mSettings.writeLPr(); 12198 } 12199 12200 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12201 synchronized (mPackages) { 12202 updatePermissionsLPw(newPackage.packageName, newPackage, 12203 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12204 ? UPDATE_PERMISSIONS_ALL : 0)); 12205 // For system-bundled packages, we assume that installing an upgraded version 12206 // of the package implies that the user actually wants to run that new code, 12207 // so we enable the package. 12208 PackageSetting ps = mSettings.mPackages.get(pkgName); 12209 if (ps != null) { 12210 if (isSystemApp(newPackage)) { 12211 // NB: implicit assumption that system package upgrades apply to all users 12212 if (DEBUG_INSTALL) { 12213 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12214 } 12215 if (res.origUsers != null) { 12216 for (int userHandle : res.origUsers) { 12217 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12218 userHandle, installerPackageName); 12219 } 12220 } 12221 // Also convey the prior install/uninstall state 12222 if (allUsers != null && perUserInstalled != null) { 12223 for (int i = 0; i < allUsers.length; i++) { 12224 if (DEBUG_INSTALL) { 12225 Slog.d(TAG, " user " + allUsers[i] 12226 + " => " + perUserInstalled[i]); 12227 } 12228 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12229 } 12230 // these install state changes will be persisted in the 12231 // upcoming call to mSettings.writeLPr(). 12232 } 12233 } 12234 // It's implied that when a user requests installation, they want the app to be 12235 // installed and enabled. 12236 int userId = user.getIdentifier(); 12237 if (userId != UserHandle.USER_ALL) { 12238 ps.setInstalled(true, userId); 12239 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12240 } 12241 } 12242 res.name = pkgName; 12243 res.uid = newPackage.applicationInfo.uid; 12244 res.pkg = newPackage; 12245 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12246 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12247 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12248 //to update install status 12249 mSettings.writeLPr(); 12250 } 12251 12252 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12253 } 12254 12255 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12256 try { 12257 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12258 installPackageLI(args, res); 12259 } finally { 12260 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12261 } 12262 } 12263 12264 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12265 final int installFlags = args.installFlags; 12266 final String installerPackageName = args.installerPackageName; 12267 final String volumeUuid = args.volumeUuid; 12268 final File tmpPackageFile = new File(args.getCodePath()); 12269 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12270 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12271 || (args.volumeUuid != null)); 12272 boolean replace = false; 12273 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12274 if (args.move != null) { 12275 // moving a complete application; perfom an initial scan on the new install location 12276 scanFlags |= SCAN_INITIAL; 12277 } 12278 // Result object to be returned 12279 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12280 12281 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12282 12283 // Retrieve PackageSettings and parse package 12284 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12285 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12286 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12287 PackageParser pp = new PackageParser(); 12288 pp.setSeparateProcesses(mSeparateProcesses); 12289 pp.setDisplayMetrics(mMetrics); 12290 12291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12292 final PackageParser.Package pkg; 12293 try { 12294 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12295 } catch (PackageParserException e) { 12296 res.setError("Failed parse during installPackageLI", e); 12297 return; 12298 } finally { 12299 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12300 } 12301 12302 // Mark that we have an install time CPU ABI override. 12303 pkg.cpuAbiOverride = args.abiOverride; 12304 12305 String pkgName = res.name = pkg.packageName; 12306 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12307 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12308 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12309 return; 12310 } 12311 } 12312 12313 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12314 try { 12315 pp.collectCertificates(pkg, parseFlags); 12316 pp.collectManifestDigest(pkg); 12317 } catch (PackageParserException e) { 12318 res.setError("Failed collect during installPackageLI", e); 12319 return; 12320 } finally { 12321 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12322 } 12323 12324 /* If the installer passed in a manifest digest, compare it now. */ 12325 if (args.manifestDigest != null) { 12326 if (DEBUG_INSTALL) { 12327 final String parsedManifest = pkg.manifestDigest == null ? "null" 12328 : pkg.manifestDigest.toString(); 12329 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12330 + parsedManifest); 12331 } 12332 12333 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12334 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12335 return; 12336 } 12337 } else if (DEBUG_INSTALL) { 12338 final String parsedManifest = pkg.manifestDigest == null 12339 ? "null" : pkg.manifestDigest.toString(); 12340 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12341 } 12342 12343 // Get rid of all references to package scan path via parser. 12344 pp = null; 12345 String oldCodePath = null; 12346 boolean systemApp = false; 12347 synchronized (mPackages) { 12348 // Check if installing already existing package 12349 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12350 String oldName = mSettings.mRenamedPackages.get(pkgName); 12351 if (pkg.mOriginalPackages != null 12352 && pkg.mOriginalPackages.contains(oldName) 12353 && mPackages.containsKey(oldName)) { 12354 // This package is derived from an original package, 12355 // and this device has been updating from that original 12356 // name. We must continue using the original name, so 12357 // rename the new package here. 12358 pkg.setPackageName(oldName); 12359 pkgName = pkg.packageName; 12360 replace = true; 12361 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12362 + oldName + " pkgName=" + pkgName); 12363 } else if (mPackages.containsKey(pkgName)) { 12364 // This package, under its official name, already exists 12365 // on the device; we should replace it. 12366 replace = true; 12367 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12368 } 12369 12370 // Prevent apps opting out from runtime permissions 12371 if (replace) { 12372 PackageParser.Package oldPackage = mPackages.get(pkgName); 12373 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12374 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12375 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12376 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12377 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12378 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12379 + " doesn't support runtime permissions but the old" 12380 + " target SDK " + oldTargetSdk + " does."); 12381 return; 12382 } 12383 } 12384 } 12385 12386 PackageSetting ps = mSettings.mPackages.get(pkgName); 12387 if (ps != null) { 12388 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12389 12390 // Quick sanity check that we're signed correctly if updating; 12391 // we'll check this again later when scanning, but we want to 12392 // bail early here before tripping over redefined permissions. 12393 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12394 if (!checkUpgradeKeySetLP(ps, pkg)) { 12395 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12396 + pkg.packageName + " upgrade keys do not match the " 12397 + "previously installed version"); 12398 return; 12399 } 12400 } else { 12401 try { 12402 verifySignaturesLP(ps, pkg); 12403 } catch (PackageManagerException e) { 12404 res.setError(e.error, e.getMessage()); 12405 return; 12406 } 12407 } 12408 12409 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12410 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12411 systemApp = (ps.pkg.applicationInfo.flags & 12412 ApplicationInfo.FLAG_SYSTEM) != 0; 12413 } 12414 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12415 } 12416 12417 // Check whether the newly-scanned package wants to define an already-defined perm 12418 int N = pkg.permissions.size(); 12419 for (int i = N-1; i >= 0; i--) { 12420 PackageParser.Permission perm = pkg.permissions.get(i); 12421 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12422 if (bp != null) { 12423 // If the defining package is signed with our cert, it's okay. This 12424 // also includes the "updating the same package" case, of course. 12425 // "updating same package" could also involve key-rotation. 12426 final boolean sigsOk; 12427 if (bp.sourcePackage.equals(pkg.packageName) 12428 && (bp.packageSetting instanceof PackageSetting) 12429 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12430 scanFlags))) { 12431 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12432 } else { 12433 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12434 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12435 } 12436 if (!sigsOk) { 12437 // If the owning package is the system itself, we log but allow 12438 // install to proceed; we fail the install on all other permission 12439 // redefinitions. 12440 if (!bp.sourcePackage.equals("android")) { 12441 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12442 + pkg.packageName + " attempting to redeclare permission " 12443 + perm.info.name + " already owned by " + bp.sourcePackage); 12444 res.origPermission = perm.info.name; 12445 res.origPackage = bp.sourcePackage; 12446 return; 12447 } else { 12448 Slog.w(TAG, "Package " + pkg.packageName 12449 + " attempting to redeclare system permission " 12450 + perm.info.name + "; ignoring new declaration"); 12451 pkg.permissions.remove(i); 12452 } 12453 } 12454 } 12455 } 12456 12457 } 12458 12459 if (systemApp && onExternal) { 12460 // Disable updates to system apps on sdcard 12461 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12462 "Cannot install updates to system apps on sdcard"); 12463 return; 12464 } 12465 12466 if (args.move != null) { 12467 // We did an in-place move, so dex is ready to roll 12468 scanFlags |= SCAN_NO_DEX; 12469 scanFlags |= SCAN_MOVE; 12470 12471 synchronized (mPackages) { 12472 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12473 if (ps == null) { 12474 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12475 "Missing settings for moved package " + pkgName); 12476 } 12477 12478 // We moved the entire application as-is, so bring over the 12479 // previously derived ABI information. 12480 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12481 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12482 } 12483 12484 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12485 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12486 scanFlags |= SCAN_NO_DEX; 12487 12488 try { 12489 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12490 true /* extract libs */); 12491 } catch (PackageManagerException pme) { 12492 Slog.e(TAG, "Error deriving application ABI", pme); 12493 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12494 return; 12495 } 12496 12497 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12498 int result = mPackageDexOptimizer 12499 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12500 false /* defer */, false /* inclDependencies */); 12501 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12502 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12503 return; 12504 } 12505 } 12506 12507 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12508 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12509 return; 12510 } 12511 12512 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12513 12514 if (replace) { 12515 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12516 installerPackageName, volumeUuid, res); 12517 } else { 12518 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12519 args.user, installerPackageName, volumeUuid, res); 12520 } 12521 synchronized (mPackages) { 12522 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12523 if (ps != null) { 12524 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12525 } 12526 } 12527 } 12528 12529 private void startIntentFilterVerifications(int userId, boolean replacing, 12530 PackageParser.Package pkg) { 12531 if (mIntentFilterVerifierComponent == null) { 12532 Slog.w(TAG, "No IntentFilter verification will not be done as " 12533 + "there is no IntentFilterVerifier available!"); 12534 return; 12535 } 12536 12537 final int verifierUid = getPackageUid( 12538 mIntentFilterVerifierComponent.getPackageName(), 12539 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12540 12541 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12542 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12543 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12544 mHandler.sendMessage(msg); 12545 } 12546 12547 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12548 PackageParser.Package pkg) { 12549 int size = pkg.activities.size(); 12550 if (size == 0) { 12551 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12552 "No activity, so no need to verify any IntentFilter!"); 12553 return; 12554 } 12555 12556 final boolean hasDomainURLs = hasDomainURLs(pkg); 12557 if (!hasDomainURLs) { 12558 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12559 "No domain URLs, so no need to verify any IntentFilter!"); 12560 return; 12561 } 12562 12563 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12564 + " if any IntentFilter from the " + size 12565 + " Activities needs verification ..."); 12566 12567 int count = 0; 12568 final String packageName = pkg.packageName; 12569 12570 synchronized (mPackages) { 12571 // If this is a new install and we see that we've already run verification for this 12572 // package, we have nothing to do: it means the state was restored from backup. 12573 if (!replacing) { 12574 IntentFilterVerificationInfo ivi = 12575 mSettings.getIntentFilterVerificationLPr(packageName); 12576 if (ivi != null) { 12577 if (DEBUG_DOMAIN_VERIFICATION) { 12578 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12579 + ivi.getStatusString()); 12580 } 12581 return; 12582 } 12583 } 12584 12585 // If any filters need to be verified, then all need to be. 12586 boolean needToVerify = false; 12587 for (PackageParser.Activity a : pkg.activities) { 12588 for (ActivityIntentInfo filter : a.intents) { 12589 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12590 if (DEBUG_DOMAIN_VERIFICATION) { 12591 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12592 } 12593 needToVerify = true; 12594 break; 12595 } 12596 } 12597 } 12598 12599 if (needToVerify) { 12600 final int verificationId = mIntentFilterVerificationToken++; 12601 for (PackageParser.Activity a : pkg.activities) { 12602 for (ActivityIntentInfo filter : a.intents) { 12603 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12604 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12605 "Verification needed for IntentFilter:" + filter.toString()); 12606 mIntentFilterVerifier.addOneIntentFilterVerification( 12607 verifierUid, userId, verificationId, filter, packageName); 12608 count++; 12609 } 12610 } 12611 } 12612 } 12613 } 12614 12615 if (count > 0) { 12616 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12617 + " IntentFilter verification" + (count > 1 ? "s" : "") 12618 + " for userId:" + userId); 12619 mIntentFilterVerifier.startVerifications(userId); 12620 } else { 12621 if (DEBUG_DOMAIN_VERIFICATION) { 12622 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12623 } 12624 } 12625 } 12626 12627 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12628 final ComponentName cn = filter.activity.getComponentName(); 12629 final String packageName = cn.getPackageName(); 12630 12631 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12632 packageName); 12633 if (ivi == null) { 12634 return true; 12635 } 12636 int status = ivi.getStatus(); 12637 switch (status) { 12638 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12639 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12640 return true; 12641 12642 default: 12643 // Nothing to do 12644 return false; 12645 } 12646 } 12647 12648 private static boolean isMultiArch(PackageSetting ps) { 12649 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12650 } 12651 12652 private static boolean isMultiArch(ApplicationInfo info) { 12653 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12654 } 12655 12656 private static boolean isExternal(PackageParser.Package pkg) { 12657 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12658 } 12659 12660 private static boolean isExternal(PackageSetting ps) { 12661 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12662 } 12663 12664 private static boolean isExternal(ApplicationInfo info) { 12665 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12666 } 12667 12668 private static boolean isSystemApp(PackageParser.Package pkg) { 12669 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12670 } 12671 12672 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12673 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12674 } 12675 12676 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12677 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12678 } 12679 12680 private static boolean isSystemApp(PackageSetting ps) { 12681 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12682 } 12683 12684 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12685 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12686 } 12687 12688 private int packageFlagsToInstallFlags(PackageSetting ps) { 12689 int installFlags = 0; 12690 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12691 // This existing package was an external ASEC install when we have 12692 // the external flag without a UUID 12693 installFlags |= PackageManager.INSTALL_EXTERNAL; 12694 } 12695 if (ps.isForwardLocked()) { 12696 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12697 } 12698 return installFlags; 12699 } 12700 12701 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12702 if (isExternal(pkg)) { 12703 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12704 return mSettings.getExternalVersion(); 12705 } else { 12706 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12707 } 12708 } else { 12709 return mSettings.getInternalVersion(); 12710 } 12711 } 12712 12713 private void deleteTempPackageFiles() { 12714 final FilenameFilter filter = new FilenameFilter() { 12715 public boolean accept(File dir, String name) { 12716 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12717 } 12718 }; 12719 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12720 file.delete(); 12721 } 12722 } 12723 12724 @Override 12725 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12726 int flags) { 12727 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12728 flags); 12729 } 12730 12731 @Override 12732 public void deletePackage(final String packageName, 12733 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12734 mContext.enforceCallingOrSelfPermission( 12735 android.Manifest.permission.DELETE_PACKAGES, null); 12736 Preconditions.checkNotNull(packageName); 12737 Preconditions.checkNotNull(observer); 12738 final int uid = Binder.getCallingUid(); 12739 if (UserHandle.getUserId(uid) != userId) { 12740 mContext.enforceCallingPermission( 12741 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12742 "deletePackage for user " + userId); 12743 } 12744 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12745 try { 12746 observer.onPackageDeleted(packageName, 12747 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12748 } catch (RemoteException re) { 12749 } 12750 return; 12751 } 12752 12753 boolean uninstallBlocked = false; 12754 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12755 int[] users = sUserManager.getUserIds(); 12756 for (int i = 0; i < users.length; ++i) { 12757 if (getBlockUninstallForUser(packageName, users[i])) { 12758 uninstallBlocked = true; 12759 break; 12760 } 12761 } 12762 } else { 12763 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12764 } 12765 if (uninstallBlocked) { 12766 try { 12767 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12768 null); 12769 } catch (RemoteException re) { 12770 } 12771 return; 12772 } 12773 12774 if (DEBUG_REMOVE) { 12775 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12776 } 12777 // Queue up an async operation since the package deletion may take a little while. 12778 mHandler.post(new Runnable() { 12779 public void run() { 12780 mHandler.removeCallbacks(this); 12781 final int returnCode = deletePackageX(packageName, userId, flags); 12782 if (observer != null) { 12783 try { 12784 observer.onPackageDeleted(packageName, returnCode, null); 12785 } catch (RemoteException e) { 12786 Log.i(TAG, "Observer no longer exists."); 12787 } //end catch 12788 } //end if 12789 } //end run 12790 }); 12791 } 12792 12793 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12794 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12795 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12796 try { 12797 if (dpm != null) { 12798 if (dpm.isDeviceOwner(packageName)) { 12799 return true; 12800 } 12801 int[] users; 12802 if (userId == UserHandle.USER_ALL) { 12803 users = sUserManager.getUserIds(); 12804 } else { 12805 users = new int[]{userId}; 12806 } 12807 for (int i = 0; i < users.length; ++i) { 12808 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12809 return true; 12810 } 12811 } 12812 } 12813 } catch (RemoteException e) { 12814 } 12815 return false; 12816 } 12817 12818 /** 12819 * This method is an internal method that could be get invoked either 12820 * to delete an installed package or to clean up a failed installation. 12821 * After deleting an installed package, a broadcast is sent to notify any 12822 * listeners that the package has been installed. For cleaning up a failed 12823 * installation, the broadcast is not necessary since the package's 12824 * installation wouldn't have sent the initial broadcast either 12825 * The key steps in deleting a package are 12826 * deleting the package information in internal structures like mPackages, 12827 * deleting the packages base directories through installd 12828 * updating mSettings to reflect current status 12829 * persisting settings for later use 12830 * sending a broadcast if necessary 12831 */ 12832 private int deletePackageX(String packageName, int userId, int flags) { 12833 final PackageRemovedInfo info = new PackageRemovedInfo(); 12834 final boolean res; 12835 12836 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12837 ? UserHandle.ALL : new UserHandle(userId); 12838 12839 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12840 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12841 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12842 } 12843 12844 boolean removedForAllUsers = false; 12845 boolean systemUpdate = false; 12846 12847 // for the uninstall-updates case and restricted profiles, remember the per- 12848 // userhandle installed state 12849 int[] allUsers; 12850 boolean[] perUserInstalled; 12851 synchronized (mPackages) { 12852 PackageSetting ps = mSettings.mPackages.get(packageName); 12853 allUsers = sUserManager.getUserIds(); 12854 perUserInstalled = new boolean[allUsers.length]; 12855 for (int i = 0; i < allUsers.length; i++) { 12856 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12857 } 12858 } 12859 12860 synchronized (mInstallLock) { 12861 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12862 res = deletePackageLI(packageName, removeForUser, 12863 true, allUsers, perUserInstalled, 12864 flags | REMOVE_CHATTY, info, true); 12865 systemUpdate = info.isRemovedPackageSystemUpdate; 12866 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12867 removedForAllUsers = true; 12868 } 12869 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12870 + " removedForAllUsers=" + removedForAllUsers); 12871 } 12872 12873 if (res) { 12874 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12875 12876 // If the removed package was a system update, the old system package 12877 // was re-enabled; we need to broadcast this information 12878 if (systemUpdate) { 12879 Bundle extras = new Bundle(1); 12880 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12881 ? info.removedAppId : info.uid); 12882 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12883 12884 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12885 extras, null, null, null); 12886 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12887 extras, null, null, null); 12888 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12889 null, packageName, null, null); 12890 } 12891 } 12892 // Force a gc here. 12893 Runtime.getRuntime().gc(); 12894 // Delete the resources here after sending the broadcast to let 12895 // other processes clean up before deleting resources. 12896 if (info.args != null) { 12897 synchronized (mInstallLock) { 12898 info.args.doPostDeleteLI(true); 12899 } 12900 } 12901 12902 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12903 } 12904 12905 class PackageRemovedInfo { 12906 String removedPackage; 12907 int uid = -1; 12908 int removedAppId = -1; 12909 int[] removedUsers = null; 12910 boolean isRemovedPackageSystemUpdate = false; 12911 // Clean up resources deleted packages. 12912 InstallArgs args = null; 12913 12914 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12915 Bundle extras = new Bundle(1); 12916 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12917 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12918 if (replacing) { 12919 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12920 } 12921 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12922 if (removedPackage != null) { 12923 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12924 extras, null, null, removedUsers); 12925 if (fullRemove && !replacing) { 12926 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12927 extras, null, null, removedUsers); 12928 } 12929 } 12930 if (removedAppId >= 0) { 12931 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12932 removedUsers); 12933 } 12934 } 12935 } 12936 12937 /* 12938 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12939 * flag is not set, the data directory is removed as well. 12940 * make sure this flag is set for partially installed apps. If not its meaningless to 12941 * delete a partially installed application. 12942 */ 12943 private void removePackageDataLI(PackageSetting ps, 12944 int[] allUserHandles, boolean[] perUserInstalled, 12945 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12946 String packageName = ps.name; 12947 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12948 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12949 // Retrieve object to delete permissions for shared user later on 12950 final PackageSetting deletedPs; 12951 // reader 12952 synchronized (mPackages) { 12953 deletedPs = mSettings.mPackages.get(packageName); 12954 if (outInfo != null) { 12955 outInfo.removedPackage = packageName; 12956 outInfo.removedUsers = deletedPs != null 12957 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12958 : null; 12959 } 12960 } 12961 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12962 removeDataDirsLI(ps.volumeUuid, packageName); 12963 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12964 } 12965 // writer 12966 synchronized (mPackages) { 12967 if (deletedPs != null) { 12968 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12969 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12970 clearDefaultBrowserIfNeeded(packageName); 12971 if (outInfo != null) { 12972 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12973 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12974 } 12975 updatePermissionsLPw(deletedPs.name, null, 0); 12976 if (deletedPs.sharedUser != null) { 12977 // Remove permissions associated with package. Since runtime 12978 // permissions are per user we have to kill the removed package 12979 // or packages running under the shared user of the removed 12980 // package if revoking the permissions requested only by the removed 12981 // package is successful and this causes a change in gids. 12982 for (int userId : UserManagerService.getInstance().getUserIds()) { 12983 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12984 userId); 12985 if (userIdToKill == UserHandle.USER_ALL 12986 || userIdToKill >= UserHandle.USER_OWNER) { 12987 // If gids changed for this user, kill all affected packages. 12988 mHandler.post(new Runnable() { 12989 @Override 12990 public void run() { 12991 // This has to happen with no lock held. 12992 killApplication(deletedPs.name, deletedPs.appId, 12993 KILL_APP_REASON_GIDS_CHANGED); 12994 } 12995 }); 12996 break; 12997 } 12998 } 12999 } 13000 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13001 } 13002 // make sure to preserve per-user disabled state if this removal was just 13003 // a downgrade of a system app to the factory package 13004 if (allUserHandles != null && perUserInstalled != null) { 13005 if (DEBUG_REMOVE) { 13006 Slog.d(TAG, "Propagating install state across downgrade"); 13007 } 13008 for (int i = 0; i < allUserHandles.length; i++) { 13009 if (DEBUG_REMOVE) { 13010 Slog.d(TAG, " user " + allUserHandles[i] 13011 + " => " + perUserInstalled[i]); 13012 } 13013 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13014 } 13015 } 13016 } 13017 // can downgrade to reader 13018 if (writeSettings) { 13019 // Save settings now 13020 mSettings.writeLPr(); 13021 } 13022 } 13023 if (outInfo != null) { 13024 // A user ID was deleted here. Go through all users and remove it 13025 // from KeyStore. 13026 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13027 } 13028 } 13029 13030 static boolean locationIsPrivileged(File path) { 13031 try { 13032 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13033 .getCanonicalPath(); 13034 return path.getCanonicalPath().startsWith(privilegedAppDir); 13035 } catch (IOException e) { 13036 Slog.e(TAG, "Unable to access code path " + path); 13037 } 13038 return false; 13039 } 13040 13041 /* 13042 * Tries to delete system package. 13043 */ 13044 private boolean deleteSystemPackageLI(PackageSetting newPs, 13045 int[] allUserHandles, boolean[] perUserInstalled, 13046 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13047 final boolean applyUserRestrictions 13048 = (allUserHandles != null) && (perUserInstalled != null); 13049 PackageSetting disabledPs = null; 13050 // Confirm if the system package has been updated 13051 // An updated system app can be deleted. This will also have to restore 13052 // the system pkg from system partition 13053 // reader 13054 synchronized (mPackages) { 13055 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13056 } 13057 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13058 + " disabledPs=" + disabledPs); 13059 if (disabledPs == null) { 13060 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13061 return false; 13062 } else if (DEBUG_REMOVE) { 13063 Slog.d(TAG, "Deleting system pkg from data partition"); 13064 } 13065 if (DEBUG_REMOVE) { 13066 if (applyUserRestrictions) { 13067 Slog.d(TAG, "Remembering install states:"); 13068 for (int i = 0; i < allUserHandles.length; i++) { 13069 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13070 } 13071 } 13072 } 13073 // Delete the updated package 13074 outInfo.isRemovedPackageSystemUpdate = true; 13075 if (disabledPs.versionCode < newPs.versionCode) { 13076 // Delete data for downgrades 13077 flags &= ~PackageManager.DELETE_KEEP_DATA; 13078 } else { 13079 // Preserve data by setting flag 13080 flags |= PackageManager.DELETE_KEEP_DATA; 13081 } 13082 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13083 allUserHandles, perUserInstalled, outInfo, writeSettings); 13084 if (!ret) { 13085 return false; 13086 } 13087 // writer 13088 synchronized (mPackages) { 13089 // Reinstate the old system package 13090 mSettings.enableSystemPackageLPw(newPs.name); 13091 // Remove any native libraries from the upgraded package. 13092 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13093 } 13094 // Install the system package 13095 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13096 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13097 if (locationIsPrivileged(disabledPs.codePath)) { 13098 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13099 } 13100 13101 final PackageParser.Package newPkg; 13102 try { 13103 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13104 } catch (PackageManagerException e) { 13105 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13106 return false; 13107 } 13108 13109 // writer 13110 synchronized (mPackages) { 13111 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13112 13113 // Propagate the permissions state as we do not want to drop on the floor 13114 // runtime permissions. The update permissions method below will take 13115 // care of removing obsolete permissions and grant install permissions. 13116 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13117 updatePermissionsLPw(newPkg.packageName, newPkg, 13118 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13119 13120 if (applyUserRestrictions) { 13121 if (DEBUG_REMOVE) { 13122 Slog.d(TAG, "Propagating install state across reinstall"); 13123 } 13124 for (int i = 0; i < allUserHandles.length; i++) { 13125 if (DEBUG_REMOVE) { 13126 Slog.d(TAG, " user " + allUserHandles[i] 13127 + " => " + perUserInstalled[i]); 13128 } 13129 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13130 13131 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13132 } 13133 // Regardless of writeSettings we need to ensure that this restriction 13134 // state propagation is persisted 13135 mSettings.writeAllUsersPackageRestrictionsLPr(); 13136 } 13137 // can downgrade to reader here 13138 if (writeSettings) { 13139 mSettings.writeLPr(); 13140 } 13141 } 13142 return true; 13143 } 13144 13145 private boolean deleteInstalledPackageLI(PackageSetting ps, 13146 boolean deleteCodeAndResources, int flags, 13147 int[] allUserHandles, boolean[] perUserInstalled, 13148 PackageRemovedInfo outInfo, boolean writeSettings) { 13149 if (outInfo != null) { 13150 outInfo.uid = ps.appId; 13151 } 13152 13153 // Delete package data from internal structures and also remove data if flag is set 13154 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13155 13156 // Delete application code and resources 13157 if (deleteCodeAndResources && (outInfo != null)) { 13158 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13159 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13160 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13161 } 13162 return true; 13163 } 13164 13165 @Override 13166 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13167 int userId) { 13168 mContext.enforceCallingOrSelfPermission( 13169 android.Manifest.permission.DELETE_PACKAGES, null); 13170 synchronized (mPackages) { 13171 PackageSetting ps = mSettings.mPackages.get(packageName); 13172 if (ps == null) { 13173 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13174 return false; 13175 } 13176 if (!ps.getInstalled(userId)) { 13177 // Can't block uninstall for an app that is not installed or enabled. 13178 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13179 return false; 13180 } 13181 ps.setBlockUninstall(blockUninstall, userId); 13182 mSettings.writePackageRestrictionsLPr(userId); 13183 } 13184 return true; 13185 } 13186 13187 @Override 13188 public boolean getBlockUninstallForUser(String packageName, int userId) { 13189 synchronized (mPackages) { 13190 PackageSetting ps = mSettings.mPackages.get(packageName); 13191 if (ps == null) { 13192 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13193 return false; 13194 } 13195 return ps.getBlockUninstall(userId); 13196 } 13197 } 13198 13199 /* 13200 * This method handles package deletion in general 13201 */ 13202 private boolean deletePackageLI(String packageName, UserHandle user, 13203 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13204 int flags, PackageRemovedInfo outInfo, 13205 boolean writeSettings) { 13206 if (packageName == null) { 13207 Slog.w(TAG, "Attempt to delete null packageName."); 13208 return false; 13209 } 13210 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13211 PackageSetting ps; 13212 boolean dataOnly = false; 13213 int removeUser = -1; 13214 int appId = -1; 13215 synchronized (mPackages) { 13216 ps = mSettings.mPackages.get(packageName); 13217 if (ps == null) { 13218 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13219 return false; 13220 } 13221 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13222 && user.getIdentifier() != UserHandle.USER_ALL) { 13223 // The caller is asking that the package only be deleted for a single 13224 // user. To do this, we just mark its uninstalled state and delete 13225 // its data. If this is a system app, we only allow this to happen if 13226 // they have set the special DELETE_SYSTEM_APP which requests different 13227 // semantics than normal for uninstalling system apps. 13228 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13229 final int userId = user.getIdentifier(); 13230 ps.setUserState(userId, 13231 COMPONENT_ENABLED_STATE_DEFAULT, 13232 false, //installed 13233 true, //stopped 13234 true, //notLaunched 13235 false, //hidden 13236 null, null, null, 13237 false, // blockUninstall 13238 ps.readUserState(userId).domainVerificationStatus, 0); 13239 if (!isSystemApp(ps)) { 13240 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13241 // Other user still have this package installed, so all 13242 // we need to do is clear this user's data and save that 13243 // it is uninstalled. 13244 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13245 removeUser = user.getIdentifier(); 13246 appId = ps.appId; 13247 scheduleWritePackageRestrictionsLocked(removeUser); 13248 } else { 13249 // We need to set it back to 'installed' so the uninstall 13250 // broadcasts will be sent correctly. 13251 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13252 ps.setInstalled(true, user.getIdentifier()); 13253 } 13254 } else { 13255 // This is a system app, so we assume that the 13256 // other users still have this package installed, so all 13257 // we need to do is clear this user's data and save that 13258 // it is uninstalled. 13259 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13260 removeUser = user.getIdentifier(); 13261 appId = ps.appId; 13262 scheduleWritePackageRestrictionsLocked(removeUser); 13263 } 13264 } 13265 } 13266 13267 if (removeUser >= 0) { 13268 // From above, we determined that we are deleting this only 13269 // for a single user. Continue the work here. 13270 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13271 if (outInfo != null) { 13272 outInfo.removedPackage = packageName; 13273 outInfo.removedAppId = appId; 13274 outInfo.removedUsers = new int[] {removeUser}; 13275 } 13276 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13277 removeKeystoreDataIfNeeded(removeUser, appId); 13278 schedulePackageCleaning(packageName, removeUser, false); 13279 synchronized (mPackages) { 13280 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13281 scheduleWritePackageRestrictionsLocked(removeUser); 13282 } 13283 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13284 } 13285 return true; 13286 } 13287 13288 if (dataOnly) { 13289 // Delete application data first 13290 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13291 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13292 return true; 13293 } 13294 13295 boolean ret = false; 13296 if (isSystemApp(ps)) { 13297 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13298 // When an updated system application is deleted we delete the existing resources as well and 13299 // fall back to existing code in system partition 13300 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13301 flags, outInfo, writeSettings); 13302 } else { 13303 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13304 // Kill application pre-emptively especially for apps on sd. 13305 killApplication(packageName, ps.appId, "uninstall pkg"); 13306 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13307 allUserHandles, perUserInstalled, 13308 outInfo, writeSettings); 13309 } 13310 13311 return ret; 13312 } 13313 13314 private final class ClearStorageConnection implements ServiceConnection { 13315 IMediaContainerService mContainerService; 13316 13317 @Override 13318 public void onServiceConnected(ComponentName name, IBinder service) { 13319 synchronized (this) { 13320 mContainerService = IMediaContainerService.Stub.asInterface(service); 13321 notifyAll(); 13322 } 13323 } 13324 13325 @Override 13326 public void onServiceDisconnected(ComponentName name) { 13327 } 13328 } 13329 13330 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13331 final boolean mounted; 13332 if (Environment.isExternalStorageEmulated()) { 13333 mounted = true; 13334 } else { 13335 final String status = Environment.getExternalStorageState(); 13336 13337 mounted = status.equals(Environment.MEDIA_MOUNTED) 13338 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13339 } 13340 13341 if (!mounted) { 13342 return; 13343 } 13344 13345 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13346 int[] users; 13347 if (userId == UserHandle.USER_ALL) { 13348 users = sUserManager.getUserIds(); 13349 } else { 13350 users = new int[] { userId }; 13351 } 13352 final ClearStorageConnection conn = new ClearStorageConnection(); 13353 if (mContext.bindServiceAsUser( 13354 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13355 try { 13356 for (int curUser : users) { 13357 long timeout = SystemClock.uptimeMillis() + 5000; 13358 synchronized (conn) { 13359 long now = SystemClock.uptimeMillis(); 13360 while (conn.mContainerService == null && now < timeout) { 13361 try { 13362 conn.wait(timeout - now); 13363 } catch (InterruptedException e) { 13364 } 13365 } 13366 } 13367 if (conn.mContainerService == null) { 13368 return; 13369 } 13370 13371 final UserEnvironment userEnv = new UserEnvironment(curUser); 13372 clearDirectory(conn.mContainerService, 13373 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13374 if (allData) { 13375 clearDirectory(conn.mContainerService, 13376 userEnv.buildExternalStorageAppDataDirs(packageName)); 13377 clearDirectory(conn.mContainerService, 13378 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13379 } 13380 } 13381 } finally { 13382 mContext.unbindService(conn); 13383 } 13384 } 13385 } 13386 13387 @Override 13388 public void clearApplicationUserData(final String packageName, 13389 final IPackageDataObserver observer, final int userId) { 13390 mContext.enforceCallingOrSelfPermission( 13391 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13392 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13393 // Queue up an async operation since the package deletion may take a little while. 13394 mHandler.post(new Runnable() { 13395 public void run() { 13396 mHandler.removeCallbacks(this); 13397 final boolean succeeded; 13398 synchronized (mInstallLock) { 13399 succeeded = clearApplicationUserDataLI(packageName, userId); 13400 } 13401 clearExternalStorageDataSync(packageName, userId, true); 13402 if (succeeded) { 13403 // invoke DeviceStorageMonitor's update method to clear any notifications 13404 DeviceStorageMonitorInternal 13405 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13406 if (dsm != null) { 13407 dsm.checkMemory(); 13408 } 13409 } 13410 if(observer != null) { 13411 try { 13412 observer.onRemoveCompleted(packageName, succeeded); 13413 } catch (RemoteException e) { 13414 Log.i(TAG, "Observer no longer exists."); 13415 } 13416 } //end if observer 13417 } //end run 13418 }); 13419 } 13420 13421 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13422 if (packageName == null) { 13423 Slog.w(TAG, "Attempt to delete null packageName."); 13424 return false; 13425 } 13426 13427 // Try finding details about the requested package 13428 PackageParser.Package pkg; 13429 synchronized (mPackages) { 13430 pkg = mPackages.get(packageName); 13431 if (pkg == null) { 13432 final PackageSetting ps = mSettings.mPackages.get(packageName); 13433 if (ps != null) { 13434 pkg = ps.pkg; 13435 } 13436 } 13437 13438 if (pkg == null) { 13439 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13440 return false; 13441 } 13442 13443 PackageSetting ps = (PackageSetting) pkg.mExtras; 13444 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13445 } 13446 13447 // Always delete data directories for package, even if we found no other 13448 // record of app. This helps users recover from UID mismatches without 13449 // resorting to a full data wipe. 13450 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13451 if (retCode < 0) { 13452 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13453 return false; 13454 } 13455 13456 final int appId = pkg.applicationInfo.uid; 13457 removeKeystoreDataIfNeeded(userId, appId); 13458 13459 // Create a native library symlink only if we have native libraries 13460 // and if the native libraries are 32 bit libraries. We do not provide 13461 // this symlink for 64 bit libraries. 13462 if (pkg.applicationInfo.primaryCpuAbi != null && 13463 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13464 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13465 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13466 nativeLibPath, userId) < 0) { 13467 Slog.w(TAG, "Failed linking native library dir"); 13468 return false; 13469 } 13470 } 13471 13472 return true; 13473 } 13474 13475 /** 13476 * Reverts user permission state changes (permissions and flags) in 13477 * all packages for a given user. 13478 * 13479 * @param userId The device user for which to do a reset. 13480 */ 13481 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13482 final int packageCount = mPackages.size(); 13483 for (int i = 0; i < packageCount; i++) { 13484 PackageParser.Package pkg = mPackages.valueAt(i); 13485 PackageSetting ps = (PackageSetting) pkg.mExtras; 13486 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13487 } 13488 } 13489 13490 /** 13491 * Reverts user permission state changes (permissions and flags). 13492 * 13493 * @param ps The package for which to reset. 13494 * @param userId The device user for which to do a reset. 13495 */ 13496 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13497 final PackageSetting ps, final int userId) { 13498 if (ps.pkg == null) { 13499 return; 13500 } 13501 13502 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13503 | FLAG_PERMISSION_USER_FIXED 13504 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13505 13506 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13507 | FLAG_PERMISSION_POLICY_FIXED; 13508 13509 boolean writeInstallPermissions = false; 13510 boolean writeRuntimePermissions = false; 13511 13512 final int permissionCount = ps.pkg.requestedPermissions.size(); 13513 for (int i = 0; i < permissionCount; i++) { 13514 String permission = ps.pkg.requestedPermissions.get(i); 13515 13516 BasePermission bp = mSettings.mPermissions.get(permission); 13517 if (bp == null) { 13518 continue; 13519 } 13520 13521 // If shared user we just reset the state to which only this app contributed. 13522 if (ps.sharedUser != null) { 13523 boolean used = false; 13524 final int packageCount = ps.sharedUser.packages.size(); 13525 for (int j = 0; j < packageCount; j++) { 13526 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13527 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13528 && pkg.pkg.requestedPermissions.contains(permission)) { 13529 used = true; 13530 break; 13531 } 13532 } 13533 if (used) { 13534 continue; 13535 } 13536 } 13537 13538 PermissionsState permissionsState = ps.getPermissionsState(); 13539 13540 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13541 13542 // Always clear the user settable flags. 13543 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13544 bp.name) != null; 13545 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13546 if (hasInstallState) { 13547 writeInstallPermissions = true; 13548 } else { 13549 writeRuntimePermissions = true; 13550 } 13551 } 13552 13553 // Below is only runtime permission handling. 13554 if (!bp.isRuntime()) { 13555 continue; 13556 } 13557 13558 // Never clobber system or policy. 13559 if ((oldFlags & policyOrSystemFlags) != 0) { 13560 continue; 13561 } 13562 13563 // If this permission was granted by default, make sure it is. 13564 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13565 if (permissionsState.grantRuntimePermission(bp, userId) 13566 != PERMISSION_OPERATION_FAILURE) { 13567 writeRuntimePermissions = true; 13568 } 13569 } else { 13570 // Otherwise, reset the permission. 13571 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13572 switch (revokeResult) { 13573 case PERMISSION_OPERATION_SUCCESS: { 13574 writeRuntimePermissions = true; 13575 } break; 13576 13577 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13578 writeRuntimePermissions = true; 13579 final int appId = ps.appId; 13580 mHandler.post(new Runnable() { 13581 @Override 13582 public void run() { 13583 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13584 } 13585 }); 13586 } break; 13587 } 13588 } 13589 } 13590 13591 // Synchronously write as we are taking permissions away. 13592 if (writeRuntimePermissions) { 13593 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13594 } 13595 13596 // Synchronously write as we are taking permissions away. 13597 if (writeInstallPermissions) { 13598 mSettings.writeLPr(); 13599 } 13600 } 13601 13602 /** 13603 * Remove entries from the keystore daemon. Will only remove it if the 13604 * {@code appId} is valid. 13605 */ 13606 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13607 if (appId < 0) { 13608 return; 13609 } 13610 13611 final KeyStore keyStore = KeyStore.getInstance(); 13612 if (keyStore != null) { 13613 if (userId == UserHandle.USER_ALL) { 13614 for (final int individual : sUserManager.getUserIds()) { 13615 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13616 } 13617 } else { 13618 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13619 } 13620 } else { 13621 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13622 } 13623 } 13624 13625 @Override 13626 public void deleteApplicationCacheFiles(final String packageName, 13627 final IPackageDataObserver observer) { 13628 mContext.enforceCallingOrSelfPermission( 13629 android.Manifest.permission.DELETE_CACHE_FILES, null); 13630 // Queue up an async operation since the package deletion may take a little while. 13631 final int userId = UserHandle.getCallingUserId(); 13632 mHandler.post(new Runnable() { 13633 public void run() { 13634 mHandler.removeCallbacks(this); 13635 final boolean succeded; 13636 synchronized (mInstallLock) { 13637 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13638 } 13639 clearExternalStorageDataSync(packageName, userId, false); 13640 if (observer != null) { 13641 try { 13642 observer.onRemoveCompleted(packageName, succeded); 13643 } catch (RemoteException e) { 13644 Log.i(TAG, "Observer no longer exists."); 13645 } 13646 } //end if observer 13647 } //end run 13648 }); 13649 } 13650 13651 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13652 if (packageName == null) { 13653 Slog.w(TAG, "Attempt to delete null packageName."); 13654 return false; 13655 } 13656 PackageParser.Package p; 13657 synchronized (mPackages) { 13658 p = mPackages.get(packageName); 13659 } 13660 if (p == null) { 13661 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13662 return false; 13663 } 13664 final ApplicationInfo applicationInfo = p.applicationInfo; 13665 if (applicationInfo == null) { 13666 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13667 return false; 13668 } 13669 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13670 if (retCode < 0) { 13671 Slog.w(TAG, "Couldn't remove cache files for package: " 13672 + packageName + " u" + userId); 13673 return false; 13674 } 13675 return true; 13676 } 13677 13678 @Override 13679 public void getPackageSizeInfo(final String packageName, int userHandle, 13680 final IPackageStatsObserver observer) { 13681 mContext.enforceCallingOrSelfPermission( 13682 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13683 if (packageName == null) { 13684 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13685 } 13686 13687 PackageStats stats = new PackageStats(packageName, userHandle); 13688 13689 /* 13690 * Queue up an async operation since the package measurement may take a 13691 * little while. 13692 */ 13693 Message msg = mHandler.obtainMessage(INIT_COPY); 13694 msg.obj = new MeasureParams(stats, observer); 13695 mHandler.sendMessage(msg); 13696 } 13697 13698 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13699 PackageStats pStats) { 13700 if (packageName == null) { 13701 Slog.w(TAG, "Attempt to get size of null packageName."); 13702 return false; 13703 } 13704 PackageParser.Package p; 13705 boolean dataOnly = false; 13706 String libDirRoot = null; 13707 String asecPath = null; 13708 PackageSetting ps = null; 13709 synchronized (mPackages) { 13710 p = mPackages.get(packageName); 13711 ps = mSettings.mPackages.get(packageName); 13712 if(p == null) { 13713 dataOnly = true; 13714 if((ps == null) || (ps.pkg == null)) { 13715 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13716 return false; 13717 } 13718 p = ps.pkg; 13719 } 13720 if (ps != null) { 13721 libDirRoot = ps.legacyNativeLibraryPathString; 13722 } 13723 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13724 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13725 if (secureContainerId != null) { 13726 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13727 } 13728 } 13729 } 13730 String publicSrcDir = null; 13731 if(!dataOnly) { 13732 final ApplicationInfo applicationInfo = p.applicationInfo; 13733 if (applicationInfo == null) { 13734 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13735 return false; 13736 } 13737 if (p.isForwardLocked()) { 13738 publicSrcDir = applicationInfo.getBaseResourcePath(); 13739 } 13740 } 13741 // TODO: extend to measure size of split APKs 13742 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13743 // not just the first level. 13744 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13745 // just the primary. 13746 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13747 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13748 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13749 if (res < 0) { 13750 return false; 13751 } 13752 13753 // Fix-up for forward-locked applications in ASEC containers. 13754 if (!isExternal(p)) { 13755 pStats.codeSize += pStats.externalCodeSize; 13756 pStats.externalCodeSize = 0L; 13757 } 13758 13759 return true; 13760 } 13761 13762 13763 @Override 13764 public void addPackageToPreferred(String packageName) { 13765 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13766 } 13767 13768 @Override 13769 public void removePackageFromPreferred(String packageName) { 13770 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13771 } 13772 13773 @Override 13774 public List<PackageInfo> getPreferredPackages(int flags) { 13775 return new ArrayList<PackageInfo>(); 13776 } 13777 13778 private int getUidTargetSdkVersionLockedLPr(int uid) { 13779 Object obj = mSettings.getUserIdLPr(uid); 13780 if (obj instanceof SharedUserSetting) { 13781 final SharedUserSetting sus = (SharedUserSetting) obj; 13782 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13783 final Iterator<PackageSetting> it = sus.packages.iterator(); 13784 while (it.hasNext()) { 13785 final PackageSetting ps = it.next(); 13786 if (ps.pkg != null) { 13787 int v = ps.pkg.applicationInfo.targetSdkVersion; 13788 if (v < vers) vers = v; 13789 } 13790 } 13791 return vers; 13792 } else if (obj instanceof PackageSetting) { 13793 final PackageSetting ps = (PackageSetting) obj; 13794 if (ps.pkg != null) { 13795 return ps.pkg.applicationInfo.targetSdkVersion; 13796 } 13797 } 13798 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13799 } 13800 13801 @Override 13802 public void addPreferredActivity(IntentFilter filter, int match, 13803 ComponentName[] set, ComponentName activity, int userId) { 13804 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13805 "Adding preferred"); 13806 } 13807 13808 private void addPreferredActivityInternal(IntentFilter filter, int match, 13809 ComponentName[] set, ComponentName activity, boolean always, int userId, 13810 String opname) { 13811 // writer 13812 int callingUid = Binder.getCallingUid(); 13813 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13814 if (filter.countActions() == 0) { 13815 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13816 return; 13817 } 13818 synchronized (mPackages) { 13819 if (mContext.checkCallingOrSelfPermission( 13820 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13821 != PackageManager.PERMISSION_GRANTED) { 13822 if (getUidTargetSdkVersionLockedLPr(callingUid) 13823 < Build.VERSION_CODES.FROYO) { 13824 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13825 + callingUid); 13826 return; 13827 } 13828 mContext.enforceCallingOrSelfPermission( 13829 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13830 } 13831 13832 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13833 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13834 + userId + ":"); 13835 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13836 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13837 scheduleWritePackageRestrictionsLocked(userId); 13838 } 13839 } 13840 13841 @Override 13842 public void replacePreferredActivity(IntentFilter filter, int match, 13843 ComponentName[] set, ComponentName activity, int userId) { 13844 if (filter.countActions() != 1) { 13845 throw new IllegalArgumentException( 13846 "replacePreferredActivity expects filter to have only 1 action."); 13847 } 13848 if (filter.countDataAuthorities() != 0 13849 || filter.countDataPaths() != 0 13850 || filter.countDataSchemes() > 1 13851 || filter.countDataTypes() != 0) { 13852 throw new IllegalArgumentException( 13853 "replacePreferredActivity expects filter to have no data authorities, " + 13854 "paths, or types; and at most one scheme."); 13855 } 13856 13857 final int callingUid = Binder.getCallingUid(); 13858 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13859 synchronized (mPackages) { 13860 if (mContext.checkCallingOrSelfPermission( 13861 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13862 != PackageManager.PERMISSION_GRANTED) { 13863 if (getUidTargetSdkVersionLockedLPr(callingUid) 13864 < Build.VERSION_CODES.FROYO) { 13865 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13866 + Binder.getCallingUid()); 13867 return; 13868 } 13869 mContext.enforceCallingOrSelfPermission( 13870 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13871 } 13872 13873 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13874 if (pir != null) { 13875 // Get all of the existing entries that exactly match this filter. 13876 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13877 if (existing != null && existing.size() == 1) { 13878 PreferredActivity cur = existing.get(0); 13879 if (DEBUG_PREFERRED) { 13880 Slog.i(TAG, "Checking replace of preferred:"); 13881 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13882 if (!cur.mPref.mAlways) { 13883 Slog.i(TAG, " -- CUR; not mAlways!"); 13884 } else { 13885 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13886 Slog.i(TAG, " -- CUR: mSet=" 13887 + Arrays.toString(cur.mPref.mSetComponents)); 13888 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13889 Slog.i(TAG, " -- NEW: mMatch=" 13890 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13891 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13892 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13893 } 13894 } 13895 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13896 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13897 && cur.mPref.sameSet(set)) { 13898 // Setting the preferred activity to what it happens to be already 13899 if (DEBUG_PREFERRED) { 13900 Slog.i(TAG, "Replacing with same preferred activity " 13901 + cur.mPref.mShortComponent + " for user " 13902 + userId + ":"); 13903 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13904 } 13905 return; 13906 } 13907 } 13908 13909 if (existing != null) { 13910 if (DEBUG_PREFERRED) { 13911 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13912 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13913 } 13914 for (int i = 0; i < existing.size(); i++) { 13915 PreferredActivity pa = existing.get(i); 13916 if (DEBUG_PREFERRED) { 13917 Slog.i(TAG, "Removing existing preferred activity " 13918 + pa.mPref.mComponent + ":"); 13919 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13920 } 13921 pir.removeFilter(pa); 13922 } 13923 } 13924 } 13925 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13926 "Replacing preferred"); 13927 } 13928 } 13929 13930 @Override 13931 public void clearPackagePreferredActivities(String packageName) { 13932 final int uid = Binder.getCallingUid(); 13933 // writer 13934 synchronized (mPackages) { 13935 PackageParser.Package pkg = mPackages.get(packageName); 13936 if (pkg == null || pkg.applicationInfo.uid != uid) { 13937 if (mContext.checkCallingOrSelfPermission( 13938 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13939 != PackageManager.PERMISSION_GRANTED) { 13940 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13941 < Build.VERSION_CODES.FROYO) { 13942 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13943 + Binder.getCallingUid()); 13944 return; 13945 } 13946 mContext.enforceCallingOrSelfPermission( 13947 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13948 } 13949 } 13950 13951 int user = UserHandle.getCallingUserId(); 13952 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13953 scheduleWritePackageRestrictionsLocked(user); 13954 } 13955 } 13956 } 13957 13958 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13959 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13960 ArrayList<PreferredActivity> removed = null; 13961 boolean changed = false; 13962 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13963 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13964 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13965 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13966 continue; 13967 } 13968 Iterator<PreferredActivity> it = pir.filterIterator(); 13969 while (it.hasNext()) { 13970 PreferredActivity pa = it.next(); 13971 // Mark entry for removal only if it matches the package name 13972 // and the entry is of type "always". 13973 if (packageName == null || 13974 (pa.mPref.mComponent.getPackageName().equals(packageName) 13975 && pa.mPref.mAlways)) { 13976 if (removed == null) { 13977 removed = new ArrayList<PreferredActivity>(); 13978 } 13979 removed.add(pa); 13980 } 13981 } 13982 if (removed != null) { 13983 for (int j=0; j<removed.size(); j++) { 13984 PreferredActivity pa = removed.get(j); 13985 pir.removeFilter(pa); 13986 } 13987 changed = true; 13988 } 13989 } 13990 return changed; 13991 } 13992 13993 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13994 private void clearIntentFilterVerificationsLPw(int userId) { 13995 final int packageCount = mPackages.size(); 13996 for (int i = 0; i < packageCount; i++) { 13997 PackageParser.Package pkg = mPackages.valueAt(i); 13998 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13999 } 14000 } 14001 14002 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14003 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14004 if (userId == UserHandle.USER_ALL) { 14005 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14006 sUserManager.getUserIds())) { 14007 for (int oneUserId : sUserManager.getUserIds()) { 14008 scheduleWritePackageRestrictionsLocked(oneUserId); 14009 } 14010 } 14011 } else { 14012 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14013 scheduleWritePackageRestrictionsLocked(userId); 14014 } 14015 } 14016 } 14017 14018 void clearDefaultBrowserIfNeeded(String packageName) { 14019 for (int oneUserId : sUserManager.getUserIds()) { 14020 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14021 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14022 if (packageName.equals(defaultBrowserPackageName)) { 14023 setDefaultBrowserPackageName(null, oneUserId); 14024 } 14025 } 14026 } 14027 14028 @Override 14029 public void resetApplicationPreferences(int userId) { 14030 mContext.enforceCallingOrSelfPermission( 14031 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14032 // writer 14033 synchronized (mPackages) { 14034 final long identity = Binder.clearCallingIdentity(); 14035 try { 14036 clearPackagePreferredActivitiesLPw(null, userId); 14037 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14038 // TODO: We have to reset the default SMS and Phone. This requires 14039 // significant refactoring to keep all default apps in the package 14040 // manager (cleaner but more work) or have the services provide 14041 // callbacks to the package manager to request a default app reset. 14042 applyFactoryDefaultBrowserLPw(userId); 14043 clearIntentFilterVerificationsLPw(userId); 14044 primeDomainVerificationsLPw(userId); 14045 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14046 scheduleWritePackageRestrictionsLocked(userId); 14047 } finally { 14048 Binder.restoreCallingIdentity(identity); 14049 } 14050 } 14051 } 14052 14053 @Override 14054 public int getPreferredActivities(List<IntentFilter> outFilters, 14055 List<ComponentName> outActivities, String packageName) { 14056 14057 int num = 0; 14058 final int userId = UserHandle.getCallingUserId(); 14059 // reader 14060 synchronized (mPackages) { 14061 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14062 if (pir != null) { 14063 final Iterator<PreferredActivity> it = pir.filterIterator(); 14064 while (it.hasNext()) { 14065 final PreferredActivity pa = it.next(); 14066 if (packageName == null 14067 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14068 && pa.mPref.mAlways)) { 14069 if (outFilters != null) { 14070 outFilters.add(new IntentFilter(pa)); 14071 } 14072 if (outActivities != null) { 14073 outActivities.add(pa.mPref.mComponent); 14074 } 14075 } 14076 } 14077 } 14078 } 14079 14080 return num; 14081 } 14082 14083 @Override 14084 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14085 int userId) { 14086 int callingUid = Binder.getCallingUid(); 14087 if (callingUid != Process.SYSTEM_UID) { 14088 throw new SecurityException( 14089 "addPersistentPreferredActivity can only be run by the system"); 14090 } 14091 if (filter.countActions() == 0) { 14092 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14093 return; 14094 } 14095 synchronized (mPackages) { 14096 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14097 " :"); 14098 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14099 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14100 new PersistentPreferredActivity(filter, activity)); 14101 scheduleWritePackageRestrictionsLocked(userId); 14102 } 14103 } 14104 14105 @Override 14106 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14107 int callingUid = Binder.getCallingUid(); 14108 if (callingUid != Process.SYSTEM_UID) { 14109 throw new SecurityException( 14110 "clearPackagePersistentPreferredActivities can only be run by the system"); 14111 } 14112 ArrayList<PersistentPreferredActivity> removed = null; 14113 boolean changed = false; 14114 synchronized (mPackages) { 14115 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14116 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14117 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14118 .valueAt(i); 14119 if (userId != thisUserId) { 14120 continue; 14121 } 14122 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14123 while (it.hasNext()) { 14124 PersistentPreferredActivity ppa = it.next(); 14125 // Mark entry for removal only if it matches the package name. 14126 if (ppa.mComponent.getPackageName().equals(packageName)) { 14127 if (removed == null) { 14128 removed = new ArrayList<PersistentPreferredActivity>(); 14129 } 14130 removed.add(ppa); 14131 } 14132 } 14133 if (removed != null) { 14134 for (int j=0; j<removed.size(); j++) { 14135 PersistentPreferredActivity ppa = removed.get(j); 14136 ppir.removeFilter(ppa); 14137 } 14138 changed = true; 14139 } 14140 } 14141 14142 if (changed) { 14143 scheduleWritePackageRestrictionsLocked(userId); 14144 } 14145 } 14146 } 14147 14148 /** 14149 * Common machinery for picking apart a restored XML blob and passing 14150 * it to a caller-supplied functor to be applied to the running system. 14151 */ 14152 private void restoreFromXml(XmlPullParser parser, int userId, 14153 String expectedStartTag, BlobXmlRestorer functor) 14154 throws IOException, XmlPullParserException { 14155 int type; 14156 while ((type = parser.next()) != XmlPullParser.START_TAG 14157 && type != XmlPullParser.END_DOCUMENT) { 14158 } 14159 if (type != XmlPullParser.START_TAG) { 14160 // oops didn't find a start tag?! 14161 if (DEBUG_BACKUP) { 14162 Slog.e(TAG, "Didn't find start tag during restore"); 14163 } 14164 return; 14165 } 14166 14167 // this is supposed to be TAG_PREFERRED_BACKUP 14168 if (!expectedStartTag.equals(parser.getName())) { 14169 if (DEBUG_BACKUP) { 14170 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14171 } 14172 return; 14173 } 14174 14175 // skip interfering stuff, then we're aligned with the backing implementation 14176 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14177 functor.apply(parser, userId); 14178 } 14179 14180 private interface BlobXmlRestorer { 14181 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14182 } 14183 14184 /** 14185 * Non-Binder method, support for the backup/restore mechanism: write the 14186 * full set of preferred activities in its canonical XML format. Returns the 14187 * XML output as a byte array, or null if there is none. 14188 */ 14189 @Override 14190 public byte[] getPreferredActivityBackup(int userId) { 14191 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14192 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14193 } 14194 14195 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14196 try { 14197 final XmlSerializer serializer = new FastXmlSerializer(); 14198 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14199 serializer.startDocument(null, true); 14200 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14201 14202 synchronized (mPackages) { 14203 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14204 } 14205 14206 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14207 serializer.endDocument(); 14208 serializer.flush(); 14209 } catch (Exception e) { 14210 if (DEBUG_BACKUP) { 14211 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14212 } 14213 return null; 14214 } 14215 14216 return dataStream.toByteArray(); 14217 } 14218 14219 @Override 14220 public void restorePreferredActivities(byte[] backup, int userId) { 14221 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14222 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14223 } 14224 14225 try { 14226 final XmlPullParser parser = Xml.newPullParser(); 14227 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14228 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14229 new BlobXmlRestorer() { 14230 @Override 14231 public void apply(XmlPullParser parser, int userId) 14232 throws XmlPullParserException, IOException { 14233 synchronized (mPackages) { 14234 mSettings.readPreferredActivitiesLPw(parser, userId); 14235 } 14236 } 14237 } ); 14238 } catch (Exception e) { 14239 if (DEBUG_BACKUP) { 14240 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14241 } 14242 } 14243 } 14244 14245 /** 14246 * Non-Binder method, support for the backup/restore mechanism: write the 14247 * default browser (etc) settings in its canonical XML format. Returns the default 14248 * browser XML representation as a byte array, or null if there is none. 14249 */ 14250 @Override 14251 public byte[] getDefaultAppsBackup(int userId) { 14252 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14253 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14254 } 14255 14256 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14257 try { 14258 final XmlSerializer serializer = new FastXmlSerializer(); 14259 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14260 serializer.startDocument(null, true); 14261 serializer.startTag(null, TAG_DEFAULT_APPS); 14262 14263 synchronized (mPackages) { 14264 mSettings.writeDefaultAppsLPr(serializer, userId); 14265 } 14266 14267 serializer.endTag(null, TAG_DEFAULT_APPS); 14268 serializer.endDocument(); 14269 serializer.flush(); 14270 } catch (Exception e) { 14271 if (DEBUG_BACKUP) { 14272 Slog.e(TAG, "Unable to write default apps for backup", e); 14273 } 14274 return null; 14275 } 14276 14277 return dataStream.toByteArray(); 14278 } 14279 14280 @Override 14281 public void restoreDefaultApps(byte[] backup, int userId) { 14282 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14283 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14284 } 14285 14286 try { 14287 final XmlPullParser parser = Xml.newPullParser(); 14288 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14289 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14290 new BlobXmlRestorer() { 14291 @Override 14292 public void apply(XmlPullParser parser, int userId) 14293 throws XmlPullParserException, IOException { 14294 synchronized (mPackages) { 14295 mSettings.readDefaultAppsLPw(parser, userId); 14296 } 14297 } 14298 } ); 14299 } catch (Exception e) { 14300 if (DEBUG_BACKUP) { 14301 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14302 } 14303 } 14304 } 14305 14306 @Override 14307 public byte[] getIntentFilterVerificationBackup(int userId) { 14308 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14309 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14310 } 14311 14312 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14313 try { 14314 final XmlSerializer serializer = new FastXmlSerializer(); 14315 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14316 serializer.startDocument(null, true); 14317 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14318 14319 synchronized (mPackages) { 14320 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14321 } 14322 14323 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14324 serializer.endDocument(); 14325 serializer.flush(); 14326 } catch (Exception e) { 14327 if (DEBUG_BACKUP) { 14328 Slog.e(TAG, "Unable to write default apps for backup", e); 14329 } 14330 return null; 14331 } 14332 14333 return dataStream.toByteArray(); 14334 } 14335 14336 @Override 14337 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14338 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14339 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14340 } 14341 14342 try { 14343 final XmlPullParser parser = Xml.newPullParser(); 14344 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14345 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14346 new BlobXmlRestorer() { 14347 @Override 14348 public void apply(XmlPullParser parser, int userId) 14349 throws XmlPullParserException, IOException { 14350 synchronized (mPackages) { 14351 mSettings.readAllDomainVerificationsLPr(parser, userId); 14352 mSettings.writeLPr(); 14353 } 14354 } 14355 } ); 14356 } catch (Exception e) { 14357 if (DEBUG_BACKUP) { 14358 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14359 } 14360 } 14361 } 14362 14363 @Override 14364 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14365 int sourceUserId, int targetUserId, int flags) { 14366 mContext.enforceCallingOrSelfPermission( 14367 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14368 int callingUid = Binder.getCallingUid(); 14369 enforceOwnerRights(ownerPackage, callingUid); 14370 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14371 if (intentFilter.countActions() == 0) { 14372 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14373 return; 14374 } 14375 synchronized (mPackages) { 14376 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14377 ownerPackage, targetUserId, flags); 14378 CrossProfileIntentResolver resolver = 14379 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14380 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14381 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14382 if (existing != null) { 14383 int size = existing.size(); 14384 for (int i = 0; i < size; i++) { 14385 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14386 return; 14387 } 14388 } 14389 } 14390 resolver.addFilter(newFilter); 14391 scheduleWritePackageRestrictionsLocked(sourceUserId); 14392 } 14393 } 14394 14395 @Override 14396 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14397 mContext.enforceCallingOrSelfPermission( 14398 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14399 int callingUid = Binder.getCallingUid(); 14400 enforceOwnerRights(ownerPackage, callingUid); 14401 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14402 synchronized (mPackages) { 14403 CrossProfileIntentResolver resolver = 14404 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14405 ArraySet<CrossProfileIntentFilter> set = 14406 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14407 for (CrossProfileIntentFilter filter : set) { 14408 if (filter.getOwnerPackage().equals(ownerPackage)) { 14409 resolver.removeFilter(filter); 14410 } 14411 } 14412 scheduleWritePackageRestrictionsLocked(sourceUserId); 14413 } 14414 } 14415 14416 // Enforcing that callingUid is owning pkg on userId 14417 private void enforceOwnerRights(String pkg, int callingUid) { 14418 // The system owns everything. 14419 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14420 return; 14421 } 14422 int callingUserId = UserHandle.getUserId(callingUid); 14423 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14424 if (pi == null) { 14425 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14426 + callingUserId); 14427 } 14428 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14429 throw new SecurityException("Calling uid " + callingUid 14430 + " does not own package " + pkg); 14431 } 14432 } 14433 14434 @Override 14435 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14436 Intent intent = new Intent(Intent.ACTION_MAIN); 14437 intent.addCategory(Intent.CATEGORY_HOME); 14438 14439 final int callingUserId = UserHandle.getCallingUserId(); 14440 List<ResolveInfo> list = queryIntentActivities(intent, null, 14441 PackageManager.GET_META_DATA, callingUserId); 14442 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14443 true, false, false, callingUserId); 14444 14445 allHomeCandidates.clear(); 14446 if (list != null) { 14447 for (ResolveInfo ri : list) { 14448 allHomeCandidates.add(ri); 14449 } 14450 } 14451 return (preferred == null || preferred.activityInfo == null) 14452 ? null 14453 : new ComponentName(preferred.activityInfo.packageName, 14454 preferred.activityInfo.name); 14455 } 14456 14457 @Override 14458 public void setApplicationEnabledSetting(String appPackageName, 14459 int newState, int flags, int userId, String callingPackage) { 14460 if (!sUserManager.exists(userId)) return; 14461 if (callingPackage == null) { 14462 callingPackage = Integer.toString(Binder.getCallingUid()); 14463 } 14464 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14465 } 14466 14467 @Override 14468 public void setComponentEnabledSetting(ComponentName componentName, 14469 int newState, int flags, int userId) { 14470 if (!sUserManager.exists(userId)) return; 14471 setEnabledSetting(componentName.getPackageName(), 14472 componentName.getClassName(), newState, flags, userId, null); 14473 } 14474 14475 private void setEnabledSetting(final String packageName, String className, int newState, 14476 final int flags, int userId, String callingPackage) { 14477 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14478 || newState == COMPONENT_ENABLED_STATE_ENABLED 14479 || newState == COMPONENT_ENABLED_STATE_DISABLED 14480 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14481 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14482 throw new IllegalArgumentException("Invalid new component state: " 14483 + newState); 14484 } 14485 PackageSetting pkgSetting; 14486 final int uid = Binder.getCallingUid(); 14487 final int permission = mContext.checkCallingOrSelfPermission( 14488 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14489 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14490 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14491 boolean sendNow = false; 14492 boolean isApp = (className == null); 14493 String componentName = isApp ? packageName : className; 14494 int packageUid = -1; 14495 ArrayList<String> components; 14496 14497 // writer 14498 synchronized (mPackages) { 14499 pkgSetting = mSettings.mPackages.get(packageName); 14500 if (pkgSetting == null) { 14501 if (className == null) { 14502 throw new IllegalArgumentException( 14503 "Unknown package: " + packageName); 14504 } 14505 throw new IllegalArgumentException( 14506 "Unknown component: " + packageName 14507 + "/" + className); 14508 } 14509 // Allow root and verify that userId is not being specified by a different user 14510 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14511 throw new SecurityException( 14512 "Permission Denial: attempt to change component state from pid=" 14513 + Binder.getCallingPid() 14514 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14515 } 14516 if (className == null) { 14517 // We're dealing with an application/package level state change 14518 if (pkgSetting.getEnabled(userId) == newState) { 14519 // Nothing to do 14520 return; 14521 } 14522 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14523 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14524 // Don't care about who enables an app. 14525 callingPackage = null; 14526 } 14527 pkgSetting.setEnabled(newState, userId, callingPackage); 14528 // pkgSetting.pkg.mSetEnabled = newState; 14529 } else { 14530 // We're dealing with a component level state change 14531 // First, verify that this is a valid class name. 14532 PackageParser.Package pkg = pkgSetting.pkg; 14533 if (pkg == null || !pkg.hasComponentClassName(className)) { 14534 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14535 throw new IllegalArgumentException("Component class " + className 14536 + " does not exist in " + packageName); 14537 } else { 14538 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14539 + className + " does not exist in " + packageName); 14540 } 14541 } 14542 switch (newState) { 14543 case COMPONENT_ENABLED_STATE_ENABLED: 14544 if (!pkgSetting.enableComponentLPw(className, userId)) { 14545 return; 14546 } 14547 break; 14548 case COMPONENT_ENABLED_STATE_DISABLED: 14549 if (!pkgSetting.disableComponentLPw(className, userId)) { 14550 return; 14551 } 14552 break; 14553 case COMPONENT_ENABLED_STATE_DEFAULT: 14554 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14555 return; 14556 } 14557 break; 14558 default: 14559 Slog.e(TAG, "Invalid new component state: " + newState); 14560 return; 14561 } 14562 } 14563 scheduleWritePackageRestrictionsLocked(userId); 14564 components = mPendingBroadcasts.get(userId, packageName); 14565 final boolean newPackage = components == null; 14566 if (newPackage) { 14567 components = new ArrayList<String>(); 14568 } 14569 if (!components.contains(componentName)) { 14570 components.add(componentName); 14571 } 14572 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14573 sendNow = true; 14574 // Purge entry from pending broadcast list if another one exists already 14575 // since we are sending one right away. 14576 mPendingBroadcasts.remove(userId, packageName); 14577 } else { 14578 if (newPackage) { 14579 mPendingBroadcasts.put(userId, packageName, components); 14580 } 14581 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14582 // Schedule a message 14583 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14584 } 14585 } 14586 } 14587 14588 long callingId = Binder.clearCallingIdentity(); 14589 try { 14590 if (sendNow) { 14591 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14592 sendPackageChangedBroadcast(packageName, 14593 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14594 } 14595 } finally { 14596 Binder.restoreCallingIdentity(callingId); 14597 } 14598 } 14599 14600 private void sendPackageChangedBroadcast(String packageName, 14601 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14602 if (DEBUG_INSTALL) 14603 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14604 + componentNames); 14605 Bundle extras = new Bundle(4); 14606 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14607 String nameList[] = new String[componentNames.size()]; 14608 componentNames.toArray(nameList); 14609 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14610 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14611 extras.putInt(Intent.EXTRA_UID, packageUid); 14612 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14613 new int[] {UserHandle.getUserId(packageUid)}); 14614 } 14615 14616 @Override 14617 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14618 if (!sUserManager.exists(userId)) return; 14619 final int uid = Binder.getCallingUid(); 14620 final int permission = mContext.checkCallingOrSelfPermission( 14621 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14622 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14623 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14624 // writer 14625 synchronized (mPackages) { 14626 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14627 allowedByPermission, uid, userId)) { 14628 scheduleWritePackageRestrictionsLocked(userId); 14629 } 14630 } 14631 } 14632 14633 @Override 14634 public String getInstallerPackageName(String packageName) { 14635 // reader 14636 synchronized (mPackages) { 14637 return mSettings.getInstallerPackageNameLPr(packageName); 14638 } 14639 } 14640 14641 @Override 14642 public int getApplicationEnabledSetting(String packageName, int userId) { 14643 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14644 int uid = Binder.getCallingUid(); 14645 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14646 // reader 14647 synchronized (mPackages) { 14648 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14649 } 14650 } 14651 14652 @Override 14653 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14654 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14655 int uid = Binder.getCallingUid(); 14656 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14657 // reader 14658 synchronized (mPackages) { 14659 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14660 } 14661 } 14662 14663 @Override 14664 public void enterSafeMode() { 14665 enforceSystemOrRoot("Only the system can request entering safe mode"); 14666 14667 if (!mSystemReady) { 14668 mSafeMode = true; 14669 } 14670 } 14671 14672 @Override 14673 public void systemReady() { 14674 mSystemReady = true; 14675 14676 // Read the compatibilty setting when the system is ready. 14677 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14678 mContext.getContentResolver(), 14679 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14680 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14681 if (DEBUG_SETTINGS) { 14682 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14683 } 14684 14685 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14686 14687 synchronized (mPackages) { 14688 // Verify that all of the preferred activity components actually 14689 // exist. It is possible for applications to be updated and at 14690 // that point remove a previously declared activity component that 14691 // had been set as a preferred activity. We try to clean this up 14692 // the next time we encounter that preferred activity, but it is 14693 // possible for the user flow to never be able to return to that 14694 // situation so here we do a sanity check to make sure we haven't 14695 // left any junk around. 14696 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14697 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14698 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14699 removed.clear(); 14700 for (PreferredActivity pa : pir.filterSet()) { 14701 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14702 removed.add(pa); 14703 } 14704 } 14705 if (removed.size() > 0) { 14706 for (int r=0; r<removed.size(); r++) { 14707 PreferredActivity pa = removed.get(r); 14708 Slog.w(TAG, "Removing dangling preferred activity: " 14709 + pa.mPref.mComponent); 14710 pir.removeFilter(pa); 14711 } 14712 mSettings.writePackageRestrictionsLPr( 14713 mSettings.mPreferredActivities.keyAt(i)); 14714 } 14715 } 14716 14717 for (int userId : UserManagerService.getInstance().getUserIds()) { 14718 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14719 grantPermissionsUserIds = ArrayUtils.appendInt( 14720 grantPermissionsUserIds, userId); 14721 } 14722 } 14723 } 14724 sUserManager.systemReady(); 14725 14726 // If we upgraded grant all default permissions before kicking off. 14727 for (int userId : grantPermissionsUserIds) { 14728 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14729 } 14730 14731 // Kick off any messages waiting for system ready 14732 if (mPostSystemReadyMessages != null) { 14733 for (Message msg : mPostSystemReadyMessages) { 14734 msg.sendToTarget(); 14735 } 14736 mPostSystemReadyMessages = null; 14737 } 14738 14739 // Watch for external volumes that come and go over time 14740 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14741 storage.registerListener(mStorageListener); 14742 14743 mInstallerService.systemReady(); 14744 mPackageDexOptimizer.systemReady(); 14745 14746 MountServiceInternal mountServiceInternal = LocalServices.getService( 14747 MountServiceInternal.class); 14748 mountServiceInternal.addExternalStoragePolicy( 14749 new MountServiceInternal.ExternalStorageMountPolicy() { 14750 @Override 14751 public int getMountMode(int uid, String packageName) { 14752 if (Process.isIsolated(uid)) { 14753 return Zygote.MOUNT_EXTERNAL_NONE; 14754 } 14755 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14756 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14757 } 14758 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14759 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14760 } 14761 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14762 return Zygote.MOUNT_EXTERNAL_READ; 14763 } 14764 return Zygote.MOUNT_EXTERNAL_WRITE; 14765 } 14766 14767 @Override 14768 public boolean hasExternalStorage(int uid, String packageName) { 14769 return true; 14770 } 14771 }); 14772 } 14773 14774 @Override 14775 public boolean isSafeMode() { 14776 return mSafeMode; 14777 } 14778 14779 @Override 14780 public boolean hasSystemUidErrors() { 14781 return mHasSystemUidErrors; 14782 } 14783 14784 static String arrayToString(int[] array) { 14785 StringBuffer buf = new StringBuffer(128); 14786 buf.append('['); 14787 if (array != null) { 14788 for (int i=0; i<array.length; i++) { 14789 if (i > 0) buf.append(", "); 14790 buf.append(array[i]); 14791 } 14792 } 14793 buf.append(']'); 14794 return buf.toString(); 14795 } 14796 14797 static class DumpState { 14798 public static final int DUMP_LIBS = 1 << 0; 14799 public static final int DUMP_FEATURES = 1 << 1; 14800 public static final int DUMP_RESOLVERS = 1 << 2; 14801 public static final int DUMP_PERMISSIONS = 1 << 3; 14802 public static final int DUMP_PACKAGES = 1 << 4; 14803 public static final int DUMP_SHARED_USERS = 1 << 5; 14804 public static final int DUMP_MESSAGES = 1 << 6; 14805 public static final int DUMP_PROVIDERS = 1 << 7; 14806 public static final int DUMP_VERIFIERS = 1 << 8; 14807 public static final int DUMP_PREFERRED = 1 << 9; 14808 public static final int DUMP_PREFERRED_XML = 1 << 10; 14809 public static final int DUMP_KEYSETS = 1 << 11; 14810 public static final int DUMP_VERSION = 1 << 12; 14811 public static final int DUMP_INSTALLS = 1 << 13; 14812 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14813 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14814 14815 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14816 14817 private int mTypes; 14818 14819 private int mOptions; 14820 14821 private boolean mTitlePrinted; 14822 14823 private SharedUserSetting mSharedUser; 14824 14825 public boolean isDumping(int type) { 14826 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14827 return true; 14828 } 14829 14830 return (mTypes & type) != 0; 14831 } 14832 14833 public void setDump(int type) { 14834 mTypes |= type; 14835 } 14836 14837 public boolean isOptionEnabled(int option) { 14838 return (mOptions & option) != 0; 14839 } 14840 14841 public void setOptionEnabled(int option) { 14842 mOptions |= option; 14843 } 14844 14845 public boolean onTitlePrinted() { 14846 final boolean printed = mTitlePrinted; 14847 mTitlePrinted = true; 14848 return printed; 14849 } 14850 14851 public boolean getTitlePrinted() { 14852 return mTitlePrinted; 14853 } 14854 14855 public void setTitlePrinted(boolean enabled) { 14856 mTitlePrinted = enabled; 14857 } 14858 14859 public SharedUserSetting getSharedUser() { 14860 return mSharedUser; 14861 } 14862 14863 public void setSharedUser(SharedUserSetting user) { 14864 mSharedUser = user; 14865 } 14866 } 14867 14868 @Override 14869 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14870 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14871 != PackageManager.PERMISSION_GRANTED) { 14872 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14873 + Binder.getCallingPid() 14874 + ", uid=" + Binder.getCallingUid() 14875 + " without permission " 14876 + android.Manifest.permission.DUMP); 14877 return; 14878 } 14879 14880 DumpState dumpState = new DumpState(); 14881 boolean fullPreferred = false; 14882 boolean checkin = false; 14883 14884 String packageName = null; 14885 ArraySet<String> permissionNames = null; 14886 14887 int opti = 0; 14888 while (opti < args.length) { 14889 String opt = args[opti]; 14890 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14891 break; 14892 } 14893 opti++; 14894 14895 if ("-a".equals(opt)) { 14896 // Right now we only know how to print all. 14897 } else if ("-h".equals(opt)) { 14898 pw.println("Package manager dump options:"); 14899 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14900 pw.println(" --checkin: dump for a checkin"); 14901 pw.println(" -f: print details of intent filters"); 14902 pw.println(" -h: print this help"); 14903 pw.println(" cmd may be one of:"); 14904 pw.println(" l[ibraries]: list known shared libraries"); 14905 pw.println(" f[ibraries]: list device features"); 14906 pw.println(" k[eysets]: print known keysets"); 14907 pw.println(" r[esolvers]: dump intent resolvers"); 14908 pw.println(" perm[issions]: dump permissions"); 14909 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14910 pw.println(" pref[erred]: print preferred package settings"); 14911 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14912 pw.println(" prov[iders]: dump content providers"); 14913 pw.println(" p[ackages]: dump installed packages"); 14914 pw.println(" s[hared-users]: dump shared user IDs"); 14915 pw.println(" m[essages]: print collected runtime messages"); 14916 pw.println(" v[erifiers]: print package verifier info"); 14917 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14918 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14919 pw.println(" version: print database version info"); 14920 pw.println(" write: write current settings now"); 14921 pw.println(" installs: details about install sessions"); 14922 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14923 pw.println(" <package.name>: info about given package"); 14924 return; 14925 } else if ("--checkin".equals(opt)) { 14926 checkin = true; 14927 } else if ("-f".equals(opt)) { 14928 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14929 } else { 14930 pw.println("Unknown argument: " + opt + "; use -h for help"); 14931 } 14932 } 14933 14934 // Is the caller requesting to dump a particular piece of data? 14935 if (opti < args.length) { 14936 String cmd = args[opti]; 14937 opti++; 14938 // Is this a package name? 14939 if ("android".equals(cmd) || cmd.contains(".")) { 14940 packageName = cmd; 14941 // When dumping a single package, we always dump all of its 14942 // filter information since the amount of data will be reasonable. 14943 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14944 } else if ("check-permission".equals(cmd)) { 14945 if (opti >= args.length) { 14946 pw.println("Error: check-permission missing permission argument"); 14947 return; 14948 } 14949 String perm = args[opti]; 14950 opti++; 14951 if (opti >= args.length) { 14952 pw.println("Error: check-permission missing package argument"); 14953 return; 14954 } 14955 String pkg = args[opti]; 14956 opti++; 14957 int user = UserHandle.getUserId(Binder.getCallingUid()); 14958 if (opti < args.length) { 14959 try { 14960 user = Integer.parseInt(args[opti]); 14961 } catch (NumberFormatException e) { 14962 pw.println("Error: check-permission user argument is not a number: " 14963 + args[opti]); 14964 return; 14965 } 14966 } 14967 pw.println(checkPermission(perm, pkg, user)); 14968 return; 14969 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14970 dumpState.setDump(DumpState.DUMP_LIBS); 14971 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14972 dumpState.setDump(DumpState.DUMP_FEATURES); 14973 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14974 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14975 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14976 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14977 } else if ("permission".equals(cmd)) { 14978 if (opti >= args.length) { 14979 pw.println("Error: permission requires permission name"); 14980 return; 14981 } 14982 permissionNames = new ArraySet<>(); 14983 while (opti < args.length) { 14984 permissionNames.add(args[opti]); 14985 opti++; 14986 } 14987 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14988 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14989 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14990 dumpState.setDump(DumpState.DUMP_PREFERRED); 14991 } else if ("preferred-xml".equals(cmd)) { 14992 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14993 if (opti < args.length && "--full".equals(args[opti])) { 14994 fullPreferred = true; 14995 opti++; 14996 } 14997 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14998 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14999 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15000 dumpState.setDump(DumpState.DUMP_PACKAGES); 15001 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15002 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15003 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15004 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15005 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15006 dumpState.setDump(DumpState.DUMP_MESSAGES); 15007 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15008 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15009 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15010 || "intent-filter-verifiers".equals(cmd)) { 15011 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15012 } else if ("version".equals(cmd)) { 15013 dumpState.setDump(DumpState.DUMP_VERSION); 15014 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15015 dumpState.setDump(DumpState.DUMP_KEYSETS); 15016 } else if ("installs".equals(cmd)) { 15017 dumpState.setDump(DumpState.DUMP_INSTALLS); 15018 } else if ("write".equals(cmd)) { 15019 synchronized (mPackages) { 15020 mSettings.writeLPr(); 15021 pw.println("Settings written."); 15022 return; 15023 } 15024 } 15025 } 15026 15027 if (checkin) { 15028 pw.println("vers,1"); 15029 } 15030 15031 // reader 15032 synchronized (mPackages) { 15033 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15034 if (!checkin) { 15035 if (dumpState.onTitlePrinted()) 15036 pw.println(); 15037 pw.println("Database versions:"); 15038 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15039 } 15040 } 15041 15042 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15043 if (!checkin) { 15044 if (dumpState.onTitlePrinted()) 15045 pw.println(); 15046 pw.println("Verifiers:"); 15047 pw.print(" Required: "); 15048 pw.print(mRequiredVerifierPackage); 15049 pw.print(" (uid="); 15050 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15051 pw.println(")"); 15052 } else if (mRequiredVerifierPackage != null) { 15053 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15054 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15055 } 15056 } 15057 15058 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15059 packageName == null) { 15060 if (mIntentFilterVerifierComponent != null) { 15061 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15062 if (!checkin) { 15063 if (dumpState.onTitlePrinted()) 15064 pw.println(); 15065 pw.println("Intent Filter Verifier:"); 15066 pw.print(" Using: "); 15067 pw.print(verifierPackageName); 15068 pw.print(" (uid="); 15069 pw.print(getPackageUid(verifierPackageName, 0)); 15070 pw.println(")"); 15071 } else if (verifierPackageName != null) { 15072 pw.print("ifv,"); pw.print(verifierPackageName); 15073 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15074 } 15075 } else { 15076 pw.println(); 15077 pw.println("No Intent Filter Verifier available!"); 15078 } 15079 } 15080 15081 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15082 boolean printedHeader = false; 15083 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15084 while (it.hasNext()) { 15085 String name = it.next(); 15086 SharedLibraryEntry ent = mSharedLibraries.get(name); 15087 if (!checkin) { 15088 if (!printedHeader) { 15089 if (dumpState.onTitlePrinted()) 15090 pw.println(); 15091 pw.println("Libraries:"); 15092 printedHeader = true; 15093 } 15094 pw.print(" "); 15095 } else { 15096 pw.print("lib,"); 15097 } 15098 pw.print(name); 15099 if (!checkin) { 15100 pw.print(" -> "); 15101 } 15102 if (ent.path != null) { 15103 if (!checkin) { 15104 pw.print("(jar) "); 15105 pw.print(ent.path); 15106 } else { 15107 pw.print(",jar,"); 15108 pw.print(ent.path); 15109 } 15110 } else { 15111 if (!checkin) { 15112 pw.print("(apk) "); 15113 pw.print(ent.apk); 15114 } else { 15115 pw.print(",apk,"); 15116 pw.print(ent.apk); 15117 } 15118 } 15119 pw.println(); 15120 } 15121 } 15122 15123 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15124 if (dumpState.onTitlePrinted()) 15125 pw.println(); 15126 if (!checkin) { 15127 pw.println("Features:"); 15128 } 15129 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15130 while (it.hasNext()) { 15131 String name = it.next(); 15132 if (!checkin) { 15133 pw.print(" "); 15134 } else { 15135 pw.print("feat,"); 15136 } 15137 pw.println(name); 15138 } 15139 } 15140 15141 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15142 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15143 : "Activity Resolver Table:", " ", packageName, 15144 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15145 dumpState.setTitlePrinted(true); 15146 } 15147 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15148 : "Receiver Resolver Table:", " ", packageName, 15149 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15150 dumpState.setTitlePrinted(true); 15151 } 15152 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15153 : "Service Resolver Table:", " ", packageName, 15154 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15155 dumpState.setTitlePrinted(true); 15156 } 15157 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15158 : "Provider Resolver Table:", " ", packageName, 15159 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15160 dumpState.setTitlePrinted(true); 15161 } 15162 } 15163 15164 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15165 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15166 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15167 int user = mSettings.mPreferredActivities.keyAt(i); 15168 if (pir.dump(pw, 15169 dumpState.getTitlePrinted() 15170 ? "\nPreferred Activities User " + user + ":" 15171 : "Preferred Activities User " + user + ":", " ", 15172 packageName, true, false)) { 15173 dumpState.setTitlePrinted(true); 15174 } 15175 } 15176 } 15177 15178 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15179 pw.flush(); 15180 FileOutputStream fout = new FileOutputStream(fd); 15181 BufferedOutputStream str = new BufferedOutputStream(fout); 15182 XmlSerializer serializer = new FastXmlSerializer(); 15183 try { 15184 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15185 serializer.startDocument(null, true); 15186 serializer.setFeature( 15187 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15188 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15189 serializer.endDocument(); 15190 serializer.flush(); 15191 } catch (IllegalArgumentException e) { 15192 pw.println("Failed writing: " + e); 15193 } catch (IllegalStateException e) { 15194 pw.println("Failed writing: " + e); 15195 } catch (IOException e) { 15196 pw.println("Failed writing: " + e); 15197 } 15198 } 15199 15200 if (!checkin 15201 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15202 && packageName == null) { 15203 pw.println(); 15204 int count = mSettings.mPackages.size(); 15205 if (count == 0) { 15206 pw.println("No applications!"); 15207 pw.println(); 15208 } else { 15209 final String prefix = " "; 15210 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15211 if (allPackageSettings.size() == 0) { 15212 pw.println("No domain preferred apps!"); 15213 pw.println(); 15214 } else { 15215 pw.println("App verification status:"); 15216 pw.println(); 15217 count = 0; 15218 for (PackageSetting ps : allPackageSettings) { 15219 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15220 if (ivi == null || ivi.getPackageName() == null) continue; 15221 pw.println(prefix + "Package: " + ivi.getPackageName()); 15222 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15223 pw.println(prefix + "Status: " + ivi.getStatusString()); 15224 pw.println(); 15225 count++; 15226 } 15227 if (count == 0) { 15228 pw.println(prefix + "No app verification established."); 15229 pw.println(); 15230 } 15231 for (int userId : sUserManager.getUserIds()) { 15232 pw.println("App linkages for user " + userId + ":"); 15233 pw.println(); 15234 count = 0; 15235 for (PackageSetting ps : allPackageSettings) { 15236 final long status = ps.getDomainVerificationStatusForUser(userId); 15237 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15238 continue; 15239 } 15240 pw.println(prefix + "Package: " + ps.name); 15241 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15242 String statusStr = IntentFilterVerificationInfo. 15243 getStatusStringFromValue(status); 15244 pw.println(prefix + "Status: " + statusStr); 15245 pw.println(); 15246 count++; 15247 } 15248 if (count == 0) { 15249 pw.println(prefix + "No configured app linkages."); 15250 pw.println(); 15251 } 15252 } 15253 } 15254 } 15255 } 15256 15257 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15258 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15259 if (packageName == null && permissionNames == null) { 15260 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15261 if (iperm == 0) { 15262 if (dumpState.onTitlePrinted()) 15263 pw.println(); 15264 pw.println("AppOp Permissions:"); 15265 } 15266 pw.print(" AppOp Permission "); 15267 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15268 pw.println(":"); 15269 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15270 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15271 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15272 } 15273 } 15274 } 15275 } 15276 15277 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15278 boolean printedSomething = false; 15279 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15280 if (packageName != null && !packageName.equals(p.info.packageName)) { 15281 continue; 15282 } 15283 if (!printedSomething) { 15284 if (dumpState.onTitlePrinted()) 15285 pw.println(); 15286 pw.println("Registered ContentProviders:"); 15287 printedSomething = true; 15288 } 15289 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15290 pw.print(" "); pw.println(p.toString()); 15291 } 15292 printedSomething = false; 15293 for (Map.Entry<String, PackageParser.Provider> entry : 15294 mProvidersByAuthority.entrySet()) { 15295 PackageParser.Provider p = entry.getValue(); 15296 if (packageName != null && !packageName.equals(p.info.packageName)) { 15297 continue; 15298 } 15299 if (!printedSomething) { 15300 if (dumpState.onTitlePrinted()) 15301 pw.println(); 15302 pw.println("ContentProvider Authorities:"); 15303 printedSomething = true; 15304 } 15305 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15306 pw.print(" "); pw.println(p.toString()); 15307 if (p.info != null && p.info.applicationInfo != null) { 15308 final String appInfo = p.info.applicationInfo.toString(); 15309 pw.print(" applicationInfo="); pw.println(appInfo); 15310 } 15311 } 15312 } 15313 15314 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15315 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15316 } 15317 15318 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15319 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15320 } 15321 15322 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15323 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15324 } 15325 15326 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15327 // XXX should handle packageName != null by dumping only install data that 15328 // the given package is involved with. 15329 if (dumpState.onTitlePrinted()) pw.println(); 15330 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15331 } 15332 15333 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15334 if (dumpState.onTitlePrinted()) pw.println(); 15335 mSettings.dumpReadMessagesLPr(pw, dumpState); 15336 15337 pw.println(); 15338 pw.println("Package warning messages:"); 15339 BufferedReader in = null; 15340 String line = null; 15341 try { 15342 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15343 while ((line = in.readLine()) != null) { 15344 if (line.contains("ignored: updated version")) continue; 15345 pw.println(line); 15346 } 15347 } catch (IOException ignored) { 15348 } finally { 15349 IoUtils.closeQuietly(in); 15350 } 15351 } 15352 15353 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15354 BufferedReader in = null; 15355 String line = null; 15356 try { 15357 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15358 while ((line = in.readLine()) != null) { 15359 if (line.contains("ignored: updated version")) continue; 15360 pw.print("msg,"); 15361 pw.println(line); 15362 } 15363 } catch (IOException ignored) { 15364 } finally { 15365 IoUtils.closeQuietly(in); 15366 } 15367 } 15368 } 15369 } 15370 15371 private String dumpDomainString(String packageName) { 15372 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15373 List<IntentFilter> filters = getAllIntentFilters(packageName); 15374 15375 ArraySet<String> result = new ArraySet<>(); 15376 if (iviList.size() > 0) { 15377 for (IntentFilterVerificationInfo ivi : iviList) { 15378 for (String host : ivi.getDomains()) { 15379 result.add(host); 15380 } 15381 } 15382 } 15383 if (filters != null && filters.size() > 0) { 15384 for (IntentFilter filter : filters) { 15385 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15386 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15387 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15388 result.addAll(filter.getHostsList()); 15389 } 15390 } 15391 } 15392 15393 StringBuilder sb = new StringBuilder(result.size() * 16); 15394 for (String domain : result) { 15395 if (sb.length() > 0) sb.append(" "); 15396 sb.append(domain); 15397 } 15398 return sb.toString(); 15399 } 15400 15401 // ------- apps on sdcard specific code ------- 15402 static final boolean DEBUG_SD_INSTALL = false; 15403 15404 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15405 15406 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15407 15408 private boolean mMediaMounted = false; 15409 15410 static String getEncryptKey() { 15411 try { 15412 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15413 SD_ENCRYPTION_KEYSTORE_NAME); 15414 if (sdEncKey == null) { 15415 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15416 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15417 if (sdEncKey == null) { 15418 Slog.e(TAG, "Failed to create encryption keys"); 15419 return null; 15420 } 15421 } 15422 return sdEncKey; 15423 } catch (NoSuchAlgorithmException nsae) { 15424 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15425 return null; 15426 } catch (IOException ioe) { 15427 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15428 return null; 15429 } 15430 } 15431 15432 /* 15433 * Update media status on PackageManager. 15434 */ 15435 @Override 15436 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15437 int callingUid = Binder.getCallingUid(); 15438 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15439 throw new SecurityException("Media status can only be updated by the system"); 15440 } 15441 // reader; this apparently protects mMediaMounted, but should probably 15442 // be a different lock in that case. 15443 synchronized (mPackages) { 15444 Log.i(TAG, "Updating external media status from " 15445 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15446 + (mediaStatus ? "mounted" : "unmounted")); 15447 if (DEBUG_SD_INSTALL) 15448 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15449 + ", mMediaMounted=" + mMediaMounted); 15450 if (mediaStatus == mMediaMounted) { 15451 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15452 : 0, -1); 15453 mHandler.sendMessage(msg); 15454 return; 15455 } 15456 mMediaMounted = mediaStatus; 15457 } 15458 // Queue up an async operation since the package installation may take a 15459 // little while. 15460 mHandler.post(new Runnable() { 15461 public void run() { 15462 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15463 } 15464 }); 15465 } 15466 15467 /** 15468 * Called by MountService when the initial ASECs to scan are available. 15469 * Should block until all the ASEC containers are finished being scanned. 15470 */ 15471 public void scanAvailableAsecs() { 15472 updateExternalMediaStatusInner(true, false, false); 15473 if (mShouldRestoreconData) { 15474 SELinuxMMAC.setRestoreconDone(); 15475 mShouldRestoreconData = false; 15476 } 15477 } 15478 15479 /* 15480 * Collect information of applications on external media, map them against 15481 * existing containers and update information based on current mount status. 15482 * Please note that we always have to report status if reportStatus has been 15483 * set to true especially when unloading packages. 15484 */ 15485 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15486 boolean externalStorage) { 15487 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15488 int[] uidArr = EmptyArray.INT; 15489 15490 final String[] list = PackageHelper.getSecureContainerList(); 15491 if (ArrayUtils.isEmpty(list)) { 15492 Log.i(TAG, "No secure containers found"); 15493 } else { 15494 // Process list of secure containers and categorize them 15495 // as active or stale based on their package internal state. 15496 15497 // reader 15498 synchronized (mPackages) { 15499 for (String cid : list) { 15500 // Leave stages untouched for now; installer service owns them 15501 if (PackageInstallerService.isStageName(cid)) continue; 15502 15503 if (DEBUG_SD_INSTALL) 15504 Log.i(TAG, "Processing container " + cid); 15505 String pkgName = getAsecPackageName(cid); 15506 if (pkgName == null) { 15507 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15508 continue; 15509 } 15510 if (DEBUG_SD_INSTALL) 15511 Log.i(TAG, "Looking for pkg : " + pkgName); 15512 15513 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15514 if (ps == null) { 15515 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15516 continue; 15517 } 15518 15519 /* 15520 * Skip packages that are not external if we're unmounting 15521 * external storage. 15522 */ 15523 if (externalStorage && !isMounted && !isExternal(ps)) { 15524 continue; 15525 } 15526 15527 final AsecInstallArgs args = new AsecInstallArgs(cid, 15528 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15529 // The package status is changed only if the code path 15530 // matches between settings and the container id. 15531 if (ps.codePathString != null 15532 && ps.codePathString.startsWith(args.getCodePath())) { 15533 if (DEBUG_SD_INSTALL) { 15534 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15535 + " at code path: " + ps.codePathString); 15536 } 15537 15538 // We do have a valid package installed on sdcard 15539 processCids.put(args, ps.codePathString); 15540 final int uid = ps.appId; 15541 if (uid != -1) { 15542 uidArr = ArrayUtils.appendInt(uidArr, uid); 15543 } 15544 } else { 15545 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15546 + ps.codePathString); 15547 } 15548 } 15549 } 15550 15551 Arrays.sort(uidArr); 15552 } 15553 15554 // Process packages with valid entries. 15555 if (isMounted) { 15556 if (DEBUG_SD_INSTALL) 15557 Log.i(TAG, "Loading packages"); 15558 loadMediaPackages(processCids, uidArr); 15559 startCleaningPackages(); 15560 mInstallerService.onSecureContainersAvailable(); 15561 } else { 15562 if (DEBUG_SD_INSTALL) 15563 Log.i(TAG, "Unloading packages"); 15564 unloadMediaPackages(processCids, uidArr, reportStatus); 15565 } 15566 } 15567 15568 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15569 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15570 final int size = infos.size(); 15571 final String[] packageNames = new String[size]; 15572 final int[] packageUids = new int[size]; 15573 for (int i = 0; i < size; i++) { 15574 final ApplicationInfo info = infos.get(i); 15575 packageNames[i] = info.packageName; 15576 packageUids[i] = info.uid; 15577 } 15578 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15579 finishedReceiver); 15580 } 15581 15582 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15583 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15584 sendResourcesChangedBroadcast(mediaStatus, replacing, 15585 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15586 } 15587 15588 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15589 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15590 int size = pkgList.length; 15591 if (size > 0) { 15592 // Send broadcasts here 15593 Bundle extras = new Bundle(); 15594 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15595 if (uidArr != null) { 15596 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15597 } 15598 if (replacing) { 15599 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15600 } 15601 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15602 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15603 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15604 } 15605 } 15606 15607 /* 15608 * Look at potentially valid container ids from processCids If package 15609 * information doesn't match the one on record or package scanning fails, 15610 * the cid is added to list of removeCids. We currently don't delete stale 15611 * containers. 15612 */ 15613 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15614 ArrayList<String> pkgList = new ArrayList<String>(); 15615 Set<AsecInstallArgs> keys = processCids.keySet(); 15616 15617 for (AsecInstallArgs args : keys) { 15618 String codePath = processCids.get(args); 15619 if (DEBUG_SD_INSTALL) 15620 Log.i(TAG, "Loading container : " + args.cid); 15621 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15622 try { 15623 // Make sure there are no container errors first. 15624 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15625 Slog.e(TAG, "Failed to mount cid : " + args.cid 15626 + " when installing from sdcard"); 15627 continue; 15628 } 15629 // Check code path here. 15630 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15631 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15632 + " does not match one in settings " + codePath); 15633 continue; 15634 } 15635 // Parse package 15636 int parseFlags = mDefParseFlags; 15637 if (args.isExternalAsec()) { 15638 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15639 } 15640 if (args.isFwdLocked()) { 15641 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15642 } 15643 15644 synchronized (mInstallLock) { 15645 PackageParser.Package pkg = null; 15646 try { 15647 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15648 } catch (PackageManagerException e) { 15649 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15650 } 15651 // Scan the package 15652 if (pkg != null) { 15653 /* 15654 * TODO why is the lock being held? doPostInstall is 15655 * called in other places without the lock. This needs 15656 * to be straightened out. 15657 */ 15658 // writer 15659 synchronized (mPackages) { 15660 retCode = PackageManager.INSTALL_SUCCEEDED; 15661 pkgList.add(pkg.packageName); 15662 // Post process args 15663 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15664 pkg.applicationInfo.uid); 15665 } 15666 } else { 15667 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15668 } 15669 } 15670 15671 } finally { 15672 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15673 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15674 } 15675 } 15676 } 15677 // writer 15678 synchronized (mPackages) { 15679 // If the platform SDK has changed since the last time we booted, 15680 // we need to re-grant app permission to catch any new ones that 15681 // appear. This is really a hack, and means that apps can in some 15682 // cases get permissions that the user didn't initially explicitly 15683 // allow... it would be nice to have some better way to handle 15684 // this situation. 15685 final VersionInfo ver = mSettings.getExternalVersion(); 15686 15687 int updateFlags = UPDATE_PERMISSIONS_ALL; 15688 if (ver.sdkVersion != mSdkVersion) { 15689 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15690 + mSdkVersion + "; regranting permissions for external"); 15691 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15692 } 15693 updatePermissionsLPw(null, null, updateFlags); 15694 15695 // Yay, everything is now upgraded 15696 ver.forceCurrent(); 15697 15698 // can downgrade to reader 15699 // Persist settings 15700 mSettings.writeLPr(); 15701 } 15702 // Send a broadcast to let everyone know we are done processing 15703 if (pkgList.size() > 0) { 15704 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15705 } 15706 } 15707 15708 /* 15709 * Utility method to unload a list of specified containers 15710 */ 15711 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15712 // Just unmount all valid containers. 15713 for (AsecInstallArgs arg : cidArgs) { 15714 synchronized (mInstallLock) { 15715 arg.doPostDeleteLI(false); 15716 } 15717 } 15718 } 15719 15720 /* 15721 * Unload packages mounted on external media. This involves deleting package 15722 * data from internal structures, sending broadcasts about diabled packages, 15723 * gc'ing to free up references, unmounting all secure containers 15724 * corresponding to packages on external media, and posting a 15725 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15726 * that we always have to post this message if status has been requested no 15727 * matter what. 15728 */ 15729 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15730 final boolean reportStatus) { 15731 if (DEBUG_SD_INSTALL) 15732 Log.i(TAG, "unloading media packages"); 15733 ArrayList<String> pkgList = new ArrayList<String>(); 15734 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15735 final Set<AsecInstallArgs> keys = processCids.keySet(); 15736 for (AsecInstallArgs args : keys) { 15737 String pkgName = args.getPackageName(); 15738 if (DEBUG_SD_INSTALL) 15739 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15740 // Delete package internally 15741 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15742 synchronized (mInstallLock) { 15743 boolean res = deletePackageLI(pkgName, null, false, null, null, 15744 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15745 if (res) { 15746 pkgList.add(pkgName); 15747 } else { 15748 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15749 failedList.add(args); 15750 } 15751 } 15752 } 15753 15754 // reader 15755 synchronized (mPackages) { 15756 // We didn't update the settings after removing each package; 15757 // write them now for all packages. 15758 mSettings.writeLPr(); 15759 } 15760 15761 // We have to absolutely send UPDATED_MEDIA_STATUS only 15762 // after confirming that all the receivers processed the ordered 15763 // broadcast when packages get disabled, force a gc to clean things up. 15764 // and unload all the containers. 15765 if (pkgList.size() > 0) { 15766 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15767 new IIntentReceiver.Stub() { 15768 public void performReceive(Intent intent, int resultCode, String data, 15769 Bundle extras, boolean ordered, boolean sticky, 15770 int sendingUser) throws RemoteException { 15771 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15772 reportStatus ? 1 : 0, 1, keys); 15773 mHandler.sendMessage(msg); 15774 } 15775 }); 15776 } else { 15777 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15778 keys); 15779 mHandler.sendMessage(msg); 15780 } 15781 } 15782 15783 private void loadPrivatePackages(VolumeInfo vol) { 15784 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15785 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15786 synchronized (mInstallLock) { 15787 synchronized (mPackages) { 15788 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15789 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15790 for (PackageSetting ps : packages) { 15791 final PackageParser.Package pkg; 15792 try { 15793 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15794 loaded.add(pkg.applicationInfo); 15795 } catch (PackageManagerException e) { 15796 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15797 } 15798 15799 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15800 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15801 } 15802 } 15803 15804 int updateFlags = UPDATE_PERMISSIONS_ALL; 15805 if (ver.sdkVersion != mSdkVersion) { 15806 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15807 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15808 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15809 } 15810 updatePermissionsLPw(null, null, updateFlags); 15811 15812 // Yay, everything is now upgraded 15813 ver.forceCurrent(); 15814 15815 mSettings.writeLPr(); 15816 } 15817 } 15818 15819 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15820 sendResourcesChangedBroadcast(true, false, loaded, null); 15821 } 15822 15823 private void unloadPrivatePackages(VolumeInfo vol) { 15824 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15825 synchronized (mInstallLock) { 15826 synchronized (mPackages) { 15827 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15828 for (PackageSetting ps : packages) { 15829 if (ps.pkg == null) continue; 15830 15831 final ApplicationInfo info = ps.pkg.applicationInfo; 15832 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15833 if (deletePackageLI(ps.name, null, false, null, null, 15834 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15835 unloaded.add(info); 15836 } else { 15837 Slog.w(TAG, "Failed to unload " + ps.codePath); 15838 } 15839 } 15840 15841 mSettings.writeLPr(); 15842 } 15843 } 15844 15845 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15846 sendResourcesChangedBroadcast(false, false, unloaded, null); 15847 } 15848 15849 /** 15850 * Examine all users present on given mounted volume, and destroy data 15851 * belonging to users that are no longer valid, or whose user ID has been 15852 * recycled. 15853 */ 15854 private void reconcileUsers(String volumeUuid) { 15855 final File[] files = FileUtils 15856 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15857 for (File file : files) { 15858 if (!file.isDirectory()) continue; 15859 15860 final int userId; 15861 final UserInfo info; 15862 try { 15863 userId = Integer.parseInt(file.getName()); 15864 info = sUserManager.getUserInfo(userId); 15865 } catch (NumberFormatException e) { 15866 Slog.w(TAG, "Invalid user directory " + file); 15867 continue; 15868 } 15869 15870 boolean destroyUser = false; 15871 if (info == null) { 15872 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15873 + " because no matching user was found"); 15874 destroyUser = true; 15875 } else { 15876 try { 15877 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15878 } catch (IOException e) { 15879 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15880 + " because we failed to enforce serial number: " + e); 15881 destroyUser = true; 15882 } 15883 } 15884 15885 if (destroyUser) { 15886 synchronized (mInstallLock) { 15887 mInstaller.removeUserDataDirs(volumeUuid, userId); 15888 } 15889 } 15890 } 15891 15892 final UserManager um = mContext.getSystemService(UserManager.class); 15893 for (UserInfo user : um.getUsers()) { 15894 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15895 if (userDir.exists()) continue; 15896 15897 try { 15898 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15899 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15900 } catch (IOException e) { 15901 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15902 } 15903 } 15904 } 15905 15906 /** 15907 * Examine all apps present on given mounted volume, and destroy apps that 15908 * aren't expected, either due to uninstallation or reinstallation on 15909 * another volume. 15910 */ 15911 private void reconcileApps(String volumeUuid) { 15912 final File[] files = FileUtils 15913 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15914 for (File file : files) { 15915 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15916 && !PackageInstallerService.isStageName(file.getName()); 15917 if (!isPackage) { 15918 // Ignore entries which are not packages 15919 continue; 15920 } 15921 15922 boolean destroyApp = false; 15923 String packageName = null; 15924 try { 15925 final PackageLite pkg = PackageParser.parsePackageLite(file, 15926 PackageParser.PARSE_MUST_BE_APK); 15927 packageName = pkg.packageName; 15928 15929 synchronized (mPackages) { 15930 final PackageSetting ps = mSettings.mPackages.get(packageName); 15931 if (ps == null) { 15932 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15933 + volumeUuid + " because we found no install record"); 15934 destroyApp = true; 15935 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15936 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15937 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15938 destroyApp = true; 15939 } 15940 } 15941 15942 } catch (PackageParserException e) { 15943 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15944 destroyApp = true; 15945 } 15946 15947 if (destroyApp) { 15948 synchronized (mInstallLock) { 15949 if (packageName != null) { 15950 removeDataDirsLI(volumeUuid, packageName); 15951 } 15952 if (file.isDirectory()) { 15953 mInstaller.rmPackageDir(file.getAbsolutePath()); 15954 } else { 15955 file.delete(); 15956 } 15957 } 15958 } 15959 } 15960 } 15961 15962 private void unfreezePackage(String packageName) { 15963 synchronized (mPackages) { 15964 final PackageSetting ps = mSettings.mPackages.get(packageName); 15965 if (ps != null) { 15966 ps.frozen = false; 15967 } 15968 } 15969 } 15970 15971 @Override 15972 public int movePackage(final String packageName, final String volumeUuid) { 15973 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15974 15975 final int moveId = mNextMoveId.getAndIncrement(); 15976 try { 15977 movePackageInternal(packageName, volumeUuid, moveId); 15978 } catch (PackageManagerException e) { 15979 Slog.w(TAG, "Failed to move " + packageName, e); 15980 mMoveCallbacks.notifyStatusChanged(moveId, 15981 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15982 } 15983 return moveId; 15984 } 15985 15986 private void movePackageInternal(final String packageName, final String volumeUuid, 15987 final int moveId) throws PackageManagerException { 15988 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15989 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15990 final PackageManager pm = mContext.getPackageManager(); 15991 15992 final boolean currentAsec; 15993 final String currentVolumeUuid; 15994 final File codeFile; 15995 final String installerPackageName; 15996 final String packageAbiOverride; 15997 final int appId; 15998 final String seinfo; 15999 final String label; 16000 16001 // reader 16002 synchronized (mPackages) { 16003 final PackageParser.Package pkg = mPackages.get(packageName); 16004 final PackageSetting ps = mSettings.mPackages.get(packageName); 16005 if (pkg == null || ps == null) { 16006 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16007 } 16008 16009 if (pkg.applicationInfo.isSystemApp()) { 16010 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16011 "Cannot move system application"); 16012 } 16013 16014 if (pkg.applicationInfo.isExternalAsec()) { 16015 currentAsec = true; 16016 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16017 } else if (pkg.applicationInfo.isForwardLocked()) { 16018 currentAsec = true; 16019 currentVolumeUuid = "forward_locked"; 16020 } else { 16021 currentAsec = false; 16022 currentVolumeUuid = ps.volumeUuid; 16023 16024 final File probe = new File(pkg.codePath); 16025 final File probeOat = new File(probe, "oat"); 16026 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16027 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16028 "Move only supported for modern cluster style installs"); 16029 } 16030 } 16031 16032 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16033 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16034 "Package already moved to " + volumeUuid); 16035 } 16036 16037 if (ps.frozen) { 16038 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16039 "Failed to move already frozen package"); 16040 } 16041 ps.frozen = true; 16042 16043 codeFile = new File(pkg.codePath); 16044 installerPackageName = ps.installerPackageName; 16045 packageAbiOverride = ps.cpuAbiOverrideString; 16046 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16047 seinfo = pkg.applicationInfo.seinfo; 16048 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16049 } 16050 16051 // Now that we're guarded by frozen state, kill app during move 16052 final long token = Binder.clearCallingIdentity(); 16053 try { 16054 killApplication(packageName, appId, "move pkg"); 16055 } finally { 16056 Binder.restoreCallingIdentity(token); 16057 } 16058 16059 final Bundle extras = new Bundle(); 16060 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16061 extras.putString(Intent.EXTRA_TITLE, label); 16062 mMoveCallbacks.notifyCreated(moveId, extras); 16063 16064 int installFlags; 16065 final boolean moveCompleteApp; 16066 final File measurePath; 16067 16068 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16069 installFlags = INSTALL_INTERNAL; 16070 moveCompleteApp = !currentAsec; 16071 measurePath = Environment.getDataAppDirectory(volumeUuid); 16072 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16073 installFlags = INSTALL_EXTERNAL; 16074 moveCompleteApp = false; 16075 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16076 } else { 16077 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16078 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16079 || !volume.isMountedWritable()) { 16080 unfreezePackage(packageName); 16081 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16082 "Move location not mounted private volume"); 16083 } 16084 16085 Preconditions.checkState(!currentAsec); 16086 16087 installFlags = INSTALL_INTERNAL; 16088 moveCompleteApp = true; 16089 measurePath = Environment.getDataAppDirectory(volumeUuid); 16090 } 16091 16092 final PackageStats stats = new PackageStats(null, -1); 16093 synchronized (mInstaller) { 16094 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16095 unfreezePackage(packageName); 16096 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16097 "Failed to measure package size"); 16098 } 16099 } 16100 16101 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16102 + stats.dataSize); 16103 16104 final long startFreeBytes = measurePath.getFreeSpace(); 16105 final long sizeBytes; 16106 if (moveCompleteApp) { 16107 sizeBytes = stats.codeSize + stats.dataSize; 16108 } else { 16109 sizeBytes = stats.codeSize; 16110 } 16111 16112 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16113 unfreezePackage(packageName); 16114 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16115 "Not enough free space to move"); 16116 } 16117 16118 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16119 16120 final CountDownLatch installedLatch = new CountDownLatch(1); 16121 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16122 @Override 16123 public void onUserActionRequired(Intent intent) throws RemoteException { 16124 throw new IllegalStateException(); 16125 } 16126 16127 @Override 16128 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16129 Bundle extras) throws RemoteException { 16130 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16131 + PackageManager.installStatusToString(returnCode, msg)); 16132 16133 installedLatch.countDown(); 16134 16135 // Regardless of success or failure of the move operation, 16136 // always unfreeze the package 16137 unfreezePackage(packageName); 16138 16139 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16140 switch (status) { 16141 case PackageInstaller.STATUS_SUCCESS: 16142 mMoveCallbacks.notifyStatusChanged(moveId, 16143 PackageManager.MOVE_SUCCEEDED); 16144 break; 16145 case PackageInstaller.STATUS_FAILURE_STORAGE: 16146 mMoveCallbacks.notifyStatusChanged(moveId, 16147 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16148 break; 16149 default: 16150 mMoveCallbacks.notifyStatusChanged(moveId, 16151 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16152 break; 16153 } 16154 } 16155 }; 16156 16157 final MoveInfo move; 16158 if (moveCompleteApp) { 16159 // Kick off a thread to report progress estimates 16160 new Thread() { 16161 @Override 16162 public void run() { 16163 while (true) { 16164 try { 16165 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16166 break; 16167 } 16168 } catch (InterruptedException ignored) { 16169 } 16170 16171 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16172 final int progress = 10 + (int) MathUtils.constrain( 16173 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16174 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16175 } 16176 } 16177 }.start(); 16178 16179 final String dataAppName = codeFile.getName(); 16180 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16181 dataAppName, appId, seinfo); 16182 } else { 16183 move = null; 16184 } 16185 16186 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16187 16188 final Message msg = mHandler.obtainMessage(INIT_COPY); 16189 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16190 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16191 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16192 mHandler.sendMessage(msg); 16193 } 16194 16195 @Override 16196 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16197 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16198 16199 final int realMoveId = mNextMoveId.getAndIncrement(); 16200 final Bundle extras = new Bundle(); 16201 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16202 mMoveCallbacks.notifyCreated(realMoveId, extras); 16203 16204 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16205 @Override 16206 public void onCreated(int moveId, Bundle extras) { 16207 // Ignored 16208 } 16209 16210 @Override 16211 public void onStatusChanged(int moveId, int status, long estMillis) { 16212 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16213 } 16214 }; 16215 16216 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16217 storage.setPrimaryStorageUuid(volumeUuid, callback); 16218 return realMoveId; 16219 } 16220 16221 @Override 16222 public int getMoveStatus(int moveId) { 16223 mContext.enforceCallingOrSelfPermission( 16224 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16225 return mMoveCallbacks.mLastStatus.get(moveId); 16226 } 16227 16228 @Override 16229 public void registerMoveCallback(IPackageMoveObserver callback) { 16230 mContext.enforceCallingOrSelfPermission( 16231 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16232 mMoveCallbacks.register(callback); 16233 } 16234 16235 @Override 16236 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16237 mContext.enforceCallingOrSelfPermission( 16238 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16239 mMoveCallbacks.unregister(callback); 16240 } 16241 16242 @Override 16243 public boolean setInstallLocation(int loc) { 16244 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16245 null); 16246 if (getInstallLocation() == loc) { 16247 return true; 16248 } 16249 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16250 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16251 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16252 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16253 return true; 16254 } 16255 return false; 16256 } 16257 16258 @Override 16259 public int getInstallLocation() { 16260 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16261 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16262 PackageHelper.APP_INSTALL_AUTO); 16263 } 16264 16265 /** Called by UserManagerService */ 16266 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16267 mDirtyUsers.remove(userHandle); 16268 mSettings.removeUserLPw(userHandle); 16269 mPendingBroadcasts.remove(userHandle); 16270 if (mInstaller != null) { 16271 // Technically, we shouldn't be doing this with the package lock 16272 // held. However, this is very rare, and there is already so much 16273 // other disk I/O going on, that we'll let it slide for now. 16274 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16275 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16276 final String volumeUuid = vol.getFsUuid(); 16277 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16278 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16279 } 16280 } 16281 mUserNeedsBadging.delete(userHandle); 16282 removeUnusedPackagesLILPw(userManager, userHandle); 16283 } 16284 16285 /** 16286 * We're removing userHandle and would like to remove any downloaded packages 16287 * that are no longer in use by any other user. 16288 * @param userHandle the user being removed 16289 */ 16290 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16291 final boolean DEBUG_CLEAN_APKS = false; 16292 int [] users = userManager.getUserIdsLPr(); 16293 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16294 while (psit.hasNext()) { 16295 PackageSetting ps = psit.next(); 16296 if (ps.pkg == null) { 16297 continue; 16298 } 16299 final String packageName = ps.pkg.packageName; 16300 // Skip over if system app 16301 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16302 continue; 16303 } 16304 if (DEBUG_CLEAN_APKS) { 16305 Slog.i(TAG, "Checking package " + packageName); 16306 } 16307 boolean keep = false; 16308 for (int i = 0; i < users.length; i++) { 16309 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16310 keep = true; 16311 if (DEBUG_CLEAN_APKS) { 16312 Slog.i(TAG, " Keeping package " + packageName + " for user " 16313 + users[i]); 16314 } 16315 break; 16316 } 16317 } 16318 if (!keep) { 16319 if (DEBUG_CLEAN_APKS) { 16320 Slog.i(TAG, " Removing package " + packageName); 16321 } 16322 mHandler.post(new Runnable() { 16323 public void run() { 16324 deletePackageX(packageName, userHandle, 0); 16325 } //end run 16326 }); 16327 } 16328 } 16329 } 16330 16331 /** Called by UserManagerService */ 16332 void createNewUserLILPw(int userHandle) { 16333 if (mInstaller != null) { 16334 mInstaller.createUserConfig(userHandle); 16335 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16336 applyFactoryDefaultBrowserLPw(userHandle); 16337 primeDomainVerificationsLPw(userHandle); 16338 } 16339 } 16340 16341 void newUserCreated(final int userHandle) { 16342 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16343 } 16344 16345 @Override 16346 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16347 mContext.enforceCallingOrSelfPermission( 16348 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16349 "Only package verification agents can read the verifier device identity"); 16350 16351 synchronized (mPackages) { 16352 return mSettings.getVerifierDeviceIdentityLPw(); 16353 } 16354 } 16355 16356 @Override 16357 public void setPermissionEnforced(String permission, boolean enforced) { 16358 // TODO: Now that we no longer change GID for storage, this should to away. 16359 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16360 "setPermissionEnforced"); 16361 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16362 synchronized (mPackages) { 16363 if (mSettings.mReadExternalStorageEnforced == null 16364 || mSettings.mReadExternalStorageEnforced != enforced) { 16365 mSettings.mReadExternalStorageEnforced = enforced; 16366 mSettings.writeLPr(); 16367 } 16368 } 16369 // kill any non-foreground processes so we restart them and 16370 // grant/revoke the GID. 16371 final IActivityManager am = ActivityManagerNative.getDefault(); 16372 if (am != null) { 16373 final long token = Binder.clearCallingIdentity(); 16374 try { 16375 am.killProcessesBelowForeground("setPermissionEnforcement"); 16376 } catch (RemoteException e) { 16377 } finally { 16378 Binder.restoreCallingIdentity(token); 16379 } 16380 } 16381 } else { 16382 throw new IllegalArgumentException("No selective enforcement for " + permission); 16383 } 16384 } 16385 16386 @Override 16387 @Deprecated 16388 public boolean isPermissionEnforced(String permission) { 16389 return true; 16390 } 16391 16392 @Override 16393 public boolean isStorageLow() { 16394 final long token = Binder.clearCallingIdentity(); 16395 try { 16396 final DeviceStorageMonitorInternal 16397 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16398 if (dsm != null) { 16399 return dsm.isMemoryLow(); 16400 } else { 16401 return false; 16402 } 16403 } finally { 16404 Binder.restoreCallingIdentity(token); 16405 } 16406 } 16407 16408 @Override 16409 public IPackageInstaller getPackageInstaller() { 16410 return mInstallerService; 16411 } 16412 16413 private boolean userNeedsBadging(int userId) { 16414 int index = mUserNeedsBadging.indexOfKey(userId); 16415 if (index < 0) { 16416 final UserInfo userInfo; 16417 final long token = Binder.clearCallingIdentity(); 16418 try { 16419 userInfo = sUserManager.getUserInfo(userId); 16420 } finally { 16421 Binder.restoreCallingIdentity(token); 16422 } 16423 final boolean b; 16424 if (userInfo != null && userInfo.isManagedProfile()) { 16425 b = true; 16426 } else { 16427 b = false; 16428 } 16429 mUserNeedsBadging.put(userId, b); 16430 return b; 16431 } 16432 return mUserNeedsBadging.valueAt(index); 16433 } 16434 16435 @Override 16436 public KeySet getKeySetByAlias(String packageName, String alias) { 16437 if (packageName == null || alias == null) { 16438 return null; 16439 } 16440 synchronized(mPackages) { 16441 final PackageParser.Package pkg = mPackages.get(packageName); 16442 if (pkg == null) { 16443 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16444 throw new IllegalArgumentException("Unknown package: " + packageName); 16445 } 16446 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16447 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16448 } 16449 } 16450 16451 @Override 16452 public KeySet getSigningKeySet(String packageName) { 16453 if (packageName == null) { 16454 return null; 16455 } 16456 synchronized(mPackages) { 16457 final PackageParser.Package pkg = mPackages.get(packageName); 16458 if (pkg == null) { 16459 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16460 throw new IllegalArgumentException("Unknown package: " + packageName); 16461 } 16462 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16463 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16464 throw new SecurityException("May not access signing KeySet of other apps."); 16465 } 16466 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16467 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16468 } 16469 } 16470 16471 @Override 16472 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16473 if (packageName == null || ks == null) { 16474 return false; 16475 } 16476 synchronized(mPackages) { 16477 final PackageParser.Package pkg = mPackages.get(packageName); 16478 if (pkg == null) { 16479 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16480 throw new IllegalArgumentException("Unknown package: " + packageName); 16481 } 16482 IBinder ksh = ks.getToken(); 16483 if (ksh instanceof KeySetHandle) { 16484 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16485 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16486 } 16487 return false; 16488 } 16489 } 16490 16491 @Override 16492 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16493 if (packageName == null || ks == null) { 16494 return false; 16495 } 16496 synchronized(mPackages) { 16497 final PackageParser.Package pkg = mPackages.get(packageName); 16498 if (pkg == null) { 16499 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16500 throw new IllegalArgumentException("Unknown package: " + packageName); 16501 } 16502 IBinder ksh = ks.getToken(); 16503 if (ksh instanceof KeySetHandle) { 16504 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16505 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16506 } 16507 return false; 16508 } 16509 } 16510 16511 public void getUsageStatsIfNoPackageUsageInfo() { 16512 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16513 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16514 if (usm == null) { 16515 throw new IllegalStateException("UsageStatsManager must be initialized"); 16516 } 16517 long now = System.currentTimeMillis(); 16518 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16519 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16520 String packageName = entry.getKey(); 16521 PackageParser.Package pkg = mPackages.get(packageName); 16522 if (pkg == null) { 16523 continue; 16524 } 16525 UsageStats usage = entry.getValue(); 16526 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16527 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16528 } 16529 } 16530 } 16531 16532 /** 16533 * Check and throw if the given before/after packages would be considered a 16534 * downgrade. 16535 */ 16536 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16537 throws PackageManagerException { 16538 if (after.versionCode < before.mVersionCode) { 16539 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16540 "Update version code " + after.versionCode + " is older than current " 16541 + before.mVersionCode); 16542 } else if (after.versionCode == before.mVersionCode) { 16543 if (after.baseRevisionCode < before.baseRevisionCode) { 16544 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16545 "Update base revision code " + after.baseRevisionCode 16546 + " is older than current " + before.baseRevisionCode); 16547 } 16548 16549 if (!ArrayUtils.isEmpty(after.splitNames)) { 16550 for (int i = 0; i < after.splitNames.length; i++) { 16551 final String splitName = after.splitNames[i]; 16552 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16553 if (j != -1) { 16554 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16555 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16556 "Update split " + splitName + " revision code " 16557 + after.splitRevisionCodes[i] + " is older than current " 16558 + before.splitRevisionCodes[j]); 16559 } 16560 } 16561 } 16562 } 16563 } 16564 } 16565 16566 private static class MoveCallbacks extends Handler { 16567 private static final int MSG_CREATED = 1; 16568 private static final int MSG_STATUS_CHANGED = 2; 16569 16570 private final RemoteCallbackList<IPackageMoveObserver> 16571 mCallbacks = new RemoteCallbackList<>(); 16572 16573 private final SparseIntArray mLastStatus = new SparseIntArray(); 16574 16575 public MoveCallbacks(Looper looper) { 16576 super(looper); 16577 } 16578 16579 public void register(IPackageMoveObserver callback) { 16580 mCallbacks.register(callback); 16581 } 16582 16583 public void unregister(IPackageMoveObserver callback) { 16584 mCallbacks.unregister(callback); 16585 } 16586 16587 @Override 16588 public void handleMessage(Message msg) { 16589 final SomeArgs args = (SomeArgs) msg.obj; 16590 final int n = mCallbacks.beginBroadcast(); 16591 for (int i = 0; i < n; i++) { 16592 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16593 try { 16594 invokeCallback(callback, msg.what, args); 16595 } catch (RemoteException ignored) { 16596 } 16597 } 16598 mCallbacks.finishBroadcast(); 16599 args.recycle(); 16600 } 16601 16602 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16603 throws RemoteException { 16604 switch (what) { 16605 case MSG_CREATED: { 16606 callback.onCreated(args.argi1, (Bundle) args.arg2); 16607 break; 16608 } 16609 case MSG_STATUS_CHANGED: { 16610 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16611 break; 16612 } 16613 } 16614 } 16615 16616 private void notifyCreated(int moveId, Bundle extras) { 16617 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16618 16619 final SomeArgs args = SomeArgs.obtain(); 16620 args.argi1 = moveId; 16621 args.arg2 = extras; 16622 obtainMessage(MSG_CREATED, args).sendToTarget(); 16623 } 16624 16625 private void notifyStatusChanged(int moveId, int status) { 16626 notifyStatusChanged(moveId, status, -1); 16627 } 16628 16629 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16630 Slog.v(TAG, "Move " + moveId + " status " + status); 16631 16632 final SomeArgs args = SomeArgs.obtain(); 16633 args.argi1 = moveId; 16634 args.argi2 = status; 16635 args.arg3 = estMillis; 16636 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16637 16638 synchronized (mLastStatus) { 16639 mLastStatus.put(moveId, status); 16640 } 16641 } 16642 } 16643 16644 private final class OnPermissionChangeListeners extends Handler { 16645 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16646 16647 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16648 new RemoteCallbackList<>(); 16649 16650 public OnPermissionChangeListeners(Looper looper) { 16651 super(looper); 16652 } 16653 16654 @Override 16655 public void handleMessage(Message msg) { 16656 switch (msg.what) { 16657 case MSG_ON_PERMISSIONS_CHANGED: { 16658 final int uid = msg.arg1; 16659 handleOnPermissionsChanged(uid); 16660 } break; 16661 } 16662 } 16663 16664 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16665 mPermissionListeners.register(listener); 16666 16667 } 16668 16669 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16670 mPermissionListeners.unregister(listener); 16671 } 16672 16673 public void onPermissionsChanged(int uid) { 16674 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16675 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16676 } 16677 } 16678 16679 private void handleOnPermissionsChanged(int uid) { 16680 final int count = mPermissionListeners.beginBroadcast(); 16681 try { 16682 for (int i = 0; i < count; i++) { 16683 IOnPermissionsChangeListener callback = mPermissionListeners 16684 .getBroadcastItem(i); 16685 try { 16686 callback.onPermissionsChanged(uid); 16687 } catch (RemoteException e) { 16688 Log.e(TAG, "Permission listener is dead", e); 16689 } 16690 } 16691 } finally { 16692 mPermissionListeners.finishBroadcast(); 16693 } 16694 } 16695 } 16696 16697 private class PackageManagerInternalImpl extends PackageManagerInternal { 16698 @Override 16699 public void setLocationPackagesProvider(PackagesProvider provider) { 16700 synchronized (mPackages) { 16701 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16702 } 16703 } 16704 16705 @Override 16706 public void setImePackagesProvider(PackagesProvider provider) { 16707 synchronized (mPackages) { 16708 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16709 } 16710 } 16711 16712 @Override 16713 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16714 synchronized (mPackages) { 16715 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16716 } 16717 } 16718 16719 @Override 16720 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16721 synchronized (mPackages) { 16722 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16723 } 16724 } 16725 16726 @Override 16727 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16728 synchronized (mPackages) { 16729 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16730 } 16731 } 16732 16733 @Override 16734 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16735 synchronized (mPackages) { 16736 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16737 } 16738 } 16739 16740 @Override 16741 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16742 synchronized (mPackages) { 16743 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16744 } 16745 } 16746 16747 @Override 16748 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16749 synchronized (mPackages) { 16750 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16751 packageName, userId); 16752 } 16753 } 16754 16755 @Override 16756 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16757 synchronized (mPackages) { 16758 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16759 packageName, userId); 16760 } 16761 } 16762 @Override 16763 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16764 synchronized (mPackages) { 16765 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16766 packageName, userId); 16767 } 16768 } 16769 } 16770 16771 @Override 16772 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16773 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16774 synchronized (mPackages) { 16775 final long identity = Binder.clearCallingIdentity(); 16776 try { 16777 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16778 packageNames, userId); 16779 } finally { 16780 Binder.restoreCallingIdentity(identity); 16781 } 16782 } 16783 } 16784 16785 private static void enforceSystemOrPhoneCaller(String tag) { 16786 int callingUid = Binder.getCallingUid(); 16787 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16788 throw new SecurityException( 16789 "Cannot call " + tag + " from UID " + callingUid); 16790 } 16791 } 16792} 16793