PackageManagerService.java revision 15447798a38d2b5acb1998731340255f4203f294
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 71import static android.system.OsConstants.O_CREAT; 72import static android.system.OsConstants.O_RDWR; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 77import static com.android.internal.util.ArrayUtils.appendInt; 78import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 87 88import android.Manifest; 89import android.app.ActivityManager; 90import android.app.ActivityManagerNative; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.admin.IDevicePolicyManager; 94import android.app.backup.IBackupManager; 95import android.app.usage.UsageStats; 96import android.app.usage.UsageStatsManager; 97import android.content.BroadcastReceiver; 98import android.content.ComponentName; 99import android.content.Context; 100import android.content.IIntentReceiver; 101import android.content.Intent; 102import android.content.IntentFilter; 103import android.content.IntentSender; 104import android.content.IntentSender.SendIntentException; 105import android.content.ServiceConnection; 106import android.content.pm.ActivityInfo; 107import android.content.pm.ApplicationInfo; 108import android.content.pm.FeatureInfo; 109import android.content.pm.IOnPermissionsChangeListener; 110import android.content.pm.IPackageDataObserver; 111import android.content.pm.IPackageDeleteObserver; 112import android.content.pm.IPackageDeleteObserver2; 113import android.content.pm.IPackageInstallObserver2; 114import android.content.pm.IPackageInstaller; 115import android.content.pm.IPackageManager; 116import android.content.pm.IPackageMoveObserver; 117import android.content.pm.IPackageStatsObserver; 118import android.content.pm.InstrumentationInfo; 119import android.content.pm.IntentFilterVerificationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageManagerInternal; 129import android.content.pm.PackageParser; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageStats; 134import android.content.pm.PackageUserState; 135import android.content.pm.ParceledListSlice; 136import android.content.pm.PermissionGroupInfo; 137import android.content.pm.PermissionInfo; 138import android.content.pm.ProviderInfo; 139import android.content.pm.ResolveInfo; 140import android.content.pm.ServiceInfo; 141import android.content.pm.Signature; 142import android.content.pm.UserInfo; 143import android.content.pm.VerificationParams; 144import android.content.pm.VerifierDeviceIdentity; 145import android.content.pm.VerifierInfo; 146import android.content.res.Resources; 147import android.hardware.display.DisplayManager; 148import android.net.Uri; 149import android.os.Debug; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.FileUtils; 156import android.os.Handler; 157import android.os.IBinder; 158import android.os.Looper; 159import android.os.Message; 160import android.os.Parcel; 161import android.os.ParcelFileDescriptor; 162import android.os.Process; 163import android.os.RemoteCallbackList; 164import android.os.RemoteException; 165import android.os.ResultReceiver; 166import android.os.SELinux; 167import android.os.ServiceManager; 168import android.os.SystemClock; 169import android.os.SystemProperties; 170import android.os.Trace; 171import android.os.UserHandle; 172import android.os.UserManager; 173import android.os.storage.IMountService; 174import android.os.storage.MountServiceInternal; 175import android.os.storage.StorageEventListener; 176import android.os.storage.StorageManager; 177import android.os.storage.VolumeInfo; 178import android.os.storage.VolumeRecord; 179import android.security.KeyStore; 180import android.security.SystemKeyStore; 181import android.system.ErrnoException; 182import android.system.Os; 183import android.system.StructStat; 184import android.text.TextUtils; 185import android.text.format.DateUtils; 186import android.util.ArrayMap; 187import android.util.ArraySet; 188import android.util.AtomicFile; 189import android.util.DisplayMetrics; 190import android.util.EventLog; 191import android.util.ExceptionUtils; 192import android.util.Log; 193import android.util.LogPrinter; 194import android.util.MathUtils; 195import android.util.PrintStreamPrinter; 196import android.util.Slog; 197import android.util.SparseArray; 198import android.util.SparseBooleanArray; 199import android.util.SparseIntArray; 200import android.util.Xml; 201import android.view.Display; 202 203import dalvik.system.DexFile; 204import dalvik.system.VMRuntime; 205 206import libcore.io.IoUtils; 207import libcore.util.EmptyArray; 208 209import com.android.internal.R; 210import com.android.internal.annotations.GuardedBy; 211import com.android.internal.app.IMediaContainerService; 212import com.android.internal.app.ResolverActivity; 213import com.android.internal.content.NativeLibraryHelper; 214import com.android.internal.content.PackageHelper; 215import com.android.internal.os.IParcelFileDescriptorFactory; 216import com.android.internal.os.SomeArgs; 217import com.android.internal.os.Zygote; 218import com.android.internal.util.ArrayUtils; 219import com.android.internal.util.FastPrintWriter; 220import com.android.internal.util.FastXmlSerializer; 221import com.android.internal.util.IndentingPrintWriter; 222import com.android.internal.util.Preconditions; 223import com.android.server.EventLogTags; 224import com.android.server.FgThread; 225import com.android.server.IntentResolver; 226import com.android.server.LocalServices; 227import com.android.server.ServiceThread; 228import com.android.server.SystemConfig; 229import com.android.server.Watchdog; 230import com.android.server.pm.PermissionsState.PermissionState; 231import com.android.server.pm.Settings.DatabaseVersion; 232import com.android.server.pm.Settings.VersionInfo; 233import com.android.server.storage.DeviceStorageMonitorInternal; 234 235import org.xmlpull.v1.XmlPullParser; 236import org.xmlpull.v1.XmlPullParserException; 237import org.xmlpull.v1.XmlSerializer; 238 239import java.io.BufferedInputStream; 240import java.io.BufferedOutputStream; 241import java.io.BufferedReader; 242import java.io.ByteArrayInputStream; 243import java.io.ByteArrayOutputStream; 244import java.io.File; 245import java.io.FileDescriptor; 246import java.io.FileNotFoundException; 247import java.io.FileOutputStream; 248import java.io.FileReader; 249import java.io.FilenameFilter; 250import java.io.IOException; 251import java.io.InputStream; 252import java.io.PrintWriter; 253import java.nio.charset.StandardCharsets; 254import java.security.NoSuchAlgorithmException; 255import java.security.PublicKey; 256import java.security.cert.CertificateEncodingException; 257import java.security.cert.CertificateException; 258import java.text.SimpleDateFormat; 259import java.util.ArrayList; 260import java.util.Arrays; 261import java.util.Collection; 262import java.util.Collections; 263import java.util.Comparator; 264import java.util.Date; 265import java.util.Iterator; 266import java.util.List; 267import java.util.Map; 268import java.util.Objects; 269import java.util.Set; 270import java.util.concurrent.CountDownLatch; 271import java.util.concurrent.TimeUnit; 272import java.util.concurrent.atomic.AtomicBoolean; 273import java.util.concurrent.atomic.AtomicInteger; 274import java.util.concurrent.atomic.AtomicLong; 275 276/** 277 * Keep track of all those .apks everywhere. 278 * 279 * This is very central to the platform's security; please run the unit 280 * tests whenever making modifications here: 281 * 282runtest -c android.content.pm.PackageManagerTests frameworks-core 283 * 284 * {@hide} 285 */ 286public class PackageManagerService extends IPackageManager.Stub { 287 static final String TAG = "PackageManager"; 288 static final boolean DEBUG_SETTINGS = false; 289 static final boolean DEBUG_PREFERRED = false; 290 static final boolean DEBUG_UPGRADE = false; 291 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 292 private static final boolean DEBUG_BACKUP = false; 293 private static final boolean DEBUG_INSTALL = false; 294 private static final boolean DEBUG_REMOVE = false; 295 private static final boolean DEBUG_BROADCASTS = false; 296 private static final boolean DEBUG_SHOW_INFO = false; 297 private static final boolean DEBUG_PACKAGE_INFO = false; 298 private static final boolean DEBUG_INTENT_MATCHING = false; 299 private static final boolean DEBUG_PACKAGE_SCANNING = false; 300 private static final boolean DEBUG_VERIFY = false; 301 private static final boolean DEBUG_DEXOPT = false; 302 private static final boolean DEBUG_ABI_SELECTION = false; 303 304 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 305 306 private static final int RADIO_UID = Process.PHONE_UID; 307 private static final int LOG_UID = Process.LOG_UID; 308 private static final int NFC_UID = Process.NFC_UID; 309 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 310 private static final int SHELL_UID = Process.SHELL_UID; 311 312 // Cap the size of permission trees that 3rd party apps can define 313 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 314 315 // Suffix used during package installation when copying/moving 316 // package apks to install directory. 317 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 318 319 static final int SCAN_NO_DEX = 1<<1; 320 static final int SCAN_FORCE_DEX = 1<<2; 321 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 322 static final int SCAN_NEW_INSTALL = 1<<4; 323 static final int SCAN_NO_PATHS = 1<<5; 324 static final int SCAN_UPDATE_TIME = 1<<6; 325 static final int SCAN_DEFER_DEX = 1<<7; 326 static final int SCAN_BOOTING = 1<<8; 327 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 328 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 329 static final int SCAN_REPLACING = 1<<11; 330 static final int SCAN_REQUIRE_KNOWN = 1<<12; 331 static final int SCAN_MOVE = 1<<13; 332 static final int SCAN_INITIAL = 1<<14; 333 334 static final int REMOVE_CHATTY = 1<<16; 335 336 private static final int[] EMPTY_INT_ARRAY = new int[0]; 337 338 /** 339 * Timeout (in milliseconds) after which the watchdog should declare that 340 * our handler thread is wedged. The usual default for such things is one 341 * minute but we sometimes do very lengthy I/O operations on this thread, 342 * such as installing multi-gigabyte applications, so ours needs to be longer. 343 */ 344 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 345 346 /** 347 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 348 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 349 * settings entry if available, otherwise we use the hardcoded default. If it's been 350 * more than this long since the last fstrim, we force one during the boot sequence. 351 * 352 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 353 * one gets run at the next available charging+idle time. This final mandatory 354 * no-fstrim check kicks in only of the other scheduling criteria is never met. 355 */ 356 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 357 358 /** 359 * Whether verification is enabled by default. 360 */ 361 private static final boolean DEFAULT_VERIFY_ENABLE = true; 362 363 /** 364 * The default maximum time to wait for the verification agent to return in 365 * milliseconds. 366 */ 367 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 368 369 /** 370 * The default response for package verification timeout. 371 * 372 * This can be either PackageManager.VERIFICATION_ALLOW or 373 * PackageManager.VERIFICATION_REJECT. 374 */ 375 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 376 377 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 378 379 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 380 DEFAULT_CONTAINER_PACKAGE, 381 "com.android.defcontainer.DefaultContainerService"); 382 383 private static final String KILL_APP_REASON_GIDS_CHANGED = 384 "permission grant or revoke changed gids"; 385 386 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 387 "permissions revoked"; 388 389 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 390 391 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 392 393 /** Permission grant: not grant the permission. */ 394 private static final int GRANT_DENIED = 1; 395 396 /** Permission grant: grant the permission as an install permission. */ 397 private static final int GRANT_INSTALL = 2; 398 399 /** Permission grant: grant the permission as an install permission for a legacy app. */ 400 private static final int GRANT_INSTALL_LEGACY = 3; 401 402 /** Permission grant: grant the permission as a runtime one. */ 403 private static final int GRANT_RUNTIME = 4; 404 405 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 406 private static final int GRANT_UPGRADE = 5; 407 408 /** Canonical intent used to identify what counts as a "web browser" app */ 409 private static final Intent sBrowserIntent; 410 static { 411 sBrowserIntent = new Intent(); 412 sBrowserIntent.setAction(Intent.ACTION_VIEW); 413 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 414 sBrowserIntent.setData(Uri.parse("http:")); 415 } 416 417 final ServiceThread mHandlerThread; 418 419 final PackageHandler mHandler; 420 421 /** 422 * Messages for {@link #mHandler} that need to wait for system ready before 423 * being dispatched. 424 */ 425 private ArrayList<Message> mPostSystemReadyMessages; 426 427 final int mSdkVersion = Build.VERSION.SDK_INT; 428 429 final Context mContext; 430 final boolean mFactoryTest; 431 final boolean mOnlyCore; 432 final boolean mLazyDexOpt; 433 final long mDexOptLRUThresholdInMills; 434 final DisplayMetrics mMetrics; 435 final int mDefParseFlags; 436 final String[] mSeparateProcesses; 437 final boolean mIsUpgrade; 438 439 // This is where all application persistent data goes. 440 final File mAppDataDir; 441 442 // This is where all application persistent data goes for secondary users. 443 final File mUserAppDataDir; 444 445 /** The location for ASEC container files on internal storage. */ 446 final String mAsecInternalPath; 447 448 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 449 // LOCK HELD. Can be called with mInstallLock held. 450 @GuardedBy("mInstallLock") 451 final Installer mInstaller; 452 453 /** Directory where installed third-party apps stored */ 454 final File mAppInstallDir; 455 456 /** 457 * Directory to which applications installed internally have their 458 * 32 bit native libraries copied. 459 */ 460 private File mAppLib32InstallDir; 461 462 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 463 // apps. 464 final File mDrmAppPrivateInstallDir; 465 466 // ---------------------------------------------------------------- 467 468 // Lock for state used when installing and doing other long running 469 // operations. Methods that must be called with this lock held have 470 // the suffix "LI". 471 final Object mInstallLock = new Object(); 472 473 // ---------------------------------------------------------------- 474 475 // Keys are String (package name), values are Package. This also serves 476 // as the lock for the global state. Methods that must be called with 477 // this lock held have the prefix "LP". 478 @GuardedBy("mPackages") 479 final ArrayMap<String, PackageParser.Package> mPackages = 480 new ArrayMap<String, PackageParser.Package>(); 481 482 // Tracks available target package names -> overlay package paths. 483 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 484 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 485 486 /** 487 * Tracks new system packages [received in an OTA] that we expect to 488 * find updated user-installed versions. Keys are package name, values 489 * are package location. 490 */ 491 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 492 493 /** 494 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 495 */ 496 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 497 /** 498 * Whether or not system app permissions should be promoted from install to runtime. 499 */ 500 boolean mPromoteSystemApps; 501 502 final Settings mSettings; 503 boolean mRestoredSettings; 504 505 // System configuration read by SystemConfig. 506 final int[] mGlobalGids; 507 final SparseArray<ArraySet<String>> mSystemPermissions; 508 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 509 510 // If mac_permissions.xml was found for seinfo labeling. 511 boolean mFoundPolicyFile; 512 513 // If a recursive restorecon of /data/data/<pkg> is needed. 514 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 515 516 public static final class SharedLibraryEntry { 517 public final String path; 518 public final String apk; 519 520 SharedLibraryEntry(String _path, String _apk) { 521 path = _path; 522 apk = _apk; 523 } 524 } 525 526 // Currently known shared libraries. 527 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 528 new ArrayMap<String, SharedLibraryEntry>(); 529 530 // All available activities, for your resolving pleasure. 531 final ActivityIntentResolver mActivities = 532 new ActivityIntentResolver(); 533 534 // All available receivers, for your resolving pleasure. 535 final ActivityIntentResolver mReceivers = 536 new ActivityIntentResolver(); 537 538 // All available services, for your resolving pleasure. 539 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 540 541 // All available providers, for your resolving pleasure. 542 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 543 544 // Mapping from provider base names (first directory in content URI codePath) 545 // to the provider information. 546 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 547 new ArrayMap<String, PackageParser.Provider>(); 548 549 // Mapping from instrumentation class names to info about them. 550 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 551 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 552 553 // Mapping from permission names to info about them. 554 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 555 new ArrayMap<String, PackageParser.PermissionGroup>(); 556 557 // Packages whose data we have transfered into another package, thus 558 // should no longer exist. 559 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 560 561 // Broadcast actions that are only available to the system. 562 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 563 564 /** List of packages waiting for verification. */ 565 final SparseArray<PackageVerificationState> mPendingVerification 566 = new SparseArray<PackageVerificationState>(); 567 568 /** Set of packages associated with each app op permission. */ 569 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 570 571 final PackageInstallerService mInstallerService; 572 573 private final PackageDexOptimizer mPackageDexOptimizer; 574 575 private AtomicInteger mNextMoveId = new AtomicInteger(); 576 private final MoveCallbacks mMoveCallbacks; 577 578 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 579 580 // Cache of users who need badging. 581 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 582 583 /** Token for keys in mPendingVerification. */ 584 private int mPendingVerificationToken = 0; 585 586 volatile boolean mSystemReady; 587 volatile boolean mSafeMode; 588 volatile boolean mHasSystemUidErrors; 589 590 ApplicationInfo mAndroidApplication; 591 final ActivityInfo mResolveActivity = new ActivityInfo(); 592 final ResolveInfo mResolveInfo = new ResolveInfo(); 593 ComponentName mResolveComponentName; 594 PackageParser.Package mPlatformPackage; 595 ComponentName mCustomResolverComponentName; 596 597 boolean mResolverReplaced = false; 598 599 private final ComponentName mIntentFilterVerifierComponent; 600 private int mIntentFilterVerificationToken = 0; 601 602 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 603 = new SparseArray<IntentFilterVerificationState>(); 604 605 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 606 new DefaultPermissionGrantPolicy(this); 607 608 private static class IFVerificationParams { 609 PackageParser.Package pkg; 610 boolean replacing; 611 int userId; 612 int verifierUid; 613 614 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 615 int _userId, int _verifierUid) { 616 pkg = _pkg; 617 replacing = _replacing; 618 userId = _userId; 619 replacing = _replacing; 620 verifierUid = _verifierUid; 621 } 622 } 623 624 private interface IntentFilterVerifier<T extends IntentFilter> { 625 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 626 T filter, String packageName); 627 void startVerifications(int userId); 628 void receiveVerificationResponse(int verificationId); 629 } 630 631 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 632 private Context mContext; 633 private ComponentName mIntentFilterVerifierComponent; 634 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 635 636 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 637 mContext = context; 638 mIntentFilterVerifierComponent = verifierComponent; 639 } 640 641 private String getDefaultScheme() { 642 return IntentFilter.SCHEME_HTTPS; 643 } 644 645 @Override 646 public void startVerifications(int userId) { 647 // Launch verifications requests 648 int count = mCurrentIntentFilterVerifications.size(); 649 for (int n=0; n<count; n++) { 650 int verificationId = mCurrentIntentFilterVerifications.get(n); 651 final IntentFilterVerificationState ivs = 652 mIntentFilterVerificationStates.get(verificationId); 653 654 String packageName = ivs.getPackageName(); 655 656 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 657 final int filterCount = filters.size(); 658 ArraySet<String> domainsSet = new ArraySet<>(); 659 for (int m=0; m<filterCount; m++) { 660 PackageParser.ActivityIntentInfo filter = filters.get(m); 661 domainsSet.addAll(filter.getHostsList()); 662 } 663 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 664 synchronized (mPackages) { 665 if (mSettings.createIntentFilterVerificationIfNeededLPw( 666 packageName, domainsList) != null) { 667 scheduleWriteSettingsLocked(); 668 } 669 } 670 sendVerificationRequest(userId, verificationId, ivs); 671 } 672 mCurrentIntentFilterVerifications.clear(); 673 } 674 675 private void sendVerificationRequest(int userId, int verificationId, 676 IntentFilterVerificationState ivs) { 677 678 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 679 verificationIntent.putExtra( 680 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 681 verificationId); 682 verificationIntent.putExtra( 683 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 684 getDefaultScheme()); 685 verificationIntent.putExtra( 686 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 687 ivs.getHostsString()); 688 verificationIntent.putExtra( 689 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 690 ivs.getPackageName()); 691 verificationIntent.setComponent(mIntentFilterVerifierComponent); 692 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 693 694 UserHandle user = new UserHandle(userId); 695 mContext.sendBroadcastAsUser(verificationIntent, user); 696 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 697 "Sending IntentFilter verification broadcast"); 698 } 699 700 public void receiveVerificationResponse(int verificationId) { 701 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 702 703 final boolean verified = ivs.isVerified(); 704 705 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 706 final int count = filters.size(); 707 if (DEBUG_DOMAIN_VERIFICATION) { 708 Slog.i(TAG, "Received verification response " + verificationId 709 + " for " + count + " filters, verified=" + verified); 710 } 711 for (int n=0; n<count; n++) { 712 PackageParser.ActivityIntentInfo filter = filters.get(n); 713 filter.setVerified(verified); 714 715 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 716 + " verified with result:" + verified + " and hosts:" 717 + ivs.getHostsString()); 718 } 719 720 mIntentFilterVerificationStates.remove(verificationId); 721 722 final String packageName = ivs.getPackageName(); 723 IntentFilterVerificationInfo ivi = null; 724 725 synchronized (mPackages) { 726 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 727 } 728 if (ivi == null) { 729 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 730 + verificationId + " packageName:" + packageName); 731 return; 732 } 733 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 734 "Updating IntentFilterVerificationInfo for package " + packageName 735 +" verificationId:" + verificationId); 736 737 synchronized (mPackages) { 738 if (verified) { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 740 } else { 741 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 742 } 743 scheduleWriteSettingsLocked(); 744 745 final int userId = ivs.getUserId(); 746 if (userId != UserHandle.USER_ALL) { 747 final int userStatus = 748 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 749 750 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 751 boolean needUpdate = false; 752 753 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 754 // already been set by the User thru the Disambiguation dialog 755 switch (userStatus) { 756 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 757 if (verified) { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 759 } else { 760 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 761 } 762 needUpdate = true; 763 break; 764 765 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 766 if (verified) { 767 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 768 needUpdate = true; 769 } 770 break; 771 772 default: 773 // Nothing to do 774 } 775 776 if (needUpdate) { 777 mSettings.updateIntentFilterVerificationStatusLPw( 778 packageName, updatedStatus, userId); 779 scheduleWritePackageRestrictionsLocked(userId); 780 } 781 } 782 } 783 } 784 785 @Override 786 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 787 ActivityIntentInfo filter, String packageName) { 788 if (!hasValidDomains(filter)) { 789 return false; 790 } 791 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 792 if (ivs == null) { 793 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 794 packageName); 795 } 796 if (DEBUG_DOMAIN_VERIFICATION) { 797 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 798 } 799 ivs.addFilter(filter); 800 return true; 801 } 802 803 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 804 int userId, int verificationId, String packageName) { 805 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 806 verifierUid, userId, packageName); 807 ivs.setPendingState(); 808 synchronized (mPackages) { 809 mIntentFilterVerificationStates.append(verificationId, ivs); 810 mCurrentIntentFilterVerifications.add(verificationId); 811 } 812 return ivs; 813 } 814 } 815 816 private static boolean hasValidDomains(ActivityIntentInfo filter) { 817 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 818 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 819 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 820 } 821 822 private IntentFilterVerifier mIntentFilterVerifier; 823 824 // Set of pending broadcasts for aggregating enable/disable of components. 825 static class PendingPackageBroadcasts { 826 // for each user id, a map of <package name -> components within that package> 827 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 828 829 public PendingPackageBroadcasts() { 830 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 831 } 832 833 public ArrayList<String> get(int userId, String packageName) { 834 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 835 return packages.get(packageName); 836 } 837 838 public void put(int userId, String packageName, ArrayList<String> components) { 839 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 840 packages.put(packageName, components); 841 } 842 843 public void remove(int userId, String packageName) { 844 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 845 if (packages != null) { 846 packages.remove(packageName); 847 } 848 } 849 850 public void remove(int userId) { 851 mUidMap.remove(userId); 852 } 853 854 public int userIdCount() { 855 return mUidMap.size(); 856 } 857 858 public int userIdAt(int n) { 859 return mUidMap.keyAt(n); 860 } 861 862 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 863 return mUidMap.get(userId); 864 } 865 866 public int size() { 867 // total number of pending broadcast entries across all userIds 868 int num = 0; 869 for (int i = 0; i< mUidMap.size(); i++) { 870 num += mUidMap.valueAt(i).size(); 871 } 872 return num; 873 } 874 875 public void clear() { 876 mUidMap.clear(); 877 } 878 879 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 880 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 881 if (map == null) { 882 map = new ArrayMap<String, ArrayList<String>>(); 883 mUidMap.put(userId, map); 884 } 885 return map; 886 } 887 } 888 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 889 890 // Service Connection to remote media container service to copy 891 // package uri's from external media onto secure containers 892 // or internal storage. 893 private IMediaContainerService mContainerService = null; 894 895 static final int SEND_PENDING_BROADCAST = 1; 896 static final int MCS_BOUND = 3; 897 static final int END_COPY = 4; 898 static final int INIT_COPY = 5; 899 static final int MCS_UNBIND = 6; 900 static final int START_CLEANING_PACKAGE = 7; 901 static final int FIND_INSTALL_LOC = 8; 902 static final int POST_INSTALL = 9; 903 static final int MCS_RECONNECT = 10; 904 static final int MCS_GIVE_UP = 11; 905 static final int UPDATED_MEDIA_STATUS = 12; 906 static final int WRITE_SETTINGS = 13; 907 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 908 static final int PACKAGE_VERIFIED = 15; 909 static final int CHECK_PENDING_VERIFICATION = 16; 910 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 911 static final int INTENT_FILTER_VERIFIED = 18; 912 913 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 914 915 // Delay time in millisecs 916 static final int BROADCAST_DELAY = 10 * 1000; 917 918 static UserManagerService sUserManager; 919 920 // Stores a list of users whose package restrictions file needs to be updated 921 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 922 923 final private DefaultContainerConnection mDefContainerConn = 924 new DefaultContainerConnection(); 925 class DefaultContainerConnection implements ServiceConnection { 926 public void onServiceConnected(ComponentName name, IBinder service) { 927 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 928 IMediaContainerService imcs = 929 IMediaContainerService.Stub.asInterface(service); 930 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 931 } 932 933 public void onServiceDisconnected(ComponentName name) { 934 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 935 } 936 } 937 938 // Recordkeeping of restore-after-install operations that are currently in flight 939 // between the Package Manager and the Backup Manager 940 class PostInstallData { 941 public InstallArgs args; 942 public PackageInstalledInfo res; 943 944 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 945 args = _a; 946 res = _r; 947 } 948 } 949 950 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 951 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 952 953 // XML tags for backup/restore of various bits of state 954 private static final String TAG_PREFERRED_BACKUP = "pa"; 955 private static final String TAG_DEFAULT_APPS = "da"; 956 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 957 958 final String mRequiredVerifierPackage; 959 final String mRequiredInstallerPackage; 960 961 private final PackageUsage mPackageUsage = new PackageUsage(); 962 963 private class PackageUsage { 964 private static final int WRITE_INTERVAL 965 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 966 967 private final Object mFileLock = new Object(); 968 private final AtomicLong mLastWritten = new AtomicLong(0); 969 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 970 971 private boolean mIsHistoricalPackageUsageAvailable = true; 972 973 boolean isHistoricalPackageUsageAvailable() { 974 return mIsHistoricalPackageUsageAvailable; 975 } 976 977 void write(boolean force) { 978 if (force) { 979 writeInternal(); 980 return; 981 } 982 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 983 && !DEBUG_DEXOPT) { 984 return; 985 } 986 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 987 new Thread("PackageUsage_DiskWriter") { 988 @Override 989 public void run() { 990 try { 991 writeInternal(); 992 } finally { 993 mBackgroundWriteRunning.set(false); 994 } 995 } 996 }.start(); 997 } 998 } 999 1000 private void writeInternal() { 1001 synchronized (mPackages) { 1002 synchronized (mFileLock) { 1003 AtomicFile file = getFile(); 1004 FileOutputStream f = null; 1005 try { 1006 f = file.startWrite(); 1007 BufferedOutputStream out = new BufferedOutputStream(f); 1008 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1009 StringBuilder sb = new StringBuilder(); 1010 for (PackageParser.Package pkg : mPackages.values()) { 1011 if (pkg.mLastPackageUsageTimeInMills == 0) { 1012 continue; 1013 } 1014 sb.setLength(0); 1015 sb.append(pkg.packageName); 1016 sb.append(' '); 1017 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1018 sb.append('\n'); 1019 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1020 } 1021 out.flush(); 1022 file.finishWrite(f); 1023 } catch (IOException e) { 1024 if (f != null) { 1025 file.failWrite(f); 1026 } 1027 Log.e(TAG, "Failed to write package usage times", e); 1028 } 1029 } 1030 } 1031 mLastWritten.set(SystemClock.elapsedRealtime()); 1032 } 1033 1034 void readLP() { 1035 synchronized (mFileLock) { 1036 AtomicFile file = getFile(); 1037 BufferedInputStream in = null; 1038 try { 1039 in = new BufferedInputStream(file.openRead()); 1040 StringBuffer sb = new StringBuffer(); 1041 while (true) { 1042 String packageName = readToken(in, sb, ' '); 1043 if (packageName == null) { 1044 break; 1045 } 1046 String timeInMillisString = readToken(in, sb, '\n'); 1047 if (timeInMillisString == null) { 1048 throw new IOException("Failed to find last usage time for package " 1049 + packageName); 1050 } 1051 PackageParser.Package pkg = mPackages.get(packageName); 1052 if (pkg == null) { 1053 continue; 1054 } 1055 long timeInMillis; 1056 try { 1057 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1058 } catch (NumberFormatException e) { 1059 throw new IOException("Failed to parse " + timeInMillisString 1060 + " as a long.", e); 1061 } 1062 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1063 } 1064 } catch (FileNotFoundException expected) { 1065 mIsHistoricalPackageUsageAvailable = false; 1066 } catch (IOException e) { 1067 Log.w(TAG, "Failed to read package usage times", e); 1068 } finally { 1069 IoUtils.closeQuietly(in); 1070 } 1071 } 1072 mLastWritten.set(SystemClock.elapsedRealtime()); 1073 } 1074 1075 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1076 throws IOException { 1077 sb.setLength(0); 1078 while (true) { 1079 int ch = in.read(); 1080 if (ch == -1) { 1081 if (sb.length() == 0) { 1082 return null; 1083 } 1084 throw new IOException("Unexpected EOF"); 1085 } 1086 if (ch == endOfToken) { 1087 return sb.toString(); 1088 } 1089 sb.append((char)ch); 1090 } 1091 } 1092 1093 private AtomicFile getFile() { 1094 File dataDir = Environment.getDataDirectory(); 1095 File systemDir = new File(dataDir, "system"); 1096 File fname = new File(systemDir, "package-usage.list"); 1097 return new AtomicFile(fname); 1098 } 1099 } 1100 1101 class PackageHandler extends Handler { 1102 private boolean mBound = false; 1103 final ArrayList<HandlerParams> mPendingInstalls = 1104 new ArrayList<HandlerParams>(); 1105 1106 private boolean connectToService() { 1107 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1108 " DefaultContainerService"); 1109 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1111 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1112 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1113 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1114 mBound = true; 1115 return true; 1116 } 1117 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1118 return false; 1119 } 1120 1121 private void disconnectService() { 1122 mContainerService = null; 1123 mBound = false; 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1125 mContext.unbindService(mDefContainerConn); 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1127 } 1128 1129 PackageHandler(Looper looper) { 1130 super(looper); 1131 } 1132 1133 public void handleMessage(Message msg) { 1134 try { 1135 doHandleMessage(msg); 1136 } finally { 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1138 } 1139 } 1140 1141 void doHandleMessage(Message msg) { 1142 switch (msg.what) { 1143 case INIT_COPY: { 1144 HandlerParams params = (HandlerParams) msg.obj; 1145 int idx = mPendingInstalls.size(); 1146 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1147 // If a bind was already initiated we dont really 1148 // need to do anything. The pending install 1149 // will be processed later on. 1150 if (!mBound) { 1151 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1152 System.identityHashCode(mHandler)); 1153 // If this is the only one pending we might 1154 // have to bind to the service again. 1155 if (!connectToService()) { 1156 Slog.e(TAG, "Failed to bind to media container service"); 1157 params.serviceError(); 1158 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1159 System.identityHashCode(mHandler)); 1160 if (params.traceMethod != null) { 1161 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1162 params.traceCookie); 1163 } 1164 return; 1165 } else { 1166 // Once we bind to the service, the first 1167 // pending request will be processed. 1168 mPendingInstalls.add(idx, params); 1169 } 1170 } else { 1171 mPendingInstalls.add(idx, params); 1172 // Already bound to the service. Just make 1173 // sure we trigger off processing the first request. 1174 if (idx == 0) { 1175 mHandler.sendEmptyMessage(MCS_BOUND); 1176 } 1177 } 1178 break; 1179 } 1180 case MCS_BOUND: { 1181 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1182 if (msg.obj != null) { 1183 mContainerService = (IMediaContainerService) msg.obj; 1184 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1185 System.identityHashCode(mHandler)); 1186 } 1187 if (mContainerService == null) { 1188 if (!mBound) { 1189 // Something seriously wrong since we are not bound and we are not 1190 // waiting for connection. Bail out. 1191 Slog.e(TAG, "Cannot bind to media container service"); 1192 for (HandlerParams params : mPendingInstalls) { 1193 // Indicate service bind error 1194 params.serviceError(); 1195 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1196 System.identityHashCode(params)); 1197 if (params.traceMethod != null) { 1198 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1199 params.traceMethod, params.traceCookie); 1200 } 1201 return; 1202 } 1203 mPendingInstalls.clear(); 1204 } else { 1205 Slog.w(TAG, "Waiting to connect to media container service"); 1206 } 1207 } else if (mPendingInstalls.size() > 0) { 1208 HandlerParams params = mPendingInstalls.get(0); 1209 if (params != null) { 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1211 System.identityHashCode(params)); 1212 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1213 if (params.startCopy()) { 1214 // We are done... look for more work or to 1215 // go idle. 1216 if (DEBUG_SD_INSTALL) Log.i(TAG, 1217 "Checking for more work or unbind..."); 1218 // Delete pending install 1219 if (mPendingInstalls.size() > 0) { 1220 mPendingInstalls.remove(0); 1221 } 1222 if (mPendingInstalls.size() == 0) { 1223 if (mBound) { 1224 if (DEBUG_SD_INSTALL) Log.i(TAG, 1225 "Posting delayed MCS_UNBIND"); 1226 removeMessages(MCS_UNBIND); 1227 Message ubmsg = obtainMessage(MCS_UNBIND); 1228 // Unbind after a little delay, to avoid 1229 // continual thrashing. 1230 sendMessageDelayed(ubmsg, 10000); 1231 } 1232 } else { 1233 // There are more pending requests in queue. 1234 // Just post MCS_BOUND message to trigger processing 1235 // of next pending install. 1236 if (DEBUG_SD_INSTALL) Log.i(TAG, 1237 "Posting MCS_BOUND for next work"); 1238 mHandler.sendEmptyMessage(MCS_BOUND); 1239 } 1240 } 1241 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1242 } 1243 } else { 1244 // Should never happen ideally. 1245 Slog.w(TAG, "Empty queue"); 1246 } 1247 break; 1248 } 1249 case MCS_RECONNECT: { 1250 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1251 if (mPendingInstalls.size() > 0) { 1252 if (mBound) { 1253 disconnectService(); 1254 } 1255 if (!connectToService()) { 1256 Slog.e(TAG, "Failed to bind to media container service"); 1257 for (HandlerParams params : mPendingInstalls) { 1258 // Indicate service bind error 1259 params.serviceError(); 1260 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1261 System.identityHashCode(params)); 1262 } 1263 mPendingInstalls.clear(); 1264 } 1265 } 1266 break; 1267 } 1268 case MCS_UNBIND: { 1269 // If there is no actual work left, then time to unbind. 1270 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1271 1272 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1273 if (mBound) { 1274 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1275 1276 disconnectService(); 1277 } 1278 } else if (mPendingInstalls.size() > 0) { 1279 // There are more pending requests in queue. 1280 // Just post MCS_BOUND message to trigger processing 1281 // of next pending install. 1282 mHandler.sendEmptyMessage(MCS_BOUND); 1283 } 1284 1285 break; 1286 } 1287 case MCS_GIVE_UP: { 1288 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1289 HandlerParams params = mPendingInstalls.remove(0); 1290 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1291 System.identityHashCode(params)); 1292 break; 1293 } 1294 case SEND_PENDING_BROADCAST: { 1295 String packages[]; 1296 ArrayList<String> components[]; 1297 int size = 0; 1298 int uids[]; 1299 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1300 synchronized (mPackages) { 1301 if (mPendingBroadcasts == null) { 1302 return; 1303 } 1304 size = mPendingBroadcasts.size(); 1305 if (size <= 0) { 1306 // Nothing to be done. Just return 1307 return; 1308 } 1309 packages = new String[size]; 1310 components = new ArrayList[size]; 1311 uids = new int[size]; 1312 int i = 0; // filling out the above arrays 1313 1314 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1315 int packageUserId = mPendingBroadcasts.userIdAt(n); 1316 Iterator<Map.Entry<String, ArrayList<String>>> it 1317 = mPendingBroadcasts.packagesForUserId(packageUserId) 1318 .entrySet().iterator(); 1319 while (it.hasNext() && i < size) { 1320 Map.Entry<String, ArrayList<String>> ent = it.next(); 1321 packages[i] = ent.getKey(); 1322 components[i] = ent.getValue(); 1323 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1324 uids[i] = (ps != null) 1325 ? UserHandle.getUid(packageUserId, ps.appId) 1326 : -1; 1327 i++; 1328 } 1329 } 1330 size = i; 1331 mPendingBroadcasts.clear(); 1332 } 1333 // Send broadcasts 1334 for (int i = 0; i < size; i++) { 1335 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1336 } 1337 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1338 break; 1339 } 1340 case START_CLEANING_PACKAGE: { 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1342 final String packageName = (String)msg.obj; 1343 final int userId = msg.arg1; 1344 final boolean andCode = msg.arg2 != 0; 1345 synchronized (mPackages) { 1346 if (userId == UserHandle.USER_ALL) { 1347 int[] users = sUserManager.getUserIds(); 1348 for (int user : users) { 1349 mSettings.addPackageToCleanLPw( 1350 new PackageCleanItem(user, packageName, andCode)); 1351 } 1352 } else { 1353 mSettings.addPackageToCleanLPw( 1354 new PackageCleanItem(userId, packageName, andCode)); 1355 } 1356 } 1357 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1358 startCleaningPackages(); 1359 } break; 1360 case POST_INSTALL: { 1361 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1362 PostInstallData data = mRunningInstalls.get(msg.arg1); 1363 mRunningInstalls.delete(msg.arg1); 1364 boolean deleteOld = false; 1365 1366 if (data != null) { 1367 InstallArgs args = data.args; 1368 PackageInstalledInfo res = data.res; 1369 1370 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1371 final String packageName = res.pkg.applicationInfo.packageName; 1372 res.removedInfo.sendBroadcast(false, true, false); 1373 Bundle extras = new Bundle(1); 1374 extras.putInt(Intent.EXTRA_UID, res.uid); 1375 1376 // Now that we successfully installed the package, grant runtime 1377 // permissions if requested before broadcasting the install. 1378 if ((args.installFlags 1379 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1380 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1381 args.installGrantPermissions); 1382 } 1383 1384 // Determine the set of users who are adding this 1385 // package for the first time vs. those who are seeing 1386 // an update. 1387 int[] firstUsers; 1388 int[] updateUsers = new int[0]; 1389 if (res.origUsers == null || res.origUsers.length == 0) { 1390 firstUsers = res.newUsers; 1391 } else { 1392 firstUsers = new int[0]; 1393 for (int i=0; i<res.newUsers.length; i++) { 1394 int user = res.newUsers[i]; 1395 boolean isNew = true; 1396 for (int j=0; j<res.origUsers.length; j++) { 1397 if (res.origUsers[j] == user) { 1398 isNew = false; 1399 break; 1400 } 1401 } 1402 if (isNew) { 1403 int[] newFirst = new int[firstUsers.length+1]; 1404 System.arraycopy(firstUsers, 0, newFirst, 0, 1405 firstUsers.length); 1406 newFirst[firstUsers.length] = user; 1407 firstUsers = newFirst; 1408 } else { 1409 int[] newUpdate = new int[updateUsers.length+1]; 1410 System.arraycopy(updateUsers, 0, newUpdate, 0, 1411 updateUsers.length); 1412 newUpdate[updateUsers.length] = user; 1413 updateUsers = newUpdate; 1414 } 1415 } 1416 } 1417 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1418 packageName, extras, null, null, firstUsers); 1419 final boolean update = res.removedInfo.removedPackage != null; 1420 if (update) { 1421 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1422 } 1423 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1424 packageName, extras, null, null, updateUsers); 1425 if (update) { 1426 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1427 packageName, extras, null, null, updateUsers); 1428 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1429 null, null, packageName, null, updateUsers); 1430 1431 // treat asec-hosted packages like removable media on upgrade 1432 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1433 if (DEBUG_INSTALL) { 1434 Slog.i(TAG, "upgrading pkg " + res.pkg 1435 + " is ASEC-hosted -> AVAILABLE"); 1436 } 1437 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1438 ArrayList<String> pkgList = new ArrayList<String>(1); 1439 pkgList.add(packageName); 1440 sendResourcesChangedBroadcast(true, true, 1441 pkgList,uidArray, null); 1442 } 1443 } 1444 if (res.removedInfo.args != null) { 1445 // Remove the replaced package's older resources safely now 1446 deleteOld = true; 1447 } 1448 1449 // If this app is a browser and it's newly-installed for some 1450 // users, clear any default-browser state in those users 1451 if (firstUsers.length > 0) { 1452 // the app's nature doesn't depend on the user, so we can just 1453 // check its browser nature in any user and generalize. 1454 if (packageIsBrowser(packageName, firstUsers[0])) { 1455 synchronized (mPackages) { 1456 for (int userId : firstUsers) { 1457 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1458 } 1459 } 1460 } 1461 } 1462 // Log current value of "unknown sources" setting 1463 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1464 getUnknownSourcesSettings()); 1465 } 1466 // Force a gc to clear up things 1467 Runtime.getRuntime().gc(); 1468 // We delete after a gc for applications on sdcard. 1469 if (deleteOld) { 1470 synchronized (mInstallLock) { 1471 res.removedInfo.args.doPostDeleteLI(true); 1472 } 1473 } 1474 if (args.observer != null) { 1475 try { 1476 Bundle extras = extrasForInstallResult(res); 1477 args.observer.onPackageInstalled(res.name, res.returnCode, 1478 res.returnMsg, extras); 1479 } catch (RemoteException e) { 1480 Slog.i(TAG, "Observer no longer exists."); 1481 } 1482 } 1483 if (args.traceMethod != null) { 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1485 args.traceCookie); 1486 } 1487 return; 1488 } else { 1489 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1490 } 1491 1492 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1493 } break; 1494 case UPDATED_MEDIA_STATUS: { 1495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1496 boolean reportStatus = msg.arg1 == 1; 1497 boolean doGc = msg.arg2 == 1; 1498 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1499 if (doGc) { 1500 // Force a gc to clear up stale containers. 1501 Runtime.getRuntime().gc(); 1502 } 1503 if (msg.obj != null) { 1504 @SuppressWarnings("unchecked") 1505 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1506 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1507 // Unload containers 1508 unloadAllContainers(args); 1509 } 1510 if (reportStatus) { 1511 try { 1512 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1513 PackageHelper.getMountService().finishMediaUpdate(); 1514 } catch (RemoteException e) { 1515 Log.e(TAG, "MountService not running?"); 1516 } 1517 } 1518 } break; 1519 case WRITE_SETTINGS: { 1520 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1521 synchronized (mPackages) { 1522 removeMessages(WRITE_SETTINGS); 1523 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1524 mSettings.writeLPr(); 1525 mDirtyUsers.clear(); 1526 } 1527 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1528 } break; 1529 case WRITE_PACKAGE_RESTRICTIONS: { 1530 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1531 synchronized (mPackages) { 1532 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1533 for (int userId : mDirtyUsers) { 1534 mSettings.writePackageRestrictionsLPr(userId); 1535 } 1536 mDirtyUsers.clear(); 1537 } 1538 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1539 } break; 1540 case CHECK_PENDING_VERIFICATION: { 1541 final int verificationId = msg.arg1; 1542 final PackageVerificationState state = mPendingVerification.get(verificationId); 1543 1544 if ((state != null) && !state.timeoutExtended()) { 1545 final InstallArgs args = state.getInstallArgs(); 1546 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1547 1548 Slog.i(TAG, "Verification timed out for " + originUri); 1549 mPendingVerification.remove(verificationId); 1550 1551 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1552 1553 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1554 Slog.i(TAG, "Continuing with installation of " + originUri); 1555 state.setVerifierResponse(Binder.getCallingUid(), 1556 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1557 broadcastPackageVerified(verificationId, originUri, 1558 PackageManager.VERIFICATION_ALLOW, 1559 state.getInstallArgs().getUser()); 1560 try { 1561 ret = args.copyApk(mContainerService, true); 1562 } catch (RemoteException e) { 1563 Slog.e(TAG, "Could not contact the ContainerService"); 1564 } 1565 } else { 1566 broadcastPackageVerified(verificationId, originUri, 1567 PackageManager.VERIFICATION_REJECT, 1568 state.getInstallArgs().getUser()); 1569 } 1570 1571 Trace.asyncTraceEnd( 1572 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1573 1574 processPendingInstall(args, ret); 1575 mHandler.sendEmptyMessage(MCS_UNBIND); 1576 } 1577 break; 1578 } 1579 case PACKAGE_VERIFIED: { 1580 final int verificationId = msg.arg1; 1581 1582 final PackageVerificationState state = mPendingVerification.get(verificationId); 1583 if (state == null) { 1584 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1585 break; 1586 } 1587 1588 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1589 1590 state.setVerifierResponse(response.callerUid, response.code); 1591 1592 if (state.isVerificationComplete()) { 1593 mPendingVerification.remove(verificationId); 1594 1595 final InstallArgs args = state.getInstallArgs(); 1596 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1597 1598 int ret; 1599 if (state.isInstallAllowed()) { 1600 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1601 broadcastPackageVerified(verificationId, originUri, 1602 response.code, state.getInstallArgs().getUser()); 1603 try { 1604 ret = args.copyApk(mContainerService, true); 1605 } catch (RemoteException e) { 1606 Slog.e(TAG, "Could not contact the ContainerService"); 1607 } 1608 } else { 1609 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1610 } 1611 1612 Trace.asyncTraceEnd( 1613 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1614 1615 processPendingInstall(args, ret); 1616 mHandler.sendEmptyMessage(MCS_UNBIND); 1617 } 1618 1619 break; 1620 } 1621 case START_INTENT_FILTER_VERIFICATIONS: { 1622 IFVerificationParams params = (IFVerificationParams) msg.obj; 1623 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1624 params.replacing, params.pkg); 1625 break; 1626 } 1627 case INTENT_FILTER_VERIFIED: { 1628 final int verificationId = msg.arg1; 1629 1630 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1631 verificationId); 1632 if (state == null) { 1633 Slog.w(TAG, "Invalid IntentFilter verification token " 1634 + verificationId + " received"); 1635 break; 1636 } 1637 1638 final int userId = state.getUserId(); 1639 1640 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1641 "Processing IntentFilter verification with token:" 1642 + verificationId + " and userId:" + userId); 1643 1644 final IntentFilterVerificationResponse response = 1645 (IntentFilterVerificationResponse) msg.obj; 1646 1647 state.setVerifierResponse(response.callerUid, response.code); 1648 1649 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1650 "IntentFilter verification with token:" + verificationId 1651 + " and userId:" + userId 1652 + " is settings verifier response with response code:" 1653 + response.code); 1654 1655 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1656 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1657 + response.getFailedDomainsString()); 1658 } 1659 1660 if (state.isVerificationComplete()) { 1661 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1662 } else { 1663 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1664 "IntentFilter verification with token:" + verificationId 1665 + " was not said to be complete"); 1666 } 1667 1668 break; 1669 } 1670 } 1671 } 1672 } 1673 1674 private StorageEventListener mStorageListener = new StorageEventListener() { 1675 @Override 1676 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1677 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1678 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1679 final String volumeUuid = vol.getFsUuid(); 1680 1681 // Clean up any users or apps that were removed or recreated 1682 // while this volume was missing 1683 reconcileUsers(volumeUuid); 1684 reconcileApps(volumeUuid); 1685 1686 // Clean up any install sessions that expired or were 1687 // cancelled while this volume was missing 1688 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1689 1690 loadPrivatePackages(vol); 1691 1692 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1693 unloadPrivatePackages(vol); 1694 } 1695 } 1696 1697 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1698 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1699 updateExternalMediaStatus(true, false); 1700 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1701 updateExternalMediaStatus(false, false); 1702 } 1703 } 1704 } 1705 1706 @Override 1707 public void onVolumeForgotten(String fsUuid) { 1708 if (TextUtils.isEmpty(fsUuid)) { 1709 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1710 return; 1711 } 1712 1713 // Remove any apps installed on the forgotten volume 1714 synchronized (mPackages) { 1715 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1716 for (PackageSetting ps : packages) { 1717 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1718 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1719 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1720 } 1721 1722 mSettings.onVolumeForgotten(fsUuid); 1723 mSettings.writeLPr(); 1724 } 1725 } 1726 }; 1727 1728 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1729 String[] grantedPermissions) { 1730 if (userId >= UserHandle.USER_SYSTEM) { 1731 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1732 } else if (userId == UserHandle.USER_ALL) { 1733 final int[] userIds; 1734 synchronized (mPackages) { 1735 userIds = UserManagerService.getInstance().getUserIds(); 1736 } 1737 for (int someUserId : userIds) { 1738 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1739 } 1740 } 1741 1742 // We could have touched GID membership, so flush out packages.list 1743 synchronized (mPackages) { 1744 mSettings.writePackageListLPr(); 1745 } 1746 } 1747 1748 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1749 String[] grantedPermissions) { 1750 SettingBase sb = (SettingBase) pkg.mExtras; 1751 if (sb == null) { 1752 return; 1753 } 1754 1755 PermissionsState permissionsState = sb.getPermissionsState(); 1756 1757 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1758 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1759 1760 synchronized (mPackages) { 1761 for (String permission : pkg.requestedPermissions) { 1762 BasePermission bp = mSettings.mPermissions.get(permission); 1763 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1764 && (grantedPermissions == null 1765 || ArrayUtils.contains(grantedPermissions, permission))) { 1766 final int flags = permissionsState.getPermissionFlags(permission, userId); 1767 // Installer cannot change immutable permissions. 1768 if ((flags & immutableFlags) == 0) { 1769 grantRuntimePermission(pkg.packageName, permission, userId); 1770 } 1771 } 1772 } 1773 } 1774 } 1775 1776 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1777 Bundle extras = null; 1778 switch (res.returnCode) { 1779 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1780 extras = new Bundle(); 1781 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1782 res.origPermission); 1783 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1784 res.origPackage); 1785 break; 1786 } 1787 case PackageManager.INSTALL_SUCCEEDED: { 1788 extras = new Bundle(); 1789 extras.putBoolean(Intent.EXTRA_REPLACING, 1790 res.removedInfo != null && res.removedInfo.removedPackage != null); 1791 break; 1792 } 1793 } 1794 return extras; 1795 } 1796 1797 void scheduleWriteSettingsLocked() { 1798 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1799 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1800 } 1801 } 1802 1803 void scheduleWritePackageRestrictionsLocked(int userId) { 1804 if (!sUserManager.exists(userId)) return; 1805 mDirtyUsers.add(userId); 1806 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1807 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1808 } 1809 } 1810 1811 public static PackageManagerService main(Context context, Installer installer, 1812 boolean factoryTest, boolean onlyCore) { 1813 PackageManagerService m = new PackageManagerService(context, installer, 1814 factoryTest, onlyCore); 1815 ServiceManager.addService("package", m); 1816 return m; 1817 } 1818 1819 static String[] splitString(String str, char sep) { 1820 int count = 1; 1821 int i = 0; 1822 while ((i=str.indexOf(sep, i)) >= 0) { 1823 count++; 1824 i++; 1825 } 1826 1827 String[] res = new String[count]; 1828 i=0; 1829 count = 0; 1830 int lastI=0; 1831 while ((i=str.indexOf(sep, i)) >= 0) { 1832 res[count] = str.substring(lastI, i); 1833 count++; 1834 i++; 1835 lastI = i; 1836 } 1837 res[count] = str.substring(lastI, str.length()); 1838 return res; 1839 } 1840 1841 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1842 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1843 Context.DISPLAY_SERVICE); 1844 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1845 } 1846 1847 public PackageManagerService(Context context, Installer installer, 1848 boolean factoryTest, boolean onlyCore) { 1849 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1850 SystemClock.uptimeMillis()); 1851 1852 if (mSdkVersion <= 0) { 1853 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1854 } 1855 1856 mContext = context; 1857 mFactoryTest = factoryTest; 1858 mOnlyCore = onlyCore; 1859 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1860 mMetrics = new DisplayMetrics(); 1861 mSettings = new Settings(mPackages); 1862 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1863 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1864 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1865 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1866 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1867 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1868 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1869 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1870 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1871 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1872 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1873 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1874 1875 // TODO: add a property to control this? 1876 long dexOptLRUThresholdInMinutes; 1877 if (mLazyDexOpt) { 1878 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1879 } else { 1880 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1881 } 1882 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1883 1884 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1885 if (separateProcesses != null && separateProcesses.length() > 0) { 1886 if ("*".equals(separateProcesses)) { 1887 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1888 mSeparateProcesses = null; 1889 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1890 } else { 1891 mDefParseFlags = 0; 1892 mSeparateProcesses = separateProcesses.split(","); 1893 Slog.w(TAG, "Running with debug.separate_processes: " 1894 + separateProcesses); 1895 } 1896 } else { 1897 mDefParseFlags = 0; 1898 mSeparateProcesses = null; 1899 } 1900 1901 mInstaller = installer; 1902 mPackageDexOptimizer = new PackageDexOptimizer(this); 1903 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1904 1905 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1906 FgThread.get().getLooper()); 1907 1908 getDefaultDisplayMetrics(context, mMetrics); 1909 1910 SystemConfig systemConfig = SystemConfig.getInstance(); 1911 mGlobalGids = systemConfig.getGlobalGids(); 1912 mSystemPermissions = systemConfig.getSystemPermissions(); 1913 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1914 1915 synchronized (mInstallLock) { 1916 // writer 1917 synchronized (mPackages) { 1918 mHandlerThread = new ServiceThread(TAG, 1919 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1920 mHandlerThread.start(); 1921 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1922 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1923 1924 File dataDir = Environment.getDataDirectory(); 1925 mAppDataDir = new File(dataDir, "data"); 1926 mAppInstallDir = new File(dataDir, "app"); 1927 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1928 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1929 mUserAppDataDir = new File(dataDir, "user"); 1930 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1931 1932 sUserManager = new UserManagerService(context, this, 1933 mInstallLock, mPackages); 1934 1935 // Propagate permission configuration in to package manager. 1936 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1937 = systemConfig.getPermissions(); 1938 for (int i=0; i<permConfig.size(); i++) { 1939 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1940 BasePermission bp = mSettings.mPermissions.get(perm.name); 1941 if (bp == null) { 1942 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1943 mSettings.mPermissions.put(perm.name, bp); 1944 } 1945 if (perm.gids != null) { 1946 bp.setGids(perm.gids, perm.perUser); 1947 } 1948 } 1949 1950 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1951 for (int i=0; i<libConfig.size(); i++) { 1952 mSharedLibraries.put(libConfig.keyAt(i), 1953 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1954 } 1955 1956 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1957 1958 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1959 1960 String customResolverActivity = Resources.getSystem().getString( 1961 R.string.config_customResolverActivity); 1962 if (TextUtils.isEmpty(customResolverActivity)) { 1963 customResolverActivity = null; 1964 } else { 1965 mCustomResolverComponentName = ComponentName.unflattenFromString( 1966 customResolverActivity); 1967 } 1968 1969 long startTime = SystemClock.uptimeMillis(); 1970 1971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1972 startTime); 1973 1974 // Set flag to monitor and not change apk file paths when 1975 // scanning install directories. 1976 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1977 1978 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1979 1980 /** 1981 * Add everything in the in the boot class path to the 1982 * list of process files because dexopt will have been run 1983 * if necessary during zygote startup. 1984 */ 1985 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1986 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1987 1988 if (bootClassPath != null) { 1989 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1990 for (String element : bootClassPathElements) { 1991 alreadyDexOpted.add(element); 1992 } 1993 } else { 1994 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1995 } 1996 1997 if (systemServerClassPath != null) { 1998 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1999 for (String element : systemServerClassPathElements) { 2000 alreadyDexOpted.add(element); 2001 } 2002 } else { 2003 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2004 } 2005 2006 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2007 final String[] dexCodeInstructionSets = 2008 getDexCodeInstructionSets( 2009 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2010 2011 /** 2012 * Ensure all external libraries have had dexopt run on them. 2013 */ 2014 if (mSharedLibraries.size() > 0) { 2015 // NOTE: For now, we're compiling these system "shared libraries" 2016 // (and framework jars) into all available architectures. It's possible 2017 // to compile them only when we come across an app that uses them (there's 2018 // already logic for that in scanPackageLI) but that adds some complexity. 2019 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2020 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2021 final String lib = libEntry.path; 2022 if (lib == null) { 2023 continue; 2024 } 2025 2026 try { 2027 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2028 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2029 alreadyDexOpted.add(lib); 2030 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2031 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2032 } 2033 } catch (FileNotFoundException e) { 2034 Slog.w(TAG, "Library not found: " + lib); 2035 } catch (IOException e) { 2036 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2037 + e.getMessage()); 2038 } 2039 } 2040 } 2041 } 2042 2043 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2044 2045 // Gross hack for now: we know this file doesn't contain any 2046 // code, so don't dexopt it to avoid the resulting log spew. 2047 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2048 2049 // Gross hack for now: we know this file is only part of 2050 // the boot class path for art, so don't dexopt it to 2051 // avoid the resulting log spew. 2052 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2053 2054 /** 2055 * There are a number of commands implemented in Java, which 2056 * we currently need to do the dexopt on so that they can be 2057 * run from a non-root shell. 2058 */ 2059 String[] frameworkFiles = frameworkDir.list(); 2060 if (frameworkFiles != null) { 2061 // TODO: We could compile these only for the most preferred ABI. We should 2062 // first double check that the dex files for these commands are not referenced 2063 // by other system apps. 2064 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2065 for (int i=0; i<frameworkFiles.length; i++) { 2066 File libPath = new File(frameworkDir, frameworkFiles[i]); 2067 String path = libPath.getPath(); 2068 // Skip the file if we already did it. 2069 if (alreadyDexOpted.contains(path)) { 2070 continue; 2071 } 2072 // Skip the file if it is not a type we want to dexopt. 2073 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2074 continue; 2075 } 2076 try { 2077 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2078 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2079 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2080 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2081 } 2082 } catch (FileNotFoundException e) { 2083 Slog.w(TAG, "Jar not found: " + path); 2084 } catch (IOException e) { 2085 Slog.w(TAG, "Exception reading jar: " + path, e); 2086 } 2087 } 2088 } 2089 } 2090 2091 final VersionInfo ver = mSettings.getInternalVersion(); 2092 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2093 // when upgrading from pre-M, promote system app permissions from install to runtime 2094 mPromoteSystemApps = 2095 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2096 2097 // save off the names of pre-existing system packages prior to scanning; we don't 2098 // want to automatically grant runtime permissions for new system apps 2099 if (mPromoteSystemApps) { 2100 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2101 while (pkgSettingIter.hasNext()) { 2102 PackageSetting ps = pkgSettingIter.next(); 2103 if (isSystemApp(ps)) { 2104 mExistingSystemPackages.add(ps.name); 2105 } 2106 } 2107 } 2108 2109 // Collect vendor overlay packages. 2110 // (Do this before scanning any apps.) 2111 // For security and version matching reason, only consider 2112 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2113 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2114 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2116 2117 // Find base frameworks (resource packages without code). 2118 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2119 | PackageParser.PARSE_IS_SYSTEM_DIR 2120 | PackageParser.PARSE_IS_PRIVILEGED, 2121 scanFlags | SCAN_NO_DEX, 0); 2122 2123 // Collected privileged system packages. 2124 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2125 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2126 | PackageParser.PARSE_IS_SYSTEM_DIR 2127 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2128 2129 // Collect ordinary system packages. 2130 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2131 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2132 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2133 2134 // Collect all vendor packages. 2135 File vendorAppDir = new File("/vendor/app"); 2136 try { 2137 vendorAppDir = vendorAppDir.getCanonicalFile(); 2138 } catch (IOException e) { 2139 // failed to look up canonical path, continue with original one 2140 } 2141 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2142 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2143 2144 // Collect all OEM packages. 2145 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2146 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2147 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2148 2149 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2150 mInstaller.moveFiles(); 2151 2152 // Prune any system packages that no longer exist. 2153 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2154 if (!mOnlyCore) { 2155 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2156 while (psit.hasNext()) { 2157 PackageSetting ps = psit.next(); 2158 2159 /* 2160 * If this is not a system app, it can't be a 2161 * disable system app. 2162 */ 2163 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2164 continue; 2165 } 2166 2167 /* 2168 * If the package is scanned, it's not erased. 2169 */ 2170 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2171 if (scannedPkg != null) { 2172 /* 2173 * If the system app is both scanned and in the 2174 * disabled packages list, then it must have been 2175 * added via OTA. Remove it from the currently 2176 * scanned package so the previously user-installed 2177 * application can be scanned. 2178 */ 2179 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2180 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2181 + ps.name + "; removing system app. Last known codePath=" 2182 + ps.codePathString + ", installStatus=" + ps.installStatus 2183 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2184 + scannedPkg.mVersionCode); 2185 removePackageLI(ps, true); 2186 mExpectingBetter.put(ps.name, ps.codePath); 2187 } 2188 2189 continue; 2190 } 2191 2192 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2193 psit.remove(); 2194 logCriticalInfo(Log.WARN, "System package " + ps.name 2195 + " no longer exists; wiping its data"); 2196 removeDataDirsLI(null, ps.name); 2197 } else { 2198 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2199 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2200 possiblyDeletedUpdatedSystemApps.add(ps.name); 2201 } 2202 } 2203 } 2204 } 2205 2206 //look for any incomplete package installations 2207 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2208 //clean up list 2209 for(int i = 0; i < deletePkgsList.size(); i++) { 2210 //clean up here 2211 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2212 } 2213 //delete tmp files 2214 deleteTempPackageFiles(); 2215 2216 // Remove any shared userIDs that have no associated packages 2217 mSettings.pruneSharedUsersLPw(); 2218 2219 if (!mOnlyCore) { 2220 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2221 SystemClock.uptimeMillis()); 2222 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2223 2224 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2225 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2226 2227 /** 2228 * Remove disable package settings for any updated system 2229 * apps that were removed via an OTA. If they're not a 2230 * previously-updated app, remove them completely. 2231 * Otherwise, just revoke their system-level permissions. 2232 */ 2233 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2234 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2235 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2236 2237 String msg; 2238 if (deletedPkg == null) { 2239 msg = "Updated system package " + deletedAppName 2240 + " no longer exists; wiping its data"; 2241 removeDataDirsLI(null, deletedAppName); 2242 } else { 2243 msg = "Updated system app + " + deletedAppName 2244 + " no longer present; removing system privileges for " 2245 + deletedAppName; 2246 2247 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2248 2249 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2250 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2251 } 2252 logCriticalInfo(Log.WARN, msg); 2253 } 2254 2255 /** 2256 * Make sure all system apps that we expected to appear on 2257 * the userdata partition actually showed up. If they never 2258 * appeared, crawl back and revive the system version. 2259 */ 2260 for (int i = 0; i < mExpectingBetter.size(); i++) { 2261 final String packageName = mExpectingBetter.keyAt(i); 2262 if (!mPackages.containsKey(packageName)) { 2263 final File scanFile = mExpectingBetter.valueAt(i); 2264 2265 logCriticalInfo(Log.WARN, "Expected better " + packageName 2266 + " but never showed up; reverting to system"); 2267 2268 final int reparseFlags; 2269 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2270 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2271 | PackageParser.PARSE_IS_SYSTEM_DIR 2272 | PackageParser.PARSE_IS_PRIVILEGED; 2273 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2274 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2275 | PackageParser.PARSE_IS_SYSTEM_DIR; 2276 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2277 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2278 | PackageParser.PARSE_IS_SYSTEM_DIR; 2279 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2280 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2281 | PackageParser.PARSE_IS_SYSTEM_DIR; 2282 } else { 2283 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2284 continue; 2285 } 2286 2287 mSettings.enableSystemPackageLPw(packageName); 2288 2289 try { 2290 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2291 } catch (PackageManagerException e) { 2292 Slog.e(TAG, "Failed to parse original system package: " 2293 + e.getMessage()); 2294 } 2295 } 2296 } 2297 } 2298 mExpectingBetter.clear(); 2299 2300 // Now that we know all of the shared libraries, update all clients to have 2301 // the correct library paths. 2302 updateAllSharedLibrariesLPw(); 2303 2304 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2305 // NOTE: We ignore potential failures here during a system scan (like 2306 // the rest of the commands above) because there's precious little we 2307 // can do about it. A settings error is reported, though. 2308 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2309 false /* force dexopt */, false /* defer dexopt */, 2310 false /* boot complete */); 2311 } 2312 2313 // Now that we know all the packages we are keeping, 2314 // read and update their last usage times. 2315 mPackageUsage.readLP(); 2316 2317 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2318 SystemClock.uptimeMillis()); 2319 Slog.i(TAG, "Time to scan packages: " 2320 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2321 + " seconds"); 2322 2323 // If the platform SDK has changed since the last time we booted, 2324 // we need to re-grant app permission to catch any new ones that 2325 // appear. This is really a hack, and means that apps can in some 2326 // cases get permissions that the user didn't initially explicitly 2327 // allow... it would be nice to have some better way to handle 2328 // this situation. 2329 int updateFlags = UPDATE_PERMISSIONS_ALL; 2330 if (ver.sdkVersion != mSdkVersion) { 2331 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2332 + mSdkVersion + "; regranting permissions for internal storage"); 2333 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2334 } 2335 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2336 ver.sdkVersion = mSdkVersion; 2337 2338 // If this is the first boot or an update from pre-M, and it is a normal 2339 // boot, then we need to initialize the default preferred apps across 2340 // all defined users. 2341 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2342 for (UserInfo user : sUserManager.getUsers(true)) { 2343 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2344 applyFactoryDefaultBrowserLPw(user.id); 2345 primeDomainVerificationsLPw(user.id); 2346 } 2347 } 2348 2349 // If this is first boot after an OTA, and a normal boot, then 2350 // we need to clear code cache directories. 2351 if (mIsUpgrade && !onlyCore) { 2352 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2353 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2354 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2355 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2356 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2357 } 2358 } 2359 ver.fingerprint = Build.FINGERPRINT; 2360 } 2361 2362 checkDefaultBrowser(); 2363 2364 // clear only after permissions and other defaults have been updated 2365 mExistingSystemPackages.clear(); 2366 mPromoteSystemApps = false; 2367 2368 // All the changes are done during package scanning. 2369 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2370 2371 // can downgrade to reader 2372 mSettings.writeLPr(); 2373 2374 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2375 SystemClock.uptimeMillis()); 2376 2377 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2378 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2379 2380 mInstallerService = new PackageInstallerService(context, this); 2381 2382 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2383 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2384 mIntentFilterVerifierComponent); 2385 2386 } // synchronized (mPackages) 2387 } // synchronized (mInstallLock) 2388 2389 // Now after opening every single application zip, make sure they 2390 // are all flushed. Not really needed, but keeps things nice and 2391 // tidy. 2392 Runtime.getRuntime().gc(); 2393 2394 // The initial scanning above does many calls into installd while 2395 // holding the mPackages lock, but we're mostly interested in yelling 2396 // once we have a booted system. 2397 mInstaller.setWarnIfHeld(mPackages); 2398 2399 // Expose private service for system components to use. 2400 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2401 } 2402 2403 @Override 2404 public boolean isFirstBoot() { 2405 return !mRestoredSettings; 2406 } 2407 2408 @Override 2409 public boolean isOnlyCoreApps() { 2410 return mOnlyCore; 2411 } 2412 2413 @Override 2414 public boolean isUpgrade() { 2415 return mIsUpgrade; 2416 } 2417 2418 private String getRequiredVerifierLPr() { 2419 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2420 // We only care about verifier that's installed under system user. 2421 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2422 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2423 2424 String requiredVerifier = null; 2425 2426 final int N = receivers.size(); 2427 for (int i = 0; i < N; i++) { 2428 final ResolveInfo info = receivers.get(i); 2429 2430 if (info.activityInfo == null) { 2431 continue; 2432 } 2433 2434 final String packageName = info.activityInfo.packageName; 2435 2436 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2437 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2438 continue; 2439 } 2440 2441 if (requiredVerifier != null) { 2442 throw new RuntimeException("There can be only one required verifier"); 2443 } 2444 2445 requiredVerifier = packageName; 2446 } 2447 2448 return requiredVerifier; 2449 } 2450 2451 private String getRequiredInstallerLPr() { 2452 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2453 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2454 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2455 2456 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2457 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2458 2459 String requiredInstaller = null; 2460 2461 final int N = installers.size(); 2462 for (int i = 0; i < N; i++) { 2463 final ResolveInfo info = installers.get(i); 2464 final String packageName = info.activityInfo.packageName; 2465 2466 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2467 continue; 2468 } 2469 2470 if (requiredInstaller != null) { 2471 throw new RuntimeException("There must be one required installer"); 2472 } 2473 2474 requiredInstaller = packageName; 2475 } 2476 2477 if (requiredInstaller == null) { 2478 throw new RuntimeException("There must be one required installer"); 2479 } 2480 2481 return requiredInstaller; 2482 } 2483 2484 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2485 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2486 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2487 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2488 2489 ComponentName verifierComponentName = null; 2490 2491 int priority = -1000; 2492 final int N = receivers.size(); 2493 for (int i = 0; i < N; i++) { 2494 final ResolveInfo info = receivers.get(i); 2495 2496 if (info.activityInfo == null) { 2497 continue; 2498 } 2499 2500 final String packageName = info.activityInfo.packageName; 2501 2502 final PackageSetting ps = mSettings.mPackages.get(packageName); 2503 if (ps == null) { 2504 continue; 2505 } 2506 2507 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2508 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2509 continue; 2510 } 2511 2512 // Select the IntentFilterVerifier with the highest priority 2513 if (priority < info.priority) { 2514 priority = info.priority; 2515 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2516 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2517 + verifierComponentName + " with priority: " + info.priority); 2518 } 2519 } 2520 2521 return verifierComponentName; 2522 } 2523 2524 private void primeDomainVerificationsLPw(int userId) { 2525 if (DEBUG_DOMAIN_VERIFICATION) { 2526 Slog.d(TAG, "Priming domain verifications in user " + userId); 2527 } 2528 2529 SystemConfig systemConfig = SystemConfig.getInstance(); 2530 ArraySet<String> packages = systemConfig.getLinkedApps(); 2531 ArraySet<String> domains = new ArraySet<String>(); 2532 2533 for (String packageName : packages) { 2534 PackageParser.Package pkg = mPackages.get(packageName); 2535 if (pkg != null) { 2536 if (!pkg.isSystemApp()) { 2537 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2538 continue; 2539 } 2540 2541 domains.clear(); 2542 for (PackageParser.Activity a : pkg.activities) { 2543 for (ActivityIntentInfo filter : a.intents) { 2544 if (hasValidDomains(filter)) { 2545 domains.addAll(filter.getHostsList()); 2546 } 2547 } 2548 } 2549 2550 if (domains.size() > 0) { 2551 if (DEBUG_DOMAIN_VERIFICATION) { 2552 Slog.v(TAG, " + " + packageName); 2553 } 2554 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2555 // state w.r.t. the formal app-linkage "no verification attempted" state; 2556 // and then 'always' in the per-user state actually used for intent resolution. 2557 final IntentFilterVerificationInfo ivi; 2558 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2559 new ArrayList<String>(domains)); 2560 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2561 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2562 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2563 } else { 2564 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2565 + "' does not handle web links"); 2566 } 2567 } else { 2568 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2569 } 2570 } 2571 2572 scheduleWritePackageRestrictionsLocked(userId); 2573 scheduleWriteSettingsLocked(); 2574 } 2575 2576 private void applyFactoryDefaultBrowserLPw(int userId) { 2577 // The default browser app's package name is stored in a string resource, 2578 // with a product-specific overlay used for vendor customization. 2579 String browserPkg = mContext.getResources().getString( 2580 com.android.internal.R.string.default_browser); 2581 if (!TextUtils.isEmpty(browserPkg)) { 2582 // non-empty string => required to be a known package 2583 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2584 if (ps == null) { 2585 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2586 browserPkg = null; 2587 } else { 2588 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2589 } 2590 } 2591 2592 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2593 // default. If there's more than one, just leave everything alone. 2594 if (browserPkg == null) { 2595 calculateDefaultBrowserLPw(userId); 2596 } 2597 } 2598 2599 private void calculateDefaultBrowserLPw(int userId) { 2600 List<String> allBrowsers = resolveAllBrowserApps(userId); 2601 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2602 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2603 } 2604 2605 private List<String> resolveAllBrowserApps(int userId) { 2606 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2607 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2608 PackageManager.MATCH_ALL, userId); 2609 2610 final int count = list.size(); 2611 List<String> result = new ArrayList<String>(count); 2612 for (int i=0; i<count; i++) { 2613 ResolveInfo info = list.get(i); 2614 if (info.activityInfo == null 2615 || !info.handleAllWebDataURI 2616 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2617 || result.contains(info.activityInfo.packageName)) { 2618 continue; 2619 } 2620 result.add(info.activityInfo.packageName); 2621 } 2622 2623 return result; 2624 } 2625 2626 private boolean packageIsBrowser(String packageName, int userId) { 2627 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2628 PackageManager.MATCH_ALL, userId); 2629 final int N = list.size(); 2630 for (int i = 0; i < N; i++) { 2631 ResolveInfo info = list.get(i); 2632 if (packageName.equals(info.activityInfo.packageName)) { 2633 return true; 2634 } 2635 } 2636 return false; 2637 } 2638 2639 private void checkDefaultBrowser() { 2640 final int myUserId = UserHandle.myUserId(); 2641 final String packageName = getDefaultBrowserPackageName(myUserId); 2642 if (packageName != null) { 2643 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2644 if (info == null) { 2645 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2646 synchronized (mPackages) { 2647 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2648 } 2649 } 2650 } 2651 } 2652 2653 @Override 2654 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2655 throws RemoteException { 2656 try { 2657 return super.onTransact(code, data, reply, flags); 2658 } catch (RuntimeException e) { 2659 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2660 Slog.wtf(TAG, "Package Manager Crash", e); 2661 } 2662 throw e; 2663 } 2664 } 2665 2666 void cleanupInstallFailedPackage(PackageSetting ps) { 2667 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2668 2669 removeDataDirsLI(ps.volumeUuid, ps.name); 2670 if (ps.codePath != null) { 2671 if (ps.codePath.isDirectory()) { 2672 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2673 } else { 2674 ps.codePath.delete(); 2675 } 2676 } 2677 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2678 if (ps.resourcePath.isDirectory()) { 2679 FileUtils.deleteContents(ps.resourcePath); 2680 } 2681 ps.resourcePath.delete(); 2682 } 2683 mSettings.removePackageLPw(ps.name); 2684 } 2685 2686 static int[] appendInts(int[] cur, int[] add) { 2687 if (add == null) return cur; 2688 if (cur == null) return add; 2689 final int N = add.length; 2690 for (int i=0; i<N; i++) { 2691 cur = appendInt(cur, add[i]); 2692 } 2693 return cur; 2694 } 2695 2696 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2697 if (!sUserManager.exists(userId)) return null; 2698 final PackageSetting ps = (PackageSetting) p.mExtras; 2699 if (ps == null) { 2700 return null; 2701 } 2702 2703 final PermissionsState permissionsState = ps.getPermissionsState(); 2704 2705 final int[] gids = permissionsState.computeGids(userId); 2706 final Set<String> permissions = permissionsState.getPermissions(userId); 2707 final PackageUserState state = ps.readUserState(userId); 2708 2709 return PackageParser.generatePackageInfo(p, gids, flags, 2710 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2711 } 2712 2713 @Override 2714 public boolean isPackageFrozen(String packageName) { 2715 synchronized (mPackages) { 2716 final PackageSetting ps = mSettings.mPackages.get(packageName); 2717 if (ps != null) { 2718 return ps.frozen; 2719 } 2720 } 2721 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2722 return true; 2723 } 2724 2725 @Override 2726 public boolean isPackageAvailable(String packageName, int userId) { 2727 if (!sUserManager.exists(userId)) return false; 2728 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2729 synchronized (mPackages) { 2730 PackageParser.Package p = mPackages.get(packageName); 2731 if (p != null) { 2732 final PackageSetting ps = (PackageSetting) p.mExtras; 2733 if (ps != null) { 2734 final PackageUserState state = ps.readUserState(userId); 2735 if (state != null) { 2736 return PackageParser.isAvailable(state); 2737 } 2738 } 2739 } 2740 } 2741 return false; 2742 } 2743 2744 @Override 2745 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2746 if (!sUserManager.exists(userId)) return null; 2747 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2748 // reader 2749 synchronized (mPackages) { 2750 PackageParser.Package p = mPackages.get(packageName); 2751 if (DEBUG_PACKAGE_INFO) 2752 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2753 if (p != null) { 2754 return generatePackageInfo(p, flags, userId); 2755 } 2756 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2757 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2758 } 2759 } 2760 return null; 2761 } 2762 2763 @Override 2764 public String[] currentToCanonicalPackageNames(String[] names) { 2765 String[] out = new String[names.length]; 2766 // reader 2767 synchronized (mPackages) { 2768 for (int i=names.length-1; i>=0; i--) { 2769 PackageSetting ps = mSettings.mPackages.get(names[i]); 2770 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2771 } 2772 } 2773 return out; 2774 } 2775 2776 @Override 2777 public String[] canonicalToCurrentPackageNames(String[] names) { 2778 String[] out = new String[names.length]; 2779 // reader 2780 synchronized (mPackages) { 2781 for (int i=names.length-1; i>=0; i--) { 2782 String cur = mSettings.mRenamedPackages.get(names[i]); 2783 out[i] = cur != null ? cur : names[i]; 2784 } 2785 } 2786 return out; 2787 } 2788 2789 @Override 2790 public int getPackageUid(String packageName, int userId) { 2791 return getPackageUidEtc(packageName, 0, userId); 2792 } 2793 2794 @Override 2795 public int getPackageUidEtc(String packageName, int flags, int userId) { 2796 if (!sUserManager.exists(userId)) return -1; 2797 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2798 2799 // reader 2800 synchronized (mPackages) { 2801 final PackageParser.Package p = mPackages.get(packageName); 2802 if (p != null) { 2803 return UserHandle.getUid(userId, p.applicationInfo.uid); 2804 } 2805 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2806 final PackageSetting ps = mSettings.mPackages.get(packageName); 2807 if (ps != null) { 2808 return UserHandle.getUid(userId, ps.appId); 2809 } 2810 } 2811 } 2812 2813 return -1; 2814 } 2815 2816 @Override 2817 public int[] getPackageGids(String packageName, int userId) { 2818 return getPackageGidsEtc(packageName, 0, userId); 2819 } 2820 2821 @Override 2822 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2823 if (!sUserManager.exists(userId)) { 2824 return null; 2825 } 2826 2827 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2828 "getPackageGids"); 2829 2830 // reader 2831 synchronized (mPackages) { 2832 final PackageParser.Package p = mPackages.get(packageName); 2833 if (p != null) { 2834 PackageSetting ps = (PackageSetting) p.mExtras; 2835 return ps.getPermissionsState().computeGids(userId); 2836 } 2837 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2838 final PackageSetting ps = mSettings.mPackages.get(packageName); 2839 if (ps != null) { 2840 return ps.getPermissionsState().computeGids(userId); 2841 } 2842 } 2843 } 2844 2845 return null; 2846 } 2847 2848 static PermissionInfo generatePermissionInfo( 2849 BasePermission bp, int flags) { 2850 if (bp.perm != null) { 2851 return PackageParser.generatePermissionInfo(bp.perm, flags); 2852 } 2853 PermissionInfo pi = new PermissionInfo(); 2854 pi.name = bp.name; 2855 pi.packageName = bp.sourcePackage; 2856 pi.nonLocalizedLabel = bp.name; 2857 pi.protectionLevel = bp.protectionLevel; 2858 return pi; 2859 } 2860 2861 @Override 2862 public PermissionInfo getPermissionInfo(String name, int flags) { 2863 // reader 2864 synchronized (mPackages) { 2865 final BasePermission p = mSettings.mPermissions.get(name); 2866 if (p != null) { 2867 return generatePermissionInfo(p, flags); 2868 } 2869 return null; 2870 } 2871 } 2872 2873 @Override 2874 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2875 // reader 2876 synchronized (mPackages) { 2877 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2878 for (BasePermission p : mSettings.mPermissions.values()) { 2879 if (group == null) { 2880 if (p.perm == null || p.perm.info.group == null) { 2881 out.add(generatePermissionInfo(p, flags)); 2882 } 2883 } else { 2884 if (p.perm != null && group.equals(p.perm.info.group)) { 2885 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2886 } 2887 } 2888 } 2889 2890 if (out.size() > 0) { 2891 return out; 2892 } 2893 return mPermissionGroups.containsKey(group) ? out : null; 2894 } 2895 } 2896 2897 @Override 2898 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2899 // reader 2900 synchronized (mPackages) { 2901 return PackageParser.generatePermissionGroupInfo( 2902 mPermissionGroups.get(name), flags); 2903 } 2904 } 2905 2906 @Override 2907 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2908 // reader 2909 synchronized (mPackages) { 2910 final int N = mPermissionGroups.size(); 2911 ArrayList<PermissionGroupInfo> out 2912 = new ArrayList<PermissionGroupInfo>(N); 2913 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2914 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2915 } 2916 return out; 2917 } 2918 } 2919 2920 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2921 int userId) { 2922 if (!sUserManager.exists(userId)) return null; 2923 PackageSetting ps = mSettings.mPackages.get(packageName); 2924 if (ps != null) { 2925 if (ps.pkg == null) { 2926 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2927 flags, userId); 2928 if (pInfo != null) { 2929 return pInfo.applicationInfo; 2930 } 2931 return null; 2932 } 2933 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2934 ps.readUserState(userId), userId); 2935 } 2936 return null; 2937 } 2938 2939 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2940 int userId) { 2941 if (!sUserManager.exists(userId)) return null; 2942 PackageSetting ps = mSettings.mPackages.get(packageName); 2943 if (ps != null) { 2944 PackageParser.Package pkg = ps.pkg; 2945 if (pkg == null) { 2946 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2947 return null; 2948 } 2949 // Only data remains, so we aren't worried about code paths 2950 pkg = new PackageParser.Package(packageName); 2951 pkg.applicationInfo.packageName = packageName; 2952 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2953 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2954 pkg.applicationInfo.uid = ps.appId; 2955 pkg.applicationInfo.initForUser(userId); 2956 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2957 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2958 } 2959 return generatePackageInfo(pkg, flags, userId); 2960 } 2961 return null; 2962 } 2963 2964 @Override 2965 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2966 if (!sUserManager.exists(userId)) return null; 2967 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2968 // writer 2969 synchronized (mPackages) { 2970 PackageParser.Package p = mPackages.get(packageName); 2971 if (DEBUG_PACKAGE_INFO) Log.v( 2972 TAG, "getApplicationInfo " + packageName 2973 + ": " + p); 2974 if (p != null) { 2975 PackageSetting ps = mSettings.mPackages.get(packageName); 2976 if (ps == null) return null; 2977 // Note: isEnabledLP() does not apply here - always return info 2978 return PackageParser.generateApplicationInfo( 2979 p, flags, ps.readUserState(userId), userId); 2980 } 2981 if ("android".equals(packageName)||"system".equals(packageName)) { 2982 return mAndroidApplication; 2983 } 2984 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2985 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2986 } 2987 } 2988 return null; 2989 } 2990 2991 @Override 2992 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2993 final IPackageDataObserver observer) { 2994 mContext.enforceCallingOrSelfPermission( 2995 android.Manifest.permission.CLEAR_APP_CACHE, null); 2996 // Queue up an async operation since clearing cache may take a little while. 2997 mHandler.post(new Runnable() { 2998 public void run() { 2999 mHandler.removeCallbacks(this); 3000 int retCode = -1; 3001 synchronized (mInstallLock) { 3002 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3003 if (retCode < 0) { 3004 Slog.w(TAG, "Couldn't clear application caches"); 3005 } 3006 } 3007 if (observer != null) { 3008 try { 3009 observer.onRemoveCompleted(null, (retCode >= 0)); 3010 } catch (RemoteException e) { 3011 Slog.w(TAG, "RemoveException when invoking call back"); 3012 } 3013 } 3014 } 3015 }); 3016 } 3017 3018 @Override 3019 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3020 final IntentSender pi) { 3021 mContext.enforceCallingOrSelfPermission( 3022 android.Manifest.permission.CLEAR_APP_CACHE, null); 3023 // Queue up an async operation since clearing cache may take a little while. 3024 mHandler.post(new Runnable() { 3025 public void run() { 3026 mHandler.removeCallbacks(this); 3027 int retCode = -1; 3028 synchronized (mInstallLock) { 3029 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3030 if (retCode < 0) { 3031 Slog.w(TAG, "Couldn't clear application caches"); 3032 } 3033 } 3034 if(pi != null) { 3035 try { 3036 // Callback via pending intent 3037 int code = (retCode >= 0) ? 1 : 0; 3038 pi.sendIntent(null, code, null, 3039 null, null); 3040 } catch (SendIntentException e1) { 3041 Slog.i(TAG, "Failed to send pending intent"); 3042 } 3043 } 3044 } 3045 }); 3046 } 3047 3048 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3049 synchronized (mInstallLock) { 3050 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3051 throw new IOException("Failed to free enough space"); 3052 } 3053 } 3054 } 3055 3056 @Override 3057 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3058 if (!sUserManager.exists(userId)) return null; 3059 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3060 synchronized (mPackages) { 3061 PackageParser.Activity a = mActivities.mActivities.get(component); 3062 3063 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3064 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3065 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3066 if (ps == null) return null; 3067 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3068 userId); 3069 } 3070 if (mResolveComponentName.equals(component)) { 3071 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3072 new PackageUserState(), userId); 3073 } 3074 } 3075 return null; 3076 } 3077 3078 @Override 3079 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3080 String resolvedType) { 3081 synchronized (mPackages) { 3082 if (component.equals(mResolveComponentName)) { 3083 // The resolver supports EVERYTHING! 3084 return true; 3085 } 3086 PackageParser.Activity a = mActivities.mActivities.get(component); 3087 if (a == null) { 3088 return false; 3089 } 3090 for (int i=0; i<a.intents.size(); i++) { 3091 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3092 intent.getData(), intent.getCategories(), TAG) >= 0) { 3093 return true; 3094 } 3095 } 3096 return false; 3097 } 3098 } 3099 3100 @Override 3101 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3102 if (!sUserManager.exists(userId)) return null; 3103 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3104 synchronized (mPackages) { 3105 PackageParser.Activity a = mReceivers.mActivities.get(component); 3106 if (DEBUG_PACKAGE_INFO) Log.v( 3107 TAG, "getReceiverInfo " + component + ": " + a); 3108 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3109 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3110 if (ps == null) return null; 3111 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3112 userId); 3113 } 3114 } 3115 return null; 3116 } 3117 3118 @Override 3119 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3120 if (!sUserManager.exists(userId)) return null; 3121 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3122 synchronized (mPackages) { 3123 PackageParser.Service s = mServices.mServices.get(component); 3124 if (DEBUG_PACKAGE_INFO) Log.v( 3125 TAG, "getServiceInfo " + component + ": " + s); 3126 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3127 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3128 if (ps == null) return null; 3129 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3130 userId); 3131 } 3132 } 3133 return null; 3134 } 3135 3136 @Override 3137 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3138 if (!sUserManager.exists(userId)) return null; 3139 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3140 synchronized (mPackages) { 3141 PackageParser.Provider p = mProviders.mProviders.get(component); 3142 if (DEBUG_PACKAGE_INFO) Log.v( 3143 TAG, "getProviderInfo " + component + ": " + p); 3144 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3145 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3146 if (ps == null) return null; 3147 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3148 userId); 3149 } 3150 } 3151 return null; 3152 } 3153 3154 @Override 3155 public String[] getSystemSharedLibraryNames() { 3156 Set<String> libSet; 3157 synchronized (mPackages) { 3158 libSet = mSharedLibraries.keySet(); 3159 int size = libSet.size(); 3160 if (size > 0) { 3161 String[] libs = new String[size]; 3162 libSet.toArray(libs); 3163 return libs; 3164 } 3165 } 3166 return null; 3167 } 3168 3169 /** 3170 * @hide 3171 */ 3172 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3173 synchronized (mPackages) { 3174 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3175 if (lib != null && lib.apk != null) { 3176 return mPackages.get(lib.apk); 3177 } 3178 } 3179 return null; 3180 } 3181 3182 @Override 3183 public FeatureInfo[] getSystemAvailableFeatures() { 3184 Collection<FeatureInfo> featSet; 3185 synchronized (mPackages) { 3186 featSet = mAvailableFeatures.values(); 3187 int size = featSet.size(); 3188 if (size > 0) { 3189 FeatureInfo[] features = new FeatureInfo[size+1]; 3190 featSet.toArray(features); 3191 FeatureInfo fi = new FeatureInfo(); 3192 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3193 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3194 features[size] = fi; 3195 return features; 3196 } 3197 } 3198 return null; 3199 } 3200 3201 @Override 3202 public boolean hasSystemFeature(String name) { 3203 synchronized (mPackages) { 3204 return mAvailableFeatures.containsKey(name); 3205 } 3206 } 3207 3208 private void checkValidCaller(int uid, int userId) { 3209 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3210 return; 3211 3212 throw new SecurityException("Caller uid=" + uid 3213 + " is not privileged to communicate with user=" + userId); 3214 } 3215 3216 @Override 3217 public int checkPermission(String permName, String pkgName, int userId) { 3218 if (!sUserManager.exists(userId)) { 3219 return PackageManager.PERMISSION_DENIED; 3220 } 3221 3222 synchronized (mPackages) { 3223 final PackageParser.Package p = mPackages.get(pkgName); 3224 if (p != null && p.mExtras != null) { 3225 final PackageSetting ps = (PackageSetting) p.mExtras; 3226 final PermissionsState permissionsState = ps.getPermissionsState(); 3227 if (permissionsState.hasPermission(permName, userId)) { 3228 return PackageManager.PERMISSION_GRANTED; 3229 } 3230 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3231 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3232 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3233 return PackageManager.PERMISSION_GRANTED; 3234 } 3235 } 3236 } 3237 3238 return PackageManager.PERMISSION_DENIED; 3239 } 3240 3241 @Override 3242 public int checkUidPermission(String permName, int uid) { 3243 final int userId = UserHandle.getUserId(uid); 3244 3245 if (!sUserManager.exists(userId)) { 3246 return PackageManager.PERMISSION_DENIED; 3247 } 3248 3249 synchronized (mPackages) { 3250 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3251 if (obj != null) { 3252 final SettingBase ps = (SettingBase) obj; 3253 final PermissionsState permissionsState = ps.getPermissionsState(); 3254 if (permissionsState.hasPermission(permName, userId)) { 3255 return PackageManager.PERMISSION_GRANTED; 3256 } 3257 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3258 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3259 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3260 return PackageManager.PERMISSION_GRANTED; 3261 } 3262 } else { 3263 ArraySet<String> perms = mSystemPermissions.get(uid); 3264 if (perms != null) { 3265 if (perms.contains(permName)) { 3266 return PackageManager.PERMISSION_GRANTED; 3267 } 3268 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3269 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3270 return PackageManager.PERMISSION_GRANTED; 3271 } 3272 } 3273 } 3274 } 3275 3276 return PackageManager.PERMISSION_DENIED; 3277 } 3278 3279 @Override 3280 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3281 if (UserHandle.getCallingUserId() != userId) { 3282 mContext.enforceCallingPermission( 3283 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3284 "isPermissionRevokedByPolicy for user " + userId); 3285 } 3286 3287 if (checkPermission(permission, packageName, userId) 3288 == PackageManager.PERMISSION_GRANTED) { 3289 return false; 3290 } 3291 3292 final long identity = Binder.clearCallingIdentity(); 3293 try { 3294 final int flags = getPermissionFlags(permission, packageName, userId); 3295 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3296 } finally { 3297 Binder.restoreCallingIdentity(identity); 3298 } 3299 } 3300 3301 @Override 3302 public String getPermissionControllerPackageName() { 3303 synchronized (mPackages) { 3304 return mRequiredInstallerPackage; 3305 } 3306 } 3307 3308 /** 3309 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3310 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3311 * @param checkShell TODO(yamasani): 3312 * @param message the message to log on security exception 3313 */ 3314 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3315 boolean checkShell, String message) { 3316 if (userId < 0) { 3317 throw new IllegalArgumentException("Invalid userId " + userId); 3318 } 3319 if (checkShell) { 3320 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3321 } 3322 if (userId == UserHandle.getUserId(callingUid)) return; 3323 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3324 if (requireFullPermission) { 3325 mContext.enforceCallingOrSelfPermission( 3326 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3327 } else { 3328 try { 3329 mContext.enforceCallingOrSelfPermission( 3330 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3331 } catch (SecurityException se) { 3332 mContext.enforceCallingOrSelfPermission( 3333 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3334 } 3335 } 3336 } 3337 } 3338 3339 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3340 if (callingUid == Process.SHELL_UID) { 3341 if (userHandle >= 0 3342 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3343 throw new SecurityException("Shell does not have permission to access user " 3344 + userHandle); 3345 } else if (userHandle < 0) { 3346 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3347 + Debug.getCallers(3)); 3348 } 3349 } 3350 } 3351 3352 private BasePermission findPermissionTreeLP(String permName) { 3353 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3354 if (permName.startsWith(bp.name) && 3355 permName.length() > bp.name.length() && 3356 permName.charAt(bp.name.length()) == '.') { 3357 return bp; 3358 } 3359 } 3360 return null; 3361 } 3362 3363 private BasePermission checkPermissionTreeLP(String permName) { 3364 if (permName != null) { 3365 BasePermission bp = findPermissionTreeLP(permName); 3366 if (bp != null) { 3367 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3368 return bp; 3369 } 3370 throw new SecurityException("Calling uid " 3371 + Binder.getCallingUid() 3372 + " is not allowed to add to permission tree " 3373 + bp.name + " owned by uid " + bp.uid); 3374 } 3375 } 3376 throw new SecurityException("No permission tree found for " + permName); 3377 } 3378 3379 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3380 if (s1 == null) { 3381 return s2 == null; 3382 } 3383 if (s2 == null) { 3384 return false; 3385 } 3386 if (s1.getClass() != s2.getClass()) { 3387 return false; 3388 } 3389 return s1.equals(s2); 3390 } 3391 3392 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3393 if (pi1.icon != pi2.icon) return false; 3394 if (pi1.logo != pi2.logo) return false; 3395 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3396 if (!compareStrings(pi1.name, pi2.name)) return false; 3397 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3398 // We'll take care of setting this one. 3399 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3400 // These are not currently stored in settings. 3401 //if (!compareStrings(pi1.group, pi2.group)) return false; 3402 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3403 //if (pi1.labelRes != pi2.labelRes) return false; 3404 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3405 return true; 3406 } 3407 3408 int permissionInfoFootprint(PermissionInfo info) { 3409 int size = info.name.length(); 3410 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3411 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3412 return size; 3413 } 3414 3415 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3416 int size = 0; 3417 for (BasePermission perm : mSettings.mPermissions.values()) { 3418 if (perm.uid == tree.uid) { 3419 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3420 } 3421 } 3422 return size; 3423 } 3424 3425 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3426 // We calculate the max size of permissions defined by this uid and throw 3427 // if that plus the size of 'info' would exceed our stated maximum. 3428 if (tree.uid != Process.SYSTEM_UID) { 3429 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3430 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3431 throw new SecurityException("Permission tree size cap exceeded"); 3432 } 3433 } 3434 } 3435 3436 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3437 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3438 throw new SecurityException("Label must be specified in permission"); 3439 } 3440 BasePermission tree = checkPermissionTreeLP(info.name); 3441 BasePermission bp = mSettings.mPermissions.get(info.name); 3442 boolean added = bp == null; 3443 boolean changed = true; 3444 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3445 if (added) { 3446 enforcePermissionCapLocked(info, tree); 3447 bp = new BasePermission(info.name, tree.sourcePackage, 3448 BasePermission.TYPE_DYNAMIC); 3449 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3450 throw new SecurityException( 3451 "Not allowed to modify non-dynamic permission " 3452 + info.name); 3453 } else { 3454 if (bp.protectionLevel == fixedLevel 3455 && bp.perm.owner.equals(tree.perm.owner) 3456 && bp.uid == tree.uid 3457 && comparePermissionInfos(bp.perm.info, info)) { 3458 changed = false; 3459 } 3460 } 3461 bp.protectionLevel = fixedLevel; 3462 info = new PermissionInfo(info); 3463 info.protectionLevel = fixedLevel; 3464 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3465 bp.perm.info.packageName = tree.perm.info.packageName; 3466 bp.uid = tree.uid; 3467 if (added) { 3468 mSettings.mPermissions.put(info.name, bp); 3469 } 3470 if (changed) { 3471 if (!async) { 3472 mSettings.writeLPr(); 3473 } else { 3474 scheduleWriteSettingsLocked(); 3475 } 3476 } 3477 return added; 3478 } 3479 3480 @Override 3481 public boolean addPermission(PermissionInfo info) { 3482 synchronized (mPackages) { 3483 return addPermissionLocked(info, false); 3484 } 3485 } 3486 3487 @Override 3488 public boolean addPermissionAsync(PermissionInfo info) { 3489 synchronized (mPackages) { 3490 return addPermissionLocked(info, true); 3491 } 3492 } 3493 3494 @Override 3495 public void removePermission(String name) { 3496 synchronized (mPackages) { 3497 checkPermissionTreeLP(name); 3498 BasePermission bp = mSettings.mPermissions.get(name); 3499 if (bp != null) { 3500 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3501 throw new SecurityException( 3502 "Not allowed to modify non-dynamic permission " 3503 + name); 3504 } 3505 mSettings.mPermissions.remove(name); 3506 mSettings.writeLPr(); 3507 } 3508 } 3509 } 3510 3511 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3512 BasePermission bp) { 3513 int index = pkg.requestedPermissions.indexOf(bp.name); 3514 if (index == -1) { 3515 throw new SecurityException("Package " + pkg.packageName 3516 + " has not requested permission " + bp.name); 3517 } 3518 if (!bp.isRuntime() && !bp.isDevelopment()) { 3519 throw new SecurityException("Permission " + bp.name 3520 + " is not a changeable permission type"); 3521 } 3522 } 3523 3524 @Override 3525 public void grantRuntimePermission(String packageName, String name, final int userId) { 3526 if (!sUserManager.exists(userId)) { 3527 Log.e(TAG, "No such user:" + userId); 3528 return; 3529 } 3530 3531 mContext.enforceCallingOrSelfPermission( 3532 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3533 "grantRuntimePermission"); 3534 3535 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3536 "grantRuntimePermission"); 3537 3538 final int uid; 3539 final SettingBase sb; 3540 3541 synchronized (mPackages) { 3542 final PackageParser.Package pkg = mPackages.get(packageName); 3543 if (pkg == null) { 3544 throw new IllegalArgumentException("Unknown package: " + packageName); 3545 } 3546 3547 final BasePermission bp = mSettings.mPermissions.get(name); 3548 if (bp == null) { 3549 throw new IllegalArgumentException("Unknown permission: " + name); 3550 } 3551 3552 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3553 3554 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3555 sb = (SettingBase) pkg.mExtras; 3556 if (sb == null) { 3557 throw new IllegalArgumentException("Unknown package: " + packageName); 3558 } 3559 3560 final PermissionsState permissionsState = sb.getPermissionsState(); 3561 3562 final int flags = permissionsState.getPermissionFlags(name, userId); 3563 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3564 throw new SecurityException("Cannot grant system fixed permission: " 3565 + name + " for package: " + packageName); 3566 } 3567 3568 if (bp.isDevelopment()) { 3569 // Development permissions must be handled specially, since they are not 3570 // normal runtime permissions. For now they apply to all users. 3571 if (permissionsState.grantInstallPermission(bp) != 3572 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3573 scheduleWriteSettingsLocked(); 3574 } 3575 return; 3576 } 3577 3578 final int result = permissionsState.grantRuntimePermission(bp, userId); 3579 switch (result) { 3580 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3581 return; 3582 } 3583 3584 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3585 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3586 mHandler.post(new Runnable() { 3587 @Override 3588 public void run() { 3589 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3590 } 3591 }); 3592 } 3593 break; 3594 } 3595 3596 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3597 3598 // Not critical if that is lost - app has to request again. 3599 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3600 } 3601 3602 // Only need to do this if user is initialized. Otherwise it's a new user 3603 // and there are no processes running as the user yet and there's no need 3604 // to make an expensive call to remount processes for the changed permissions. 3605 if (READ_EXTERNAL_STORAGE.equals(name) 3606 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3607 final long token = Binder.clearCallingIdentity(); 3608 try { 3609 if (sUserManager.isInitialized(userId)) { 3610 MountServiceInternal mountServiceInternal = LocalServices.getService( 3611 MountServiceInternal.class); 3612 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3613 } 3614 } finally { 3615 Binder.restoreCallingIdentity(token); 3616 } 3617 } 3618 } 3619 3620 @Override 3621 public void revokeRuntimePermission(String packageName, String name, int userId) { 3622 if (!sUserManager.exists(userId)) { 3623 Log.e(TAG, "No such user:" + userId); 3624 return; 3625 } 3626 3627 mContext.enforceCallingOrSelfPermission( 3628 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3629 "revokeRuntimePermission"); 3630 3631 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3632 "revokeRuntimePermission"); 3633 3634 final int appId; 3635 3636 synchronized (mPackages) { 3637 final PackageParser.Package pkg = mPackages.get(packageName); 3638 if (pkg == null) { 3639 throw new IllegalArgumentException("Unknown package: " + packageName); 3640 } 3641 3642 final BasePermission bp = mSettings.mPermissions.get(name); 3643 if (bp == null) { 3644 throw new IllegalArgumentException("Unknown permission: " + name); 3645 } 3646 3647 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3648 3649 SettingBase sb = (SettingBase) pkg.mExtras; 3650 if (sb == null) { 3651 throw new IllegalArgumentException("Unknown package: " + packageName); 3652 } 3653 3654 final PermissionsState permissionsState = sb.getPermissionsState(); 3655 3656 final int flags = permissionsState.getPermissionFlags(name, userId); 3657 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3658 throw new SecurityException("Cannot revoke system fixed permission: " 3659 + name + " for package: " + packageName); 3660 } 3661 3662 if (bp.isDevelopment()) { 3663 // Development permissions must be handled specially, since they are not 3664 // normal runtime permissions. For now they apply to all users. 3665 if (permissionsState.revokeInstallPermission(bp) != 3666 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3667 scheduleWriteSettingsLocked(); 3668 } 3669 return; 3670 } 3671 3672 if (permissionsState.revokeRuntimePermission(bp, userId) == 3673 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3674 return; 3675 } 3676 3677 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3678 3679 // Critical, after this call app should never have the permission. 3680 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3681 3682 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3683 } 3684 3685 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3686 } 3687 3688 @Override 3689 public void resetRuntimePermissions() { 3690 mContext.enforceCallingOrSelfPermission( 3691 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3692 "revokeRuntimePermission"); 3693 3694 int callingUid = Binder.getCallingUid(); 3695 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3696 mContext.enforceCallingOrSelfPermission( 3697 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3698 "resetRuntimePermissions"); 3699 } 3700 3701 synchronized (mPackages) { 3702 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3703 for (int userId : UserManagerService.getInstance().getUserIds()) { 3704 final int packageCount = mPackages.size(); 3705 for (int i = 0; i < packageCount; i++) { 3706 PackageParser.Package pkg = mPackages.valueAt(i); 3707 if (!(pkg.mExtras instanceof PackageSetting)) { 3708 continue; 3709 } 3710 PackageSetting ps = (PackageSetting) pkg.mExtras; 3711 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3712 } 3713 } 3714 } 3715 } 3716 3717 @Override 3718 public int getPermissionFlags(String name, String packageName, int userId) { 3719 if (!sUserManager.exists(userId)) { 3720 return 0; 3721 } 3722 3723 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3724 3725 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3726 "getPermissionFlags"); 3727 3728 synchronized (mPackages) { 3729 final PackageParser.Package pkg = mPackages.get(packageName); 3730 if (pkg == null) { 3731 throw new IllegalArgumentException("Unknown package: " + packageName); 3732 } 3733 3734 final BasePermission bp = mSettings.mPermissions.get(name); 3735 if (bp == null) { 3736 throw new IllegalArgumentException("Unknown permission: " + name); 3737 } 3738 3739 SettingBase sb = (SettingBase) pkg.mExtras; 3740 if (sb == null) { 3741 throw new IllegalArgumentException("Unknown package: " + packageName); 3742 } 3743 3744 PermissionsState permissionsState = sb.getPermissionsState(); 3745 return permissionsState.getPermissionFlags(name, userId); 3746 } 3747 } 3748 3749 @Override 3750 public void updatePermissionFlags(String name, String packageName, int flagMask, 3751 int flagValues, int userId) { 3752 if (!sUserManager.exists(userId)) { 3753 return; 3754 } 3755 3756 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3757 3758 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3759 "updatePermissionFlags"); 3760 3761 // Only the system can change these flags and nothing else. 3762 if (getCallingUid() != Process.SYSTEM_UID) { 3763 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3764 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3765 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3766 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3767 } 3768 3769 synchronized (mPackages) { 3770 final PackageParser.Package pkg = mPackages.get(packageName); 3771 if (pkg == null) { 3772 throw new IllegalArgumentException("Unknown package: " + packageName); 3773 } 3774 3775 final BasePermission bp = mSettings.mPermissions.get(name); 3776 if (bp == null) { 3777 throw new IllegalArgumentException("Unknown permission: " + name); 3778 } 3779 3780 SettingBase sb = (SettingBase) pkg.mExtras; 3781 if (sb == null) { 3782 throw new IllegalArgumentException("Unknown package: " + packageName); 3783 } 3784 3785 PermissionsState permissionsState = sb.getPermissionsState(); 3786 3787 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3788 3789 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3790 // Install and runtime permissions are stored in different places, 3791 // so figure out what permission changed and persist the change. 3792 if (permissionsState.getInstallPermissionState(name) != null) { 3793 scheduleWriteSettingsLocked(); 3794 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3795 || hadState) { 3796 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3797 } 3798 } 3799 } 3800 } 3801 3802 /** 3803 * Update the permission flags for all packages and runtime permissions of a user in order 3804 * to allow device or profile owner to remove POLICY_FIXED. 3805 */ 3806 @Override 3807 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3808 if (!sUserManager.exists(userId)) { 3809 return; 3810 } 3811 3812 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3813 3814 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3815 "updatePermissionFlagsForAllApps"); 3816 3817 // Only the system can change system fixed flags. 3818 if (getCallingUid() != Process.SYSTEM_UID) { 3819 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3820 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3821 } 3822 3823 synchronized (mPackages) { 3824 boolean changed = false; 3825 final int packageCount = mPackages.size(); 3826 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3827 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3828 SettingBase sb = (SettingBase) pkg.mExtras; 3829 if (sb == null) { 3830 continue; 3831 } 3832 PermissionsState permissionsState = sb.getPermissionsState(); 3833 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3834 userId, flagMask, flagValues); 3835 } 3836 if (changed) { 3837 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3838 } 3839 } 3840 } 3841 3842 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3843 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3844 != PackageManager.PERMISSION_GRANTED 3845 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3846 != PackageManager.PERMISSION_GRANTED) { 3847 throw new SecurityException(message + " requires " 3848 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3849 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3850 } 3851 } 3852 3853 @Override 3854 public boolean shouldShowRequestPermissionRationale(String permissionName, 3855 String packageName, int userId) { 3856 if (UserHandle.getCallingUserId() != userId) { 3857 mContext.enforceCallingPermission( 3858 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3859 "canShowRequestPermissionRationale for user " + userId); 3860 } 3861 3862 final int uid = getPackageUid(packageName, userId); 3863 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3864 return false; 3865 } 3866 3867 if (checkPermission(permissionName, packageName, userId) 3868 == PackageManager.PERMISSION_GRANTED) { 3869 return false; 3870 } 3871 3872 final int flags; 3873 3874 final long identity = Binder.clearCallingIdentity(); 3875 try { 3876 flags = getPermissionFlags(permissionName, 3877 packageName, userId); 3878 } finally { 3879 Binder.restoreCallingIdentity(identity); 3880 } 3881 3882 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3883 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3884 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3885 3886 if ((flags & fixedFlags) != 0) { 3887 return false; 3888 } 3889 3890 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3891 } 3892 3893 @Override 3894 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3895 mContext.enforceCallingOrSelfPermission( 3896 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3897 "addOnPermissionsChangeListener"); 3898 3899 synchronized (mPackages) { 3900 mOnPermissionChangeListeners.addListenerLocked(listener); 3901 } 3902 } 3903 3904 @Override 3905 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3906 synchronized (mPackages) { 3907 mOnPermissionChangeListeners.removeListenerLocked(listener); 3908 } 3909 } 3910 3911 @Override 3912 public boolean isProtectedBroadcast(String actionName) { 3913 synchronized (mPackages) { 3914 return mProtectedBroadcasts.contains(actionName); 3915 } 3916 } 3917 3918 @Override 3919 public int checkSignatures(String pkg1, String pkg2) { 3920 synchronized (mPackages) { 3921 final PackageParser.Package p1 = mPackages.get(pkg1); 3922 final PackageParser.Package p2 = mPackages.get(pkg2); 3923 if (p1 == null || p1.mExtras == null 3924 || p2 == null || p2.mExtras == null) { 3925 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3926 } 3927 return compareSignatures(p1.mSignatures, p2.mSignatures); 3928 } 3929 } 3930 3931 @Override 3932 public int checkUidSignatures(int uid1, int uid2) { 3933 // Map to base uids. 3934 uid1 = UserHandle.getAppId(uid1); 3935 uid2 = UserHandle.getAppId(uid2); 3936 // reader 3937 synchronized (mPackages) { 3938 Signature[] s1; 3939 Signature[] s2; 3940 Object obj = mSettings.getUserIdLPr(uid1); 3941 if (obj != null) { 3942 if (obj instanceof SharedUserSetting) { 3943 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3944 } else if (obj instanceof PackageSetting) { 3945 s1 = ((PackageSetting)obj).signatures.mSignatures; 3946 } else { 3947 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3948 } 3949 } else { 3950 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3951 } 3952 obj = mSettings.getUserIdLPr(uid2); 3953 if (obj != null) { 3954 if (obj instanceof SharedUserSetting) { 3955 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3956 } else if (obj instanceof PackageSetting) { 3957 s2 = ((PackageSetting)obj).signatures.mSignatures; 3958 } else { 3959 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3960 } 3961 } else { 3962 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3963 } 3964 return compareSignatures(s1, s2); 3965 } 3966 } 3967 3968 private void killUid(int appId, int userId, String reason) { 3969 final long identity = Binder.clearCallingIdentity(); 3970 try { 3971 IActivityManager am = ActivityManagerNative.getDefault(); 3972 if (am != null) { 3973 try { 3974 am.killUid(appId, userId, reason); 3975 } catch (RemoteException e) { 3976 /* ignore - same process */ 3977 } 3978 } 3979 } finally { 3980 Binder.restoreCallingIdentity(identity); 3981 } 3982 } 3983 3984 /** 3985 * Compares two sets of signatures. Returns: 3986 * <br /> 3987 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3988 * <br /> 3989 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3990 * <br /> 3991 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3992 * <br /> 3993 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3994 * <br /> 3995 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3996 */ 3997 static int compareSignatures(Signature[] s1, Signature[] s2) { 3998 if (s1 == null) { 3999 return s2 == null 4000 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4001 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4002 } 4003 4004 if (s2 == null) { 4005 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4006 } 4007 4008 if (s1.length != s2.length) { 4009 return PackageManager.SIGNATURE_NO_MATCH; 4010 } 4011 4012 // Since both signature sets are of size 1, we can compare without HashSets. 4013 if (s1.length == 1) { 4014 return s1[0].equals(s2[0]) ? 4015 PackageManager.SIGNATURE_MATCH : 4016 PackageManager.SIGNATURE_NO_MATCH; 4017 } 4018 4019 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4020 for (Signature sig : s1) { 4021 set1.add(sig); 4022 } 4023 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4024 for (Signature sig : s2) { 4025 set2.add(sig); 4026 } 4027 // Make sure s2 contains all signatures in s1. 4028 if (set1.equals(set2)) { 4029 return PackageManager.SIGNATURE_MATCH; 4030 } 4031 return PackageManager.SIGNATURE_NO_MATCH; 4032 } 4033 4034 /** 4035 * If the database version for this type of package (internal storage or 4036 * external storage) is less than the version where package signatures 4037 * were updated, return true. 4038 */ 4039 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4040 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4041 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4042 } 4043 4044 /** 4045 * Used for backward compatibility to make sure any packages with 4046 * certificate chains get upgraded to the new style. {@code existingSigs} 4047 * will be in the old format (since they were stored on disk from before the 4048 * system upgrade) and {@code scannedSigs} will be in the newer format. 4049 */ 4050 private int compareSignaturesCompat(PackageSignatures existingSigs, 4051 PackageParser.Package scannedPkg) { 4052 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4053 return PackageManager.SIGNATURE_NO_MATCH; 4054 } 4055 4056 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4057 for (Signature sig : existingSigs.mSignatures) { 4058 existingSet.add(sig); 4059 } 4060 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4061 for (Signature sig : scannedPkg.mSignatures) { 4062 try { 4063 Signature[] chainSignatures = sig.getChainSignatures(); 4064 for (Signature chainSig : chainSignatures) { 4065 scannedCompatSet.add(chainSig); 4066 } 4067 } catch (CertificateEncodingException e) { 4068 scannedCompatSet.add(sig); 4069 } 4070 } 4071 /* 4072 * Make sure the expanded scanned set contains all signatures in the 4073 * existing one. 4074 */ 4075 if (scannedCompatSet.equals(existingSet)) { 4076 // Migrate the old signatures to the new scheme. 4077 existingSigs.assignSignatures(scannedPkg.mSignatures); 4078 // The new KeySets will be re-added later in the scanning process. 4079 synchronized (mPackages) { 4080 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4081 } 4082 return PackageManager.SIGNATURE_MATCH; 4083 } 4084 return PackageManager.SIGNATURE_NO_MATCH; 4085 } 4086 4087 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4088 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4089 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4090 } 4091 4092 private int compareSignaturesRecover(PackageSignatures existingSigs, 4093 PackageParser.Package scannedPkg) { 4094 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4095 return PackageManager.SIGNATURE_NO_MATCH; 4096 } 4097 4098 String msg = null; 4099 try { 4100 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4101 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4102 + scannedPkg.packageName); 4103 return PackageManager.SIGNATURE_MATCH; 4104 } 4105 } catch (CertificateException e) { 4106 msg = e.getMessage(); 4107 } 4108 4109 logCriticalInfo(Log.INFO, 4110 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4111 return PackageManager.SIGNATURE_NO_MATCH; 4112 } 4113 4114 @Override 4115 public String[] getPackagesForUid(int uid) { 4116 uid = UserHandle.getAppId(uid); 4117 // reader 4118 synchronized (mPackages) { 4119 Object obj = mSettings.getUserIdLPr(uid); 4120 if (obj instanceof SharedUserSetting) { 4121 final SharedUserSetting sus = (SharedUserSetting) obj; 4122 final int N = sus.packages.size(); 4123 final String[] res = new String[N]; 4124 final Iterator<PackageSetting> it = sus.packages.iterator(); 4125 int i = 0; 4126 while (it.hasNext()) { 4127 res[i++] = it.next().name; 4128 } 4129 return res; 4130 } else if (obj instanceof PackageSetting) { 4131 final PackageSetting ps = (PackageSetting) obj; 4132 return new String[] { ps.name }; 4133 } 4134 } 4135 return null; 4136 } 4137 4138 @Override 4139 public String getNameForUid(int uid) { 4140 // reader 4141 synchronized (mPackages) { 4142 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4143 if (obj instanceof SharedUserSetting) { 4144 final SharedUserSetting sus = (SharedUserSetting) obj; 4145 return sus.name + ":" + sus.userId; 4146 } else if (obj instanceof PackageSetting) { 4147 final PackageSetting ps = (PackageSetting) obj; 4148 return ps.name; 4149 } 4150 } 4151 return null; 4152 } 4153 4154 @Override 4155 public int getUidForSharedUser(String sharedUserName) { 4156 if(sharedUserName == null) { 4157 return -1; 4158 } 4159 // reader 4160 synchronized (mPackages) { 4161 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4162 if (suid == null) { 4163 return -1; 4164 } 4165 return suid.userId; 4166 } 4167 } 4168 4169 @Override 4170 public int getFlagsForUid(int uid) { 4171 synchronized (mPackages) { 4172 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4173 if (obj instanceof SharedUserSetting) { 4174 final SharedUserSetting sus = (SharedUserSetting) obj; 4175 return sus.pkgFlags; 4176 } else if (obj instanceof PackageSetting) { 4177 final PackageSetting ps = (PackageSetting) obj; 4178 return ps.pkgFlags; 4179 } 4180 } 4181 return 0; 4182 } 4183 4184 @Override 4185 public int getPrivateFlagsForUid(int uid) { 4186 synchronized (mPackages) { 4187 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4188 if (obj instanceof SharedUserSetting) { 4189 final SharedUserSetting sus = (SharedUserSetting) obj; 4190 return sus.pkgPrivateFlags; 4191 } else if (obj instanceof PackageSetting) { 4192 final PackageSetting ps = (PackageSetting) obj; 4193 return ps.pkgPrivateFlags; 4194 } 4195 } 4196 return 0; 4197 } 4198 4199 @Override 4200 public boolean isUidPrivileged(int uid) { 4201 uid = UserHandle.getAppId(uid); 4202 // reader 4203 synchronized (mPackages) { 4204 Object obj = mSettings.getUserIdLPr(uid); 4205 if (obj instanceof SharedUserSetting) { 4206 final SharedUserSetting sus = (SharedUserSetting) obj; 4207 final Iterator<PackageSetting> it = sus.packages.iterator(); 4208 while (it.hasNext()) { 4209 if (it.next().isPrivileged()) { 4210 return true; 4211 } 4212 } 4213 } else if (obj instanceof PackageSetting) { 4214 final PackageSetting ps = (PackageSetting) obj; 4215 return ps.isPrivileged(); 4216 } 4217 } 4218 return false; 4219 } 4220 4221 @Override 4222 public String[] getAppOpPermissionPackages(String permissionName) { 4223 synchronized (mPackages) { 4224 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4225 if (pkgs == null) { 4226 return null; 4227 } 4228 return pkgs.toArray(new String[pkgs.size()]); 4229 } 4230 } 4231 4232 @Override 4233 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4234 int flags, int userId) { 4235 if (!sUserManager.exists(userId)) return null; 4236 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4237 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4238 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4239 } 4240 4241 @Override 4242 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4243 IntentFilter filter, int match, ComponentName activity) { 4244 final int userId = UserHandle.getCallingUserId(); 4245 if (DEBUG_PREFERRED) { 4246 Log.v(TAG, "setLastChosenActivity intent=" + intent 4247 + " resolvedType=" + resolvedType 4248 + " flags=" + flags 4249 + " filter=" + filter 4250 + " match=" + match 4251 + " activity=" + activity); 4252 filter.dump(new PrintStreamPrinter(System.out), " "); 4253 } 4254 intent.setComponent(null); 4255 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4256 // Find any earlier preferred or last chosen entries and nuke them 4257 findPreferredActivity(intent, resolvedType, 4258 flags, query, 0, false, true, false, userId); 4259 // Add the new activity as the last chosen for this filter 4260 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4261 "Setting last chosen"); 4262 } 4263 4264 @Override 4265 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4266 final int userId = UserHandle.getCallingUserId(); 4267 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4268 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4269 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4270 false, false, false, userId); 4271 } 4272 4273 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4274 int flags, List<ResolveInfo> query, int userId) { 4275 if (query != null) { 4276 final int N = query.size(); 4277 if (N == 1) { 4278 return query.get(0); 4279 } else if (N > 1) { 4280 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4281 // If there is more than one activity with the same priority, 4282 // then let the user decide between them. 4283 ResolveInfo r0 = query.get(0); 4284 ResolveInfo r1 = query.get(1); 4285 if (DEBUG_INTENT_MATCHING || debug) { 4286 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4287 + r1.activityInfo.name + "=" + r1.priority); 4288 } 4289 // If the first activity has a higher priority, or a different 4290 // default, then it is always desireable to pick it. 4291 if (r0.priority != r1.priority 4292 || r0.preferredOrder != r1.preferredOrder 4293 || r0.isDefault != r1.isDefault) { 4294 return query.get(0); 4295 } 4296 // If we have saved a preference for a preferred activity for 4297 // this Intent, use that. 4298 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4299 flags, query, r0.priority, true, false, debug, userId); 4300 if (ri != null) { 4301 return ri; 4302 } 4303 ri = new ResolveInfo(mResolveInfo); 4304 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4305 ri.activityInfo.applicationInfo = new ApplicationInfo( 4306 ri.activityInfo.applicationInfo); 4307 if (userId != 0) { 4308 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4309 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4310 } 4311 // Make sure that the resolver is displayable in car mode 4312 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4313 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4314 return ri; 4315 } 4316 } 4317 return null; 4318 } 4319 4320 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4321 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4322 final int N = query.size(); 4323 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4324 .get(userId); 4325 // Get the list of persistent preferred activities that handle the intent 4326 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4327 List<PersistentPreferredActivity> pprefs = ppir != null 4328 ? ppir.queryIntent(intent, resolvedType, 4329 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4330 : null; 4331 if (pprefs != null && pprefs.size() > 0) { 4332 final int M = pprefs.size(); 4333 for (int i=0; i<M; i++) { 4334 final PersistentPreferredActivity ppa = pprefs.get(i); 4335 if (DEBUG_PREFERRED || debug) { 4336 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4337 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4338 + "\n component=" + ppa.mComponent); 4339 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4340 } 4341 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4342 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4343 if (DEBUG_PREFERRED || debug) { 4344 Slog.v(TAG, "Found persistent preferred activity:"); 4345 if (ai != null) { 4346 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4347 } else { 4348 Slog.v(TAG, " null"); 4349 } 4350 } 4351 if (ai == null) { 4352 // This previously registered persistent preferred activity 4353 // component is no longer known. Ignore it and do NOT remove it. 4354 continue; 4355 } 4356 for (int j=0; j<N; j++) { 4357 final ResolveInfo ri = query.get(j); 4358 if (!ri.activityInfo.applicationInfo.packageName 4359 .equals(ai.applicationInfo.packageName)) { 4360 continue; 4361 } 4362 if (!ri.activityInfo.name.equals(ai.name)) { 4363 continue; 4364 } 4365 // Found a persistent preference that can handle the intent. 4366 if (DEBUG_PREFERRED || debug) { 4367 Slog.v(TAG, "Returning persistent preferred activity: " + 4368 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4369 } 4370 return ri; 4371 } 4372 } 4373 } 4374 return null; 4375 } 4376 4377 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4378 List<ResolveInfo> query, int priority, boolean always, 4379 boolean removeMatches, boolean debug, int userId) { 4380 if (!sUserManager.exists(userId)) return null; 4381 // writer 4382 synchronized (mPackages) { 4383 if (intent.getSelector() != null) { 4384 intent = intent.getSelector(); 4385 } 4386 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4387 4388 // Try to find a matching persistent preferred activity. 4389 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4390 debug, userId); 4391 4392 // If a persistent preferred activity matched, use it. 4393 if (pri != null) { 4394 return pri; 4395 } 4396 4397 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4398 // Get the list of preferred activities that handle the intent 4399 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4400 List<PreferredActivity> prefs = pir != null 4401 ? pir.queryIntent(intent, resolvedType, 4402 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4403 : null; 4404 if (prefs != null && prefs.size() > 0) { 4405 boolean changed = false; 4406 try { 4407 // First figure out how good the original match set is. 4408 // We will only allow preferred activities that came 4409 // from the same match quality. 4410 int match = 0; 4411 4412 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4413 4414 final int N = query.size(); 4415 for (int j=0; j<N; j++) { 4416 final ResolveInfo ri = query.get(j); 4417 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4418 + ": 0x" + Integer.toHexString(match)); 4419 if (ri.match > match) { 4420 match = ri.match; 4421 } 4422 } 4423 4424 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4425 + Integer.toHexString(match)); 4426 4427 match &= IntentFilter.MATCH_CATEGORY_MASK; 4428 final int M = prefs.size(); 4429 for (int i=0; i<M; i++) { 4430 final PreferredActivity pa = prefs.get(i); 4431 if (DEBUG_PREFERRED || debug) { 4432 Slog.v(TAG, "Checking PreferredActivity ds=" 4433 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4434 + "\n component=" + pa.mPref.mComponent); 4435 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4436 } 4437 if (pa.mPref.mMatch != match) { 4438 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4439 + Integer.toHexString(pa.mPref.mMatch)); 4440 continue; 4441 } 4442 // If it's not an "always" type preferred activity and that's what we're 4443 // looking for, skip it. 4444 if (always && !pa.mPref.mAlways) { 4445 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4446 continue; 4447 } 4448 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4449 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4450 if (DEBUG_PREFERRED || debug) { 4451 Slog.v(TAG, "Found preferred activity:"); 4452 if (ai != null) { 4453 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4454 } else { 4455 Slog.v(TAG, " null"); 4456 } 4457 } 4458 if (ai == null) { 4459 // This previously registered preferred activity 4460 // component is no longer known. Most likely an update 4461 // to the app was installed and in the new version this 4462 // component no longer exists. Clean it up by removing 4463 // it from the preferred activities list, and skip it. 4464 Slog.w(TAG, "Removing dangling preferred activity: " 4465 + pa.mPref.mComponent); 4466 pir.removeFilter(pa); 4467 changed = true; 4468 continue; 4469 } 4470 for (int j=0; j<N; j++) { 4471 final ResolveInfo ri = query.get(j); 4472 if (!ri.activityInfo.applicationInfo.packageName 4473 .equals(ai.applicationInfo.packageName)) { 4474 continue; 4475 } 4476 if (!ri.activityInfo.name.equals(ai.name)) { 4477 continue; 4478 } 4479 4480 if (removeMatches) { 4481 pir.removeFilter(pa); 4482 changed = true; 4483 if (DEBUG_PREFERRED) { 4484 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4485 } 4486 break; 4487 } 4488 4489 // Okay we found a previously set preferred or last chosen app. 4490 // If the result set is different from when this 4491 // was created, we need to clear it and re-ask the 4492 // user their preference, if we're looking for an "always" type entry. 4493 if (always && !pa.mPref.sameSet(query)) { 4494 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4495 + intent + " type " + resolvedType); 4496 if (DEBUG_PREFERRED) { 4497 Slog.v(TAG, "Removing preferred activity since set changed " 4498 + pa.mPref.mComponent); 4499 } 4500 pir.removeFilter(pa); 4501 // Re-add the filter as a "last chosen" entry (!always) 4502 PreferredActivity lastChosen = new PreferredActivity( 4503 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4504 pir.addFilter(lastChosen); 4505 changed = true; 4506 return null; 4507 } 4508 4509 // Yay! Either the set matched or we're looking for the last chosen 4510 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4511 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4512 return ri; 4513 } 4514 } 4515 } finally { 4516 if (changed) { 4517 if (DEBUG_PREFERRED) { 4518 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4519 } 4520 scheduleWritePackageRestrictionsLocked(userId); 4521 } 4522 } 4523 } 4524 } 4525 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4526 return null; 4527 } 4528 4529 /* 4530 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4531 */ 4532 @Override 4533 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4534 int targetUserId) { 4535 mContext.enforceCallingOrSelfPermission( 4536 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4537 List<CrossProfileIntentFilter> matches = 4538 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4539 if (matches != null) { 4540 int size = matches.size(); 4541 for (int i = 0; i < size; i++) { 4542 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4543 } 4544 } 4545 if (hasWebURI(intent)) { 4546 // cross-profile app linking works only towards the parent. 4547 final UserInfo parent = getProfileParent(sourceUserId); 4548 synchronized(mPackages) { 4549 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4550 intent, resolvedType, 0, sourceUserId, parent.id); 4551 return xpDomainInfo != null; 4552 } 4553 } 4554 return false; 4555 } 4556 4557 private UserInfo getProfileParent(int userId) { 4558 final long identity = Binder.clearCallingIdentity(); 4559 try { 4560 return sUserManager.getProfileParent(userId); 4561 } finally { 4562 Binder.restoreCallingIdentity(identity); 4563 } 4564 } 4565 4566 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4567 String resolvedType, int userId) { 4568 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4569 if (resolver != null) { 4570 return resolver.queryIntent(intent, resolvedType, false, userId); 4571 } 4572 return null; 4573 } 4574 4575 @Override 4576 public List<ResolveInfo> queryIntentActivities(Intent intent, 4577 String resolvedType, int flags, int userId) { 4578 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4579 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4580 ComponentName comp = intent.getComponent(); 4581 if (comp == null) { 4582 if (intent.getSelector() != null) { 4583 intent = intent.getSelector(); 4584 comp = intent.getComponent(); 4585 } 4586 } 4587 4588 if (comp != null) { 4589 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4590 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4591 if (ai != null) { 4592 final ResolveInfo ri = new ResolveInfo(); 4593 ri.activityInfo = ai; 4594 list.add(ri); 4595 } 4596 return list; 4597 } 4598 4599 // reader 4600 synchronized (mPackages) { 4601 final String pkgName = intent.getPackage(); 4602 if (pkgName == null) { 4603 List<CrossProfileIntentFilter> matchingFilters = 4604 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4605 // Check for results that need to skip the current profile. 4606 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4607 resolvedType, flags, userId); 4608 if (xpResolveInfo != null) { 4609 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4610 result.add(xpResolveInfo); 4611 return filterIfNotSystemUser(result, userId); 4612 } 4613 4614 // Check for results in the current profile. 4615 List<ResolveInfo> result = mActivities.queryIntent( 4616 intent, resolvedType, flags, userId); 4617 4618 // Check for cross profile results. 4619 xpResolveInfo = queryCrossProfileIntents( 4620 matchingFilters, intent, resolvedType, flags, userId); 4621 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4622 result.add(xpResolveInfo); 4623 Collections.sort(result, mResolvePrioritySorter); 4624 } 4625 result = filterIfNotSystemUser(result, userId); 4626 if (hasWebURI(intent)) { 4627 CrossProfileDomainInfo xpDomainInfo = null; 4628 final UserInfo parent = getProfileParent(userId); 4629 if (parent != null) { 4630 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4631 flags, userId, parent.id); 4632 } 4633 if (xpDomainInfo != null) { 4634 if (xpResolveInfo != null) { 4635 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4636 // in the result. 4637 result.remove(xpResolveInfo); 4638 } 4639 if (result.size() == 0) { 4640 result.add(xpDomainInfo.resolveInfo); 4641 return result; 4642 } 4643 } else if (result.size() <= 1) { 4644 return result; 4645 } 4646 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4647 xpDomainInfo, userId); 4648 Collections.sort(result, mResolvePrioritySorter); 4649 } 4650 return result; 4651 } 4652 final PackageParser.Package pkg = mPackages.get(pkgName); 4653 if (pkg != null) { 4654 return filterIfNotSystemUser( 4655 mActivities.queryIntentForPackage( 4656 intent, resolvedType, flags, pkg.activities, userId), 4657 userId); 4658 } 4659 return new ArrayList<ResolveInfo>(); 4660 } 4661 } 4662 4663 private static class CrossProfileDomainInfo { 4664 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4665 ResolveInfo resolveInfo; 4666 /* Best domain verification status of the activities found in the other profile */ 4667 int bestDomainVerificationStatus; 4668 } 4669 4670 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4671 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4672 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4673 sourceUserId)) { 4674 return null; 4675 } 4676 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4677 resolvedType, flags, parentUserId); 4678 4679 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4680 return null; 4681 } 4682 CrossProfileDomainInfo result = null; 4683 int size = resultTargetUser.size(); 4684 for (int i = 0; i < size; i++) { 4685 ResolveInfo riTargetUser = resultTargetUser.get(i); 4686 // Intent filter verification is only for filters that specify a host. So don't return 4687 // those that handle all web uris. 4688 if (riTargetUser.handleAllWebDataURI) { 4689 continue; 4690 } 4691 String packageName = riTargetUser.activityInfo.packageName; 4692 PackageSetting ps = mSettings.mPackages.get(packageName); 4693 if (ps == null) { 4694 continue; 4695 } 4696 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4697 int status = (int)(verificationState >> 32); 4698 if (result == null) { 4699 result = new CrossProfileDomainInfo(); 4700 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4701 sourceUserId, parentUserId); 4702 result.bestDomainVerificationStatus = status; 4703 } else { 4704 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4705 result.bestDomainVerificationStatus); 4706 } 4707 } 4708 // Don't consider matches with status NEVER across profiles. 4709 if (result != null && result.bestDomainVerificationStatus 4710 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4711 return null; 4712 } 4713 return result; 4714 } 4715 4716 /** 4717 * Verification statuses are ordered from the worse to the best, except for 4718 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4719 */ 4720 private int bestDomainVerificationStatus(int status1, int status2) { 4721 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4722 return status2; 4723 } 4724 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4725 return status1; 4726 } 4727 return (int) MathUtils.max(status1, status2); 4728 } 4729 4730 private boolean isUserEnabled(int userId) { 4731 long callingId = Binder.clearCallingIdentity(); 4732 try { 4733 UserInfo userInfo = sUserManager.getUserInfo(userId); 4734 return userInfo != null && userInfo.isEnabled(); 4735 } finally { 4736 Binder.restoreCallingIdentity(callingId); 4737 } 4738 } 4739 4740 /** 4741 * Filter out activities with systemUserOnly flag set, when current user is not System. 4742 * 4743 * @return filtered list 4744 */ 4745 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4746 if (userId == UserHandle.USER_SYSTEM) { 4747 return resolveInfos; 4748 } 4749 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4750 ResolveInfo info = resolveInfos.get(i); 4751 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4752 resolveInfos.remove(i); 4753 } 4754 } 4755 return resolveInfos; 4756 } 4757 4758 private static boolean hasWebURI(Intent intent) { 4759 if (intent.getData() == null) { 4760 return false; 4761 } 4762 final String scheme = intent.getScheme(); 4763 if (TextUtils.isEmpty(scheme)) { 4764 return false; 4765 } 4766 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4767 } 4768 4769 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4770 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4771 int userId) { 4772 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4773 4774 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4775 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4776 candidates.size()); 4777 } 4778 4779 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4780 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4781 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4782 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4783 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4784 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4785 4786 synchronized (mPackages) { 4787 final int count = candidates.size(); 4788 // First, try to use linked apps. Partition the candidates into four lists: 4789 // one for the final results, one for the "do not use ever", one for "undefined status" 4790 // and finally one for "browser app type". 4791 for (int n=0; n<count; n++) { 4792 ResolveInfo info = candidates.get(n); 4793 String packageName = info.activityInfo.packageName; 4794 PackageSetting ps = mSettings.mPackages.get(packageName); 4795 if (ps != null) { 4796 // Add to the special match all list (Browser use case) 4797 if (info.handleAllWebDataURI) { 4798 matchAllList.add(info); 4799 continue; 4800 } 4801 // Try to get the status from User settings first 4802 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4803 int status = (int)(packedStatus >> 32); 4804 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4805 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4806 if (DEBUG_DOMAIN_VERIFICATION) { 4807 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4808 + " : linkgen=" + linkGeneration); 4809 } 4810 // Use link-enabled generation as preferredOrder, i.e. 4811 // prefer newly-enabled over earlier-enabled. 4812 info.preferredOrder = linkGeneration; 4813 alwaysList.add(info); 4814 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4815 if (DEBUG_DOMAIN_VERIFICATION) { 4816 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4817 } 4818 neverList.add(info); 4819 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4820 if (DEBUG_DOMAIN_VERIFICATION) { 4821 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4822 } 4823 alwaysAskList.add(info); 4824 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4825 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4826 if (DEBUG_DOMAIN_VERIFICATION) { 4827 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4828 } 4829 undefinedList.add(info); 4830 } 4831 } 4832 } 4833 4834 // We'll want to include browser possibilities in a few cases 4835 boolean includeBrowser = false; 4836 4837 // First try to add the "always" resolution(s) for the current user, if any 4838 if (alwaysList.size() > 0) { 4839 result.addAll(alwaysList); 4840 } else { 4841 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4842 result.addAll(undefinedList); 4843 // Maybe add one for the other profile. 4844 if (xpDomainInfo != null && ( 4845 xpDomainInfo.bestDomainVerificationStatus 4846 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4847 result.add(xpDomainInfo.resolveInfo); 4848 } 4849 includeBrowser = true; 4850 } 4851 4852 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4853 // If there were 'always' entries their preferred order has been set, so we also 4854 // back that off to make the alternatives equivalent 4855 if (alwaysAskList.size() > 0) { 4856 for (ResolveInfo i : result) { 4857 i.preferredOrder = 0; 4858 } 4859 result.addAll(alwaysAskList); 4860 includeBrowser = true; 4861 } 4862 4863 if (includeBrowser) { 4864 // Also add browsers (all of them or only the default one) 4865 if (DEBUG_DOMAIN_VERIFICATION) { 4866 Slog.v(TAG, " ...including browsers in candidate set"); 4867 } 4868 if ((matchFlags & MATCH_ALL) != 0) { 4869 result.addAll(matchAllList); 4870 } else { 4871 // Browser/generic handling case. If there's a default browser, go straight 4872 // to that (but only if there is no other higher-priority match). 4873 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4874 int maxMatchPrio = 0; 4875 ResolveInfo defaultBrowserMatch = null; 4876 final int numCandidates = matchAllList.size(); 4877 for (int n = 0; n < numCandidates; n++) { 4878 ResolveInfo info = matchAllList.get(n); 4879 // track the highest overall match priority... 4880 if (info.priority > maxMatchPrio) { 4881 maxMatchPrio = info.priority; 4882 } 4883 // ...and the highest-priority default browser match 4884 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4885 if (defaultBrowserMatch == null 4886 || (defaultBrowserMatch.priority < info.priority)) { 4887 if (debug) { 4888 Slog.v(TAG, "Considering default browser match " + info); 4889 } 4890 defaultBrowserMatch = info; 4891 } 4892 } 4893 } 4894 if (defaultBrowserMatch != null 4895 && defaultBrowserMatch.priority >= maxMatchPrio 4896 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4897 { 4898 if (debug) { 4899 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4900 } 4901 result.add(defaultBrowserMatch); 4902 } else { 4903 result.addAll(matchAllList); 4904 } 4905 } 4906 4907 // If there is nothing selected, add all candidates and remove the ones that the user 4908 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4909 if (result.size() == 0) { 4910 result.addAll(candidates); 4911 result.removeAll(neverList); 4912 } 4913 } 4914 } 4915 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4916 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4917 result.size()); 4918 for (ResolveInfo info : result) { 4919 Slog.v(TAG, " + " + info.activityInfo); 4920 } 4921 } 4922 return result; 4923 } 4924 4925 // Returns a packed value as a long: 4926 // 4927 // high 'int'-sized word: link status: undefined/ask/never/always. 4928 // low 'int'-sized word: relative priority among 'always' results. 4929 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4930 long result = ps.getDomainVerificationStatusForUser(userId); 4931 // if none available, get the master status 4932 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4933 if (ps.getIntentFilterVerificationInfo() != null) { 4934 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4935 } 4936 } 4937 return result; 4938 } 4939 4940 private ResolveInfo querySkipCurrentProfileIntents( 4941 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4942 int flags, int sourceUserId) { 4943 if (matchingFilters != null) { 4944 int size = matchingFilters.size(); 4945 for (int i = 0; i < size; i ++) { 4946 CrossProfileIntentFilter filter = matchingFilters.get(i); 4947 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4948 // Checking if there are activities in the target user that can handle the 4949 // intent. 4950 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4951 resolvedType, flags, sourceUserId); 4952 if (resolveInfo != null) { 4953 return resolveInfo; 4954 } 4955 } 4956 } 4957 } 4958 return null; 4959 } 4960 4961 // Return matching ResolveInfo if any for skip current profile intent filters. 4962 private ResolveInfo queryCrossProfileIntents( 4963 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4964 int flags, int sourceUserId) { 4965 if (matchingFilters != null) { 4966 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4967 // match the same intent. For performance reasons, it is better not to 4968 // run queryIntent twice for the same userId 4969 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4970 int size = matchingFilters.size(); 4971 for (int i = 0; i < size; i++) { 4972 CrossProfileIntentFilter filter = matchingFilters.get(i); 4973 int targetUserId = filter.getTargetUserId(); 4974 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4975 && !alreadyTriedUserIds.get(targetUserId)) { 4976 // Checking if there are activities in the target user that can handle the 4977 // intent. 4978 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4979 resolvedType, flags, sourceUserId); 4980 if (resolveInfo != null) return resolveInfo; 4981 alreadyTriedUserIds.put(targetUserId, true); 4982 } 4983 } 4984 } 4985 return null; 4986 } 4987 4988 /** 4989 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4990 * will forward the intent to the filter's target user. 4991 * Otherwise, returns null. 4992 */ 4993 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4994 String resolvedType, int flags, int sourceUserId) { 4995 int targetUserId = filter.getTargetUserId(); 4996 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4997 resolvedType, flags, targetUserId); 4998 if (resultTargetUser != null && !resultTargetUser.isEmpty() 4999 && isUserEnabled(targetUserId)) { 5000 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5001 } 5002 return null; 5003 } 5004 5005 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5006 int sourceUserId, int targetUserId) { 5007 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5008 long ident = Binder.clearCallingIdentity(); 5009 boolean targetIsProfile; 5010 try { 5011 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5012 } finally { 5013 Binder.restoreCallingIdentity(ident); 5014 } 5015 String className; 5016 if (targetIsProfile) { 5017 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5018 } else { 5019 className = FORWARD_INTENT_TO_PARENT; 5020 } 5021 ComponentName forwardingActivityComponentName = new ComponentName( 5022 mAndroidApplication.packageName, className); 5023 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5024 sourceUserId); 5025 if (!targetIsProfile) { 5026 forwardingActivityInfo.showUserIcon = targetUserId; 5027 forwardingResolveInfo.noResourceId = true; 5028 } 5029 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5030 forwardingResolveInfo.priority = 0; 5031 forwardingResolveInfo.preferredOrder = 0; 5032 forwardingResolveInfo.match = 0; 5033 forwardingResolveInfo.isDefault = true; 5034 forwardingResolveInfo.filter = filter; 5035 forwardingResolveInfo.targetUserId = targetUserId; 5036 return forwardingResolveInfo; 5037 } 5038 5039 @Override 5040 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5041 Intent[] specifics, String[] specificTypes, Intent intent, 5042 String resolvedType, int flags, int userId) { 5043 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5044 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5045 false, "query intent activity options"); 5046 final String resultsAction = intent.getAction(); 5047 5048 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5049 | PackageManager.GET_RESOLVED_FILTER, userId); 5050 5051 if (DEBUG_INTENT_MATCHING) { 5052 Log.v(TAG, "Query " + intent + ": " + results); 5053 } 5054 5055 int specificsPos = 0; 5056 int N; 5057 5058 // todo: note that the algorithm used here is O(N^2). This 5059 // isn't a problem in our current environment, but if we start running 5060 // into situations where we have more than 5 or 10 matches then this 5061 // should probably be changed to something smarter... 5062 5063 // First we go through and resolve each of the specific items 5064 // that were supplied, taking care of removing any corresponding 5065 // duplicate items in the generic resolve list. 5066 if (specifics != null) { 5067 for (int i=0; i<specifics.length; i++) { 5068 final Intent sintent = specifics[i]; 5069 if (sintent == null) { 5070 continue; 5071 } 5072 5073 if (DEBUG_INTENT_MATCHING) { 5074 Log.v(TAG, "Specific #" + i + ": " + sintent); 5075 } 5076 5077 String action = sintent.getAction(); 5078 if (resultsAction != null && resultsAction.equals(action)) { 5079 // If this action was explicitly requested, then don't 5080 // remove things that have it. 5081 action = null; 5082 } 5083 5084 ResolveInfo ri = null; 5085 ActivityInfo ai = null; 5086 5087 ComponentName comp = sintent.getComponent(); 5088 if (comp == null) { 5089 ri = resolveIntent( 5090 sintent, 5091 specificTypes != null ? specificTypes[i] : null, 5092 flags, userId); 5093 if (ri == null) { 5094 continue; 5095 } 5096 if (ri == mResolveInfo) { 5097 // ACK! Must do something better with this. 5098 } 5099 ai = ri.activityInfo; 5100 comp = new ComponentName(ai.applicationInfo.packageName, 5101 ai.name); 5102 } else { 5103 ai = getActivityInfo(comp, flags, userId); 5104 if (ai == null) { 5105 continue; 5106 } 5107 } 5108 5109 // Look for any generic query activities that are duplicates 5110 // of this specific one, and remove them from the results. 5111 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5112 N = results.size(); 5113 int j; 5114 for (j=specificsPos; j<N; j++) { 5115 ResolveInfo sri = results.get(j); 5116 if ((sri.activityInfo.name.equals(comp.getClassName()) 5117 && sri.activityInfo.applicationInfo.packageName.equals( 5118 comp.getPackageName())) 5119 || (action != null && sri.filter.matchAction(action))) { 5120 results.remove(j); 5121 if (DEBUG_INTENT_MATCHING) Log.v( 5122 TAG, "Removing duplicate item from " + j 5123 + " due to specific " + specificsPos); 5124 if (ri == null) { 5125 ri = sri; 5126 } 5127 j--; 5128 N--; 5129 } 5130 } 5131 5132 // Add this specific item to its proper place. 5133 if (ri == null) { 5134 ri = new ResolveInfo(); 5135 ri.activityInfo = ai; 5136 } 5137 results.add(specificsPos, ri); 5138 ri.specificIndex = i; 5139 specificsPos++; 5140 } 5141 } 5142 5143 // Now we go through the remaining generic results and remove any 5144 // duplicate actions that are found here. 5145 N = results.size(); 5146 for (int i=specificsPos; i<N-1; i++) { 5147 final ResolveInfo rii = results.get(i); 5148 if (rii.filter == null) { 5149 continue; 5150 } 5151 5152 // Iterate over all of the actions of this result's intent 5153 // filter... typically this should be just one. 5154 final Iterator<String> it = rii.filter.actionsIterator(); 5155 if (it == null) { 5156 continue; 5157 } 5158 while (it.hasNext()) { 5159 final String action = it.next(); 5160 if (resultsAction != null && resultsAction.equals(action)) { 5161 // If this action was explicitly requested, then don't 5162 // remove things that have it. 5163 continue; 5164 } 5165 for (int j=i+1; j<N; j++) { 5166 final ResolveInfo rij = results.get(j); 5167 if (rij.filter != null && rij.filter.hasAction(action)) { 5168 results.remove(j); 5169 if (DEBUG_INTENT_MATCHING) Log.v( 5170 TAG, "Removing duplicate item from " + j 5171 + " due to action " + action + " at " + i); 5172 j--; 5173 N--; 5174 } 5175 } 5176 } 5177 5178 // If the caller didn't request filter information, drop it now 5179 // so we don't have to marshall/unmarshall it. 5180 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5181 rii.filter = null; 5182 } 5183 } 5184 5185 // Filter out the caller activity if so requested. 5186 if (caller != null) { 5187 N = results.size(); 5188 for (int i=0; i<N; i++) { 5189 ActivityInfo ainfo = results.get(i).activityInfo; 5190 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5191 && caller.getClassName().equals(ainfo.name)) { 5192 results.remove(i); 5193 break; 5194 } 5195 } 5196 } 5197 5198 // If the caller didn't request filter information, 5199 // drop them now so we don't have to 5200 // marshall/unmarshall it. 5201 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5202 N = results.size(); 5203 for (int i=0; i<N; i++) { 5204 results.get(i).filter = null; 5205 } 5206 } 5207 5208 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5209 return results; 5210 } 5211 5212 @Override 5213 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5214 int userId) { 5215 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5216 ComponentName comp = intent.getComponent(); 5217 if (comp == null) { 5218 if (intent.getSelector() != null) { 5219 intent = intent.getSelector(); 5220 comp = intent.getComponent(); 5221 } 5222 } 5223 if (comp != null) { 5224 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5225 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5226 if (ai != null) { 5227 ResolveInfo ri = new ResolveInfo(); 5228 ri.activityInfo = ai; 5229 list.add(ri); 5230 } 5231 return list; 5232 } 5233 5234 // reader 5235 synchronized (mPackages) { 5236 String pkgName = intent.getPackage(); 5237 if (pkgName == null) { 5238 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5239 } 5240 final PackageParser.Package pkg = mPackages.get(pkgName); 5241 if (pkg != null) { 5242 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5243 userId); 5244 } 5245 return null; 5246 } 5247 } 5248 5249 @Override 5250 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5251 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5252 if (!sUserManager.exists(userId)) return null; 5253 if (query != null) { 5254 if (query.size() >= 1) { 5255 // If there is more than one service with the same priority, 5256 // just arbitrarily pick the first one. 5257 return query.get(0); 5258 } 5259 } 5260 return null; 5261 } 5262 5263 @Override 5264 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5265 int userId) { 5266 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5267 ComponentName comp = intent.getComponent(); 5268 if (comp == null) { 5269 if (intent.getSelector() != null) { 5270 intent = intent.getSelector(); 5271 comp = intent.getComponent(); 5272 } 5273 } 5274 if (comp != null) { 5275 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5276 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5277 if (si != null) { 5278 final ResolveInfo ri = new ResolveInfo(); 5279 ri.serviceInfo = si; 5280 list.add(ri); 5281 } 5282 return list; 5283 } 5284 5285 // reader 5286 synchronized (mPackages) { 5287 String pkgName = intent.getPackage(); 5288 if (pkgName == null) { 5289 return mServices.queryIntent(intent, resolvedType, flags, userId); 5290 } 5291 final PackageParser.Package pkg = mPackages.get(pkgName); 5292 if (pkg != null) { 5293 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5294 userId); 5295 } 5296 return null; 5297 } 5298 } 5299 5300 @Override 5301 public List<ResolveInfo> queryIntentContentProviders( 5302 Intent intent, String resolvedType, int flags, int userId) { 5303 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5304 ComponentName comp = intent.getComponent(); 5305 if (comp == null) { 5306 if (intent.getSelector() != null) { 5307 intent = intent.getSelector(); 5308 comp = intent.getComponent(); 5309 } 5310 } 5311 if (comp != null) { 5312 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5313 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5314 if (pi != null) { 5315 final ResolveInfo ri = new ResolveInfo(); 5316 ri.providerInfo = pi; 5317 list.add(ri); 5318 } 5319 return list; 5320 } 5321 5322 // reader 5323 synchronized (mPackages) { 5324 String pkgName = intent.getPackage(); 5325 if (pkgName == null) { 5326 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5327 } 5328 final PackageParser.Package pkg = mPackages.get(pkgName); 5329 if (pkg != null) { 5330 return mProviders.queryIntentForPackage( 5331 intent, resolvedType, flags, pkg.providers, userId); 5332 } 5333 return null; 5334 } 5335 } 5336 5337 @Override 5338 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5339 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5340 5341 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5342 5343 // writer 5344 synchronized (mPackages) { 5345 ArrayList<PackageInfo> list; 5346 if (listUninstalled) { 5347 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5348 for (PackageSetting ps : mSettings.mPackages.values()) { 5349 PackageInfo pi; 5350 if (ps.pkg != null) { 5351 pi = generatePackageInfo(ps.pkg, flags, userId); 5352 } else { 5353 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5354 } 5355 if (pi != null) { 5356 list.add(pi); 5357 } 5358 } 5359 } else { 5360 list = new ArrayList<PackageInfo>(mPackages.size()); 5361 for (PackageParser.Package p : mPackages.values()) { 5362 PackageInfo pi = generatePackageInfo(p, flags, userId); 5363 if (pi != null) { 5364 list.add(pi); 5365 } 5366 } 5367 } 5368 5369 return new ParceledListSlice<PackageInfo>(list); 5370 } 5371 } 5372 5373 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5374 String[] permissions, boolean[] tmp, int flags, int userId) { 5375 int numMatch = 0; 5376 final PermissionsState permissionsState = ps.getPermissionsState(); 5377 for (int i=0; i<permissions.length; i++) { 5378 final String permission = permissions[i]; 5379 if (permissionsState.hasPermission(permission, userId)) { 5380 tmp[i] = true; 5381 numMatch++; 5382 } else { 5383 tmp[i] = false; 5384 } 5385 } 5386 if (numMatch == 0) { 5387 return; 5388 } 5389 PackageInfo pi; 5390 if (ps.pkg != null) { 5391 pi = generatePackageInfo(ps.pkg, flags, userId); 5392 } else { 5393 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5394 } 5395 // The above might return null in cases of uninstalled apps or install-state 5396 // skew across users/profiles. 5397 if (pi != null) { 5398 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5399 if (numMatch == permissions.length) { 5400 pi.requestedPermissions = permissions; 5401 } else { 5402 pi.requestedPermissions = new String[numMatch]; 5403 numMatch = 0; 5404 for (int i=0; i<permissions.length; i++) { 5405 if (tmp[i]) { 5406 pi.requestedPermissions[numMatch] = permissions[i]; 5407 numMatch++; 5408 } 5409 } 5410 } 5411 } 5412 list.add(pi); 5413 } 5414 } 5415 5416 @Override 5417 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5418 String[] permissions, int flags, int userId) { 5419 if (!sUserManager.exists(userId)) return null; 5420 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5421 5422 // writer 5423 synchronized (mPackages) { 5424 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5425 boolean[] tmpBools = new boolean[permissions.length]; 5426 if (listUninstalled) { 5427 for (PackageSetting ps : mSettings.mPackages.values()) { 5428 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5429 } 5430 } else { 5431 for (PackageParser.Package pkg : mPackages.values()) { 5432 PackageSetting ps = (PackageSetting)pkg.mExtras; 5433 if (ps != null) { 5434 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5435 userId); 5436 } 5437 } 5438 } 5439 5440 return new ParceledListSlice<PackageInfo>(list); 5441 } 5442 } 5443 5444 @Override 5445 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5446 if (!sUserManager.exists(userId)) return null; 5447 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5448 5449 // writer 5450 synchronized (mPackages) { 5451 ArrayList<ApplicationInfo> list; 5452 if (listUninstalled) { 5453 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5454 for (PackageSetting ps : mSettings.mPackages.values()) { 5455 ApplicationInfo ai; 5456 if (ps.pkg != null) { 5457 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5458 ps.readUserState(userId), userId); 5459 } else { 5460 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5461 } 5462 if (ai != null) { 5463 list.add(ai); 5464 } 5465 } 5466 } else { 5467 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5468 for (PackageParser.Package p : mPackages.values()) { 5469 if (p.mExtras != null) { 5470 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5471 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5472 if (ai != null) { 5473 list.add(ai); 5474 } 5475 } 5476 } 5477 } 5478 5479 return new ParceledListSlice<ApplicationInfo>(list); 5480 } 5481 } 5482 5483 public List<ApplicationInfo> getPersistentApplications(int flags) { 5484 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5485 5486 // reader 5487 synchronized (mPackages) { 5488 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5489 final int userId = UserHandle.getCallingUserId(); 5490 while (i.hasNext()) { 5491 final PackageParser.Package p = i.next(); 5492 if (p.applicationInfo != null 5493 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5494 && (!mSafeMode || isSystemApp(p))) { 5495 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5496 if (ps != null) { 5497 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5498 ps.readUserState(userId), userId); 5499 if (ai != null) { 5500 finalList.add(ai); 5501 } 5502 } 5503 } 5504 } 5505 } 5506 5507 return finalList; 5508 } 5509 5510 @Override 5511 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5512 if (!sUserManager.exists(userId)) return null; 5513 // reader 5514 synchronized (mPackages) { 5515 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5516 PackageSetting ps = provider != null 5517 ? mSettings.mPackages.get(provider.owner.packageName) 5518 : null; 5519 return ps != null 5520 && mSettings.isEnabledLPr(provider.info, flags, userId) 5521 && (!mSafeMode || (provider.info.applicationInfo.flags 5522 &ApplicationInfo.FLAG_SYSTEM) != 0) 5523 ? PackageParser.generateProviderInfo(provider, flags, 5524 ps.readUserState(userId), userId) 5525 : null; 5526 } 5527 } 5528 5529 /** 5530 * @deprecated 5531 */ 5532 @Deprecated 5533 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5534 // reader 5535 synchronized (mPackages) { 5536 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5537 .entrySet().iterator(); 5538 final int userId = UserHandle.getCallingUserId(); 5539 while (i.hasNext()) { 5540 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5541 PackageParser.Provider p = entry.getValue(); 5542 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5543 5544 if (ps != null && p.syncable 5545 && (!mSafeMode || (p.info.applicationInfo.flags 5546 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5547 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5548 ps.readUserState(userId), userId); 5549 if (info != null) { 5550 outNames.add(entry.getKey()); 5551 outInfo.add(info); 5552 } 5553 } 5554 } 5555 } 5556 } 5557 5558 @Override 5559 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5560 int uid, int flags) { 5561 ArrayList<ProviderInfo> finalList = null; 5562 // reader 5563 synchronized (mPackages) { 5564 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5565 final int userId = processName != null ? 5566 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5567 while (i.hasNext()) { 5568 final PackageParser.Provider p = i.next(); 5569 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5570 if (ps != null && p.info.authority != null 5571 && (processName == null 5572 || (p.info.processName.equals(processName) 5573 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5574 && mSettings.isEnabledLPr(p.info, flags, userId) 5575 && (!mSafeMode 5576 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5577 if (finalList == null) { 5578 finalList = new ArrayList<ProviderInfo>(3); 5579 } 5580 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5581 ps.readUserState(userId), userId); 5582 if (info != null) { 5583 finalList.add(info); 5584 } 5585 } 5586 } 5587 } 5588 5589 if (finalList != null) { 5590 Collections.sort(finalList, mProviderInitOrderSorter); 5591 return new ParceledListSlice<ProviderInfo>(finalList); 5592 } 5593 5594 return null; 5595 } 5596 5597 @Override 5598 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5599 int flags) { 5600 // reader 5601 synchronized (mPackages) { 5602 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5603 return PackageParser.generateInstrumentationInfo(i, flags); 5604 } 5605 } 5606 5607 @Override 5608 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5609 int flags) { 5610 ArrayList<InstrumentationInfo> finalList = 5611 new ArrayList<InstrumentationInfo>(); 5612 5613 // reader 5614 synchronized (mPackages) { 5615 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5616 while (i.hasNext()) { 5617 final PackageParser.Instrumentation p = i.next(); 5618 if (targetPackage == null 5619 || targetPackage.equals(p.info.targetPackage)) { 5620 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5621 flags); 5622 if (ii != null) { 5623 finalList.add(ii); 5624 } 5625 } 5626 } 5627 } 5628 5629 return finalList; 5630 } 5631 5632 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5633 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5634 if (overlays == null) { 5635 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5636 return; 5637 } 5638 for (PackageParser.Package opkg : overlays.values()) { 5639 // Not much to do if idmap fails: we already logged the error 5640 // and we certainly don't want to abort installation of pkg simply 5641 // because an overlay didn't fit properly. For these reasons, 5642 // ignore the return value of createIdmapForPackagePairLI. 5643 createIdmapForPackagePairLI(pkg, opkg); 5644 } 5645 } 5646 5647 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5648 PackageParser.Package opkg) { 5649 if (!opkg.mTrustedOverlay) { 5650 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5651 opkg.baseCodePath + ": overlay not trusted"); 5652 return false; 5653 } 5654 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5655 if (overlaySet == null) { 5656 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5657 opkg.baseCodePath + " but target package has no known overlays"); 5658 return false; 5659 } 5660 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5661 // TODO: generate idmap for split APKs 5662 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5663 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5664 + opkg.baseCodePath); 5665 return false; 5666 } 5667 PackageParser.Package[] overlayArray = 5668 overlaySet.values().toArray(new PackageParser.Package[0]); 5669 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5670 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5671 return p1.mOverlayPriority - p2.mOverlayPriority; 5672 } 5673 }; 5674 Arrays.sort(overlayArray, cmp); 5675 5676 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5677 int i = 0; 5678 for (PackageParser.Package p : overlayArray) { 5679 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5680 } 5681 return true; 5682 } 5683 5684 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5685 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5686 try { 5687 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5688 } finally { 5689 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5690 } 5691 } 5692 5693 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5694 final File[] files = dir.listFiles(); 5695 if (ArrayUtils.isEmpty(files)) { 5696 Log.d(TAG, "No files in app dir " + dir); 5697 return; 5698 } 5699 5700 if (DEBUG_PACKAGE_SCANNING) { 5701 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5702 + " flags=0x" + Integer.toHexString(parseFlags)); 5703 } 5704 5705 for (File file : files) { 5706 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5707 && !PackageInstallerService.isStageName(file.getName()); 5708 if (!isPackage) { 5709 // Ignore entries which are not packages 5710 continue; 5711 } 5712 try { 5713 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5714 scanFlags, currentTime, null); 5715 } catch (PackageManagerException e) { 5716 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5717 5718 // Delete invalid userdata apps 5719 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5720 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5721 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5722 if (file.isDirectory()) { 5723 mInstaller.rmPackageDir(file.getAbsolutePath()); 5724 } else { 5725 file.delete(); 5726 } 5727 } 5728 } 5729 } 5730 } 5731 5732 private static File getSettingsProblemFile() { 5733 File dataDir = Environment.getDataDirectory(); 5734 File systemDir = new File(dataDir, "system"); 5735 File fname = new File(systemDir, "uiderrors.txt"); 5736 return fname; 5737 } 5738 5739 static void reportSettingsProblem(int priority, String msg) { 5740 logCriticalInfo(priority, msg); 5741 } 5742 5743 static void logCriticalInfo(int priority, String msg) { 5744 Slog.println(priority, TAG, msg); 5745 EventLogTags.writePmCriticalInfo(msg); 5746 try { 5747 File fname = getSettingsProblemFile(); 5748 FileOutputStream out = new FileOutputStream(fname, true); 5749 PrintWriter pw = new FastPrintWriter(out); 5750 SimpleDateFormat formatter = new SimpleDateFormat(); 5751 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5752 pw.println(dateString + ": " + msg); 5753 pw.close(); 5754 FileUtils.setPermissions( 5755 fname.toString(), 5756 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5757 -1, -1); 5758 } catch (java.io.IOException e) { 5759 } 5760 } 5761 5762 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5763 PackageParser.Package pkg, File srcFile, int parseFlags) 5764 throws PackageManagerException { 5765 if (ps != null 5766 && ps.codePath.equals(srcFile) 5767 && ps.timeStamp == srcFile.lastModified() 5768 && !isCompatSignatureUpdateNeeded(pkg) 5769 && !isRecoverSignatureUpdateNeeded(pkg)) { 5770 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5771 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5772 ArraySet<PublicKey> signingKs; 5773 synchronized (mPackages) { 5774 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5775 } 5776 if (ps.signatures.mSignatures != null 5777 && ps.signatures.mSignatures.length != 0 5778 && signingKs != null) { 5779 // Optimization: reuse the existing cached certificates 5780 // if the package appears to be unchanged. 5781 pkg.mSignatures = ps.signatures.mSignatures; 5782 pkg.mSigningKeys = signingKs; 5783 return; 5784 } 5785 5786 Slog.w(TAG, "PackageSetting for " + ps.name 5787 + " is missing signatures. Collecting certs again to recover them."); 5788 } else { 5789 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5790 } 5791 5792 try { 5793 pp.collectCertificates(pkg, parseFlags); 5794 pp.collectManifestDigest(pkg); 5795 } catch (PackageParserException e) { 5796 throw PackageManagerException.from(e); 5797 } 5798 } 5799 5800 /** 5801 * Traces a package scan. 5802 * @see #scanPackageLI(File, int, int, long, UserHandle) 5803 */ 5804 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5805 long currentTime, UserHandle user) throws PackageManagerException { 5806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5807 try { 5808 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5809 } finally { 5810 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5811 } 5812 } 5813 5814 /** 5815 * Scans a package and returns the newly parsed package. 5816 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5817 */ 5818 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5819 long currentTime, UserHandle user) throws PackageManagerException { 5820 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5821 parseFlags |= mDefParseFlags; 5822 PackageParser pp = new PackageParser(); 5823 pp.setSeparateProcesses(mSeparateProcesses); 5824 pp.setOnlyCoreApps(mOnlyCore); 5825 pp.setDisplayMetrics(mMetrics); 5826 5827 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5828 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5829 } 5830 5831 final PackageParser.Package pkg; 5832 try { 5833 pkg = pp.parsePackage(scanFile, parseFlags); 5834 } catch (PackageParserException e) { 5835 throw PackageManagerException.from(e); 5836 } 5837 5838 PackageSetting ps = null; 5839 PackageSetting updatedPkg; 5840 // reader 5841 synchronized (mPackages) { 5842 // Look to see if we already know about this package. 5843 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5844 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5845 // This package has been renamed to its original name. Let's 5846 // use that. 5847 ps = mSettings.peekPackageLPr(oldName); 5848 } 5849 // If there was no original package, see one for the real package name. 5850 if (ps == null) { 5851 ps = mSettings.peekPackageLPr(pkg.packageName); 5852 } 5853 // Check to see if this package could be hiding/updating a system 5854 // package. Must look for it either under the original or real 5855 // package name depending on our state. 5856 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5857 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5858 } 5859 boolean updatedPkgBetter = false; 5860 // First check if this is a system package that may involve an update 5861 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5862 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5863 // it needs to drop FLAG_PRIVILEGED. 5864 if (locationIsPrivileged(scanFile)) { 5865 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5866 } else { 5867 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5868 } 5869 5870 if (ps != null && !ps.codePath.equals(scanFile)) { 5871 // The path has changed from what was last scanned... check the 5872 // version of the new path against what we have stored to determine 5873 // what to do. 5874 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5875 if (pkg.mVersionCode <= ps.versionCode) { 5876 // The system package has been updated and the code path does not match 5877 // Ignore entry. Skip it. 5878 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5879 + " ignored: updated version " + ps.versionCode 5880 + " better than this " + pkg.mVersionCode); 5881 if (!updatedPkg.codePath.equals(scanFile)) { 5882 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5883 + ps.name + " changing from " + updatedPkg.codePathString 5884 + " to " + scanFile); 5885 updatedPkg.codePath = scanFile; 5886 updatedPkg.codePathString = scanFile.toString(); 5887 updatedPkg.resourcePath = scanFile; 5888 updatedPkg.resourcePathString = scanFile.toString(); 5889 } 5890 updatedPkg.pkg = pkg; 5891 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5892 "Package " + ps.name + " at " + scanFile 5893 + " ignored: updated version " + ps.versionCode 5894 + " better than this " + pkg.mVersionCode); 5895 } else { 5896 // The current app on the system partition is better than 5897 // what we have updated to on the data partition; switch 5898 // back to the system partition version. 5899 // At this point, its safely assumed that package installation for 5900 // apps in system partition will go through. If not there won't be a working 5901 // version of the app 5902 // writer 5903 synchronized (mPackages) { 5904 // Just remove the loaded entries from package lists. 5905 mPackages.remove(ps.name); 5906 } 5907 5908 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5909 + " reverting from " + ps.codePathString 5910 + ": new version " + pkg.mVersionCode 5911 + " better than installed " + ps.versionCode); 5912 5913 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5914 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5915 synchronized (mInstallLock) { 5916 args.cleanUpResourcesLI(); 5917 } 5918 synchronized (mPackages) { 5919 mSettings.enableSystemPackageLPw(ps.name); 5920 } 5921 updatedPkgBetter = true; 5922 } 5923 } 5924 } 5925 5926 if (updatedPkg != null) { 5927 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5928 // initially 5929 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5930 5931 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5932 // flag set initially 5933 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5934 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5935 } 5936 } 5937 5938 // Verify certificates against what was last scanned 5939 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5940 5941 /* 5942 * A new system app appeared, but we already had a non-system one of the 5943 * same name installed earlier. 5944 */ 5945 boolean shouldHideSystemApp = false; 5946 if (updatedPkg == null && ps != null 5947 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5948 /* 5949 * Check to make sure the signatures match first. If they don't, 5950 * wipe the installed application and its data. 5951 */ 5952 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5953 != PackageManager.SIGNATURE_MATCH) { 5954 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5955 + " signatures don't match existing userdata copy; removing"); 5956 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5957 ps = null; 5958 } else { 5959 /* 5960 * If the newly-added system app is an older version than the 5961 * already installed version, hide it. It will be scanned later 5962 * and re-added like an update. 5963 */ 5964 if (pkg.mVersionCode <= ps.versionCode) { 5965 shouldHideSystemApp = true; 5966 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5967 + " but new version " + pkg.mVersionCode + " better than installed " 5968 + ps.versionCode + "; hiding system"); 5969 } else { 5970 /* 5971 * The newly found system app is a newer version that the 5972 * one previously installed. Simply remove the 5973 * already-installed application and replace it with our own 5974 * while keeping the application data. 5975 */ 5976 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5977 + " reverting from " + ps.codePathString + ": new version " 5978 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5979 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5980 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5981 synchronized (mInstallLock) { 5982 args.cleanUpResourcesLI(); 5983 } 5984 } 5985 } 5986 } 5987 5988 // The apk is forward locked (not public) if its code and resources 5989 // are kept in different files. (except for app in either system or 5990 // vendor path). 5991 // TODO grab this value from PackageSettings 5992 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5993 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5994 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5995 } 5996 } 5997 5998 // TODO: extend to support forward-locked splits 5999 String resourcePath = null; 6000 String baseResourcePath = null; 6001 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6002 if (ps != null && ps.resourcePathString != null) { 6003 resourcePath = ps.resourcePathString; 6004 baseResourcePath = ps.resourcePathString; 6005 } else { 6006 // Should not happen at all. Just log an error. 6007 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6008 } 6009 } else { 6010 resourcePath = pkg.codePath; 6011 baseResourcePath = pkg.baseCodePath; 6012 } 6013 6014 // Set application objects path explicitly. 6015 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6016 pkg.applicationInfo.setCodePath(pkg.codePath); 6017 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6018 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6019 pkg.applicationInfo.setResourcePath(resourcePath); 6020 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6021 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6022 6023 // Note that we invoke the following method only if we are about to unpack an application 6024 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6025 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6026 6027 /* 6028 * If the system app should be overridden by a previously installed 6029 * data, hide the system app now and let the /data/app scan pick it up 6030 * again. 6031 */ 6032 if (shouldHideSystemApp) { 6033 synchronized (mPackages) { 6034 mSettings.disableSystemPackageLPw(pkg.packageName); 6035 } 6036 } 6037 6038 return scannedPkg; 6039 } 6040 6041 private static String fixProcessName(String defProcessName, 6042 String processName, int uid) { 6043 if (processName == null) { 6044 return defProcessName; 6045 } 6046 return processName; 6047 } 6048 6049 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6050 throws PackageManagerException { 6051 if (pkgSetting.signatures.mSignatures != null) { 6052 // Already existing package. Make sure signatures match 6053 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6054 == PackageManager.SIGNATURE_MATCH; 6055 if (!match) { 6056 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6057 == PackageManager.SIGNATURE_MATCH; 6058 } 6059 if (!match) { 6060 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6061 == PackageManager.SIGNATURE_MATCH; 6062 } 6063 if (!match) { 6064 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6065 + pkg.packageName + " signatures do not match the " 6066 + "previously installed version; ignoring!"); 6067 } 6068 } 6069 6070 // Check for shared user signatures 6071 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6072 // Already existing package. Make sure signatures match 6073 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6074 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6075 if (!match) { 6076 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6077 == PackageManager.SIGNATURE_MATCH; 6078 } 6079 if (!match) { 6080 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6081 == PackageManager.SIGNATURE_MATCH; 6082 } 6083 if (!match) { 6084 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6085 "Package " + pkg.packageName 6086 + " has no signatures that match those in shared user " 6087 + pkgSetting.sharedUser.name + "; ignoring!"); 6088 } 6089 } 6090 } 6091 6092 /** 6093 * Enforces that only the system UID or root's UID can call a method exposed 6094 * via Binder. 6095 * 6096 * @param message used as message if SecurityException is thrown 6097 * @throws SecurityException if the caller is not system or root 6098 */ 6099 private static final void enforceSystemOrRoot(String message) { 6100 final int uid = Binder.getCallingUid(); 6101 if (uid != Process.SYSTEM_UID && uid != 0) { 6102 throw new SecurityException(message); 6103 } 6104 } 6105 6106 @Override 6107 public void performBootDexOpt() { 6108 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6109 6110 // Before everything else, see whether we need to fstrim. 6111 try { 6112 IMountService ms = PackageHelper.getMountService(); 6113 if (ms != null) { 6114 final boolean isUpgrade = isUpgrade(); 6115 boolean doTrim = isUpgrade; 6116 if (doTrim) { 6117 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6118 } else { 6119 final long interval = android.provider.Settings.Global.getLong( 6120 mContext.getContentResolver(), 6121 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6122 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6123 if (interval > 0) { 6124 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6125 if (timeSinceLast > interval) { 6126 doTrim = true; 6127 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6128 + "; running immediately"); 6129 } 6130 } 6131 } 6132 if (doTrim) { 6133 if (!isFirstBoot()) { 6134 try { 6135 ActivityManagerNative.getDefault().showBootMessage( 6136 mContext.getResources().getString( 6137 R.string.android_upgrading_fstrim), true); 6138 } catch (RemoteException e) { 6139 } 6140 } 6141 ms.runMaintenance(); 6142 } 6143 } else { 6144 Slog.e(TAG, "Mount service unavailable!"); 6145 } 6146 } catch (RemoteException e) { 6147 // Can't happen; MountService is local 6148 } 6149 6150 final ArraySet<PackageParser.Package> pkgs; 6151 synchronized (mPackages) { 6152 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6153 } 6154 6155 if (pkgs != null) { 6156 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6157 // in case the device runs out of space. 6158 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6159 // Give priority to core apps. 6160 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6161 PackageParser.Package pkg = it.next(); 6162 if (pkg.coreApp) { 6163 if (DEBUG_DEXOPT) { 6164 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6165 } 6166 sortedPkgs.add(pkg); 6167 it.remove(); 6168 } 6169 } 6170 // Give priority to system apps that listen for pre boot complete. 6171 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6172 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6173 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6174 PackageParser.Package pkg = it.next(); 6175 if (pkgNames.contains(pkg.packageName)) { 6176 if (DEBUG_DEXOPT) { 6177 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6178 } 6179 sortedPkgs.add(pkg); 6180 it.remove(); 6181 } 6182 } 6183 // Filter out packages that aren't recently used. 6184 filterRecentlyUsedApps(pkgs); 6185 // Add all remaining apps. 6186 for (PackageParser.Package pkg : pkgs) { 6187 if (DEBUG_DEXOPT) { 6188 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6189 } 6190 sortedPkgs.add(pkg); 6191 } 6192 6193 // If we want to be lazy, filter everything that wasn't recently used. 6194 if (mLazyDexOpt) { 6195 filterRecentlyUsedApps(sortedPkgs); 6196 } 6197 6198 int i = 0; 6199 int total = sortedPkgs.size(); 6200 File dataDir = Environment.getDataDirectory(); 6201 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6202 if (lowThreshold == 0) { 6203 throw new IllegalStateException("Invalid low memory threshold"); 6204 } 6205 for (PackageParser.Package pkg : sortedPkgs) { 6206 long usableSpace = dataDir.getUsableSpace(); 6207 if (usableSpace < lowThreshold) { 6208 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6209 break; 6210 } 6211 performBootDexOpt(pkg, ++i, total); 6212 } 6213 } 6214 } 6215 6216 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6217 // Filter out packages that aren't recently used. 6218 // 6219 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6220 // should do a full dexopt. 6221 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6222 int total = pkgs.size(); 6223 int skipped = 0; 6224 long now = System.currentTimeMillis(); 6225 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6226 PackageParser.Package pkg = i.next(); 6227 long then = pkg.mLastPackageUsageTimeInMills; 6228 if (then + mDexOptLRUThresholdInMills < now) { 6229 if (DEBUG_DEXOPT) { 6230 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6231 ((then == 0) ? "never" : new Date(then))); 6232 } 6233 i.remove(); 6234 skipped++; 6235 } 6236 } 6237 if (DEBUG_DEXOPT) { 6238 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6239 } 6240 } 6241 } 6242 6243 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6244 List<ResolveInfo> ris = null; 6245 try { 6246 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6247 intent, null, 0, userId); 6248 } catch (RemoteException e) { 6249 } 6250 ArraySet<String> pkgNames = new ArraySet<String>(); 6251 if (ris != null) { 6252 for (ResolveInfo ri : ris) { 6253 pkgNames.add(ri.activityInfo.packageName); 6254 } 6255 } 6256 return pkgNames; 6257 } 6258 6259 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6260 if (DEBUG_DEXOPT) { 6261 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6262 } 6263 if (!isFirstBoot()) { 6264 try { 6265 ActivityManagerNative.getDefault().showBootMessage( 6266 mContext.getResources().getString(R.string.android_upgrading_apk, 6267 curr, total), true); 6268 } catch (RemoteException e) { 6269 } 6270 } 6271 PackageParser.Package p = pkg; 6272 synchronized (mInstallLock) { 6273 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6274 false /* force dex */, false /* defer */, true /* include dependencies */, 6275 false /* boot complete */, false /*useJit*/); 6276 } 6277 } 6278 6279 @Override 6280 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6281 return performDexOptTraced(packageName, instructionSet, false); 6282 } 6283 6284 public boolean performDexOpt( 6285 String packageName, String instructionSet, boolean backgroundDexopt) { 6286 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6287 } 6288 6289 private boolean performDexOptTraced( 6290 String packageName, String instructionSet, boolean backgroundDexopt) { 6291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6292 try { 6293 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6294 } finally { 6295 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6296 } 6297 } 6298 6299 private boolean performDexOptInternal( 6300 String packageName, String instructionSet, boolean backgroundDexopt) { 6301 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6302 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6303 if (!dexopt && !updateUsage) { 6304 // We aren't going to dexopt or update usage, so bail early. 6305 return false; 6306 } 6307 PackageParser.Package p; 6308 final String targetInstructionSet; 6309 synchronized (mPackages) { 6310 p = mPackages.get(packageName); 6311 if (p == null) { 6312 return false; 6313 } 6314 if (updateUsage) { 6315 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6316 } 6317 mPackageUsage.write(false); 6318 if (!dexopt) { 6319 // We aren't going to dexopt, so bail early. 6320 return false; 6321 } 6322 6323 targetInstructionSet = instructionSet != null ? instructionSet : 6324 getPrimaryInstructionSet(p.applicationInfo); 6325 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6326 return false; 6327 } 6328 } 6329 long callingId = Binder.clearCallingIdentity(); 6330 try { 6331 synchronized (mInstallLock) { 6332 final String[] instructionSets = new String[] { targetInstructionSet }; 6333 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6334 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6335 true /* boot complete */, false /*useJit*/); 6336 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6337 } 6338 } finally { 6339 Binder.restoreCallingIdentity(callingId); 6340 } 6341 } 6342 6343 public ArraySet<String> getPackagesThatNeedDexOpt() { 6344 ArraySet<String> pkgs = null; 6345 synchronized (mPackages) { 6346 for (PackageParser.Package p : mPackages.values()) { 6347 if (DEBUG_DEXOPT) { 6348 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6349 } 6350 if (!p.mDexOptPerformed.isEmpty()) { 6351 continue; 6352 } 6353 if (pkgs == null) { 6354 pkgs = new ArraySet<String>(); 6355 } 6356 pkgs.add(p.packageName); 6357 } 6358 } 6359 return pkgs; 6360 } 6361 6362 public void shutdown() { 6363 mPackageUsage.write(true); 6364 } 6365 6366 @Override 6367 public void forceDexOpt(String packageName) { 6368 enforceSystemOrRoot("forceDexOpt"); 6369 6370 PackageParser.Package pkg; 6371 synchronized (mPackages) { 6372 pkg = mPackages.get(packageName); 6373 if (pkg == null) { 6374 throw new IllegalArgumentException("Missing package: " + packageName); 6375 } 6376 } 6377 6378 synchronized (mInstallLock) { 6379 final String[] instructionSets = new String[] { 6380 getPrimaryInstructionSet(pkg.applicationInfo) }; 6381 6382 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6383 6384 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6385 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6386 true /* boot complete */, false /*useJit*/); 6387 6388 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6389 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6390 throw new IllegalStateException("Failed to dexopt: " + res); 6391 } 6392 } 6393 } 6394 6395 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6396 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6397 Slog.w(TAG, "Unable to update from " + oldPkg.name 6398 + " to " + newPkg.packageName 6399 + ": old package not in system partition"); 6400 return false; 6401 } else if (mPackages.get(oldPkg.name) != null) { 6402 Slog.w(TAG, "Unable to update from " + oldPkg.name 6403 + " to " + newPkg.packageName 6404 + ": old package still exists"); 6405 return false; 6406 } 6407 return true; 6408 } 6409 6410 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6411 int[] users = sUserManager.getUserIds(); 6412 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6413 if (res < 0) { 6414 return res; 6415 } 6416 for (int user : users) { 6417 if (user != 0) { 6418 res = mInstaller.createUserData(volumeUuid, packageName, 6419 UserHandle.getUid(user, uid), user, seinfo); 6420 if (res < 0) { 6421 return res; 6422 } 6423 } 6424 } 6425 return res; 6426 } 6427 6428 private int removeDataDirsLI(String volumeUuid, String packageName) { 6429 int[] users = sUserManager.getUserIds(); 6430 int res = 0; 6431 for (int user : users) { 6432 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6433 if (resInner < 0) { 6434 res = resInner; 6435 } 6436 } 6437 6438 return res; 6439 } 6440 6441 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6442 int[] users = sUserManager.getUserIds(); 6443 int res = 0; 6444 for (int user : users) { 6445 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6446 if (resInner < 0) { 6447 res = resInner; 6448 } 6449 } 6450 return res; 6451 } 6452 6453 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6454 PackageParser.Package changingLib) { 6455 if (file.path != null) { 6456 usesLibraryFiles.add(file.path); 6457 return; 6458 } 6459 PackageParser.Package p = mPackages.get(file.apk); 6460 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6461 // If we are doing this while in the middle of updating a library apk, 6462 // then we need to make sure to use that new apk for determining the 6463 // dependencies here. (We haven't yet finished committing the new apk 6464 // to the package manager state.) 6465 if (p == null || p.packageName.equals(changingLib.packageName)) { 6466 p = changingLib; 6467 } 6468 } 6469 if (p != null) { 6470 usesLibraryFiles.addAll(p.getAllCodePaths()); 6471 } 6472 } 6473 6474 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6475 PackageParser.Package changingLib) throws PackageManagerException { 6476 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6477 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6478 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6479 for (int i=0; i<N; i++) { 6480 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6481 if (file == null) { 6482 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6483 "Package " + pkg.packageName + " requires unavailable shared library " 6484 + pkg.usesLibraries.get(i) + "; failing!"); 6485 } 6486 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6487 } 6488 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6489 for (int i=0; i<N; i++) { 6490 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6491 if (file == null) { 6492 Slog.w(TAG, "Package " + pkg.packageName 6493 + " desires unavailable shared library " 6494 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6495 } else { 6496 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6497 } 6498 } 6499 N = usesLibraryFiles.size(); 6500 if (N > 0) { 6501 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6502 } else { 6503 pkg.usesLibraryFiles = null; 6504 } 6505 } 6506 } 6507 6508 private static boolean hasString(List<String> list, List<String> which) { 6509 if (list == null) { 6510 return false; 6511 } 6512 for (int i=list.size()-1; i>=0; i--) { 6513 for (int j=which.size()-1; j>=0; j--) { 6514 if (which.get(j).equals(list.get(i))) { 6515 return true; 6516 } 6517 } 6518 } 6519 return false; 6520 } 6521 6522 private void updateAllSharedLibrariesLPw() { 6523 for (PackageParser.Package pkg : mPackages.values()) { 6524 try { 6525 updateSharedLibrariesLPw(pkg, null); 6526 } catch (PackageManagerException e) { 6527 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6528 } 6529 } 6530 } 6531 6532 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6533 PackageParser.Package changingPkg) { 6534 ArrayList<PackageParser.Package> res = null; 6535 for (PackageParser.Package pkg : mPackages.values()) { 6536 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6537 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6538 if (res == null) { 6539 res = new ArrayList<PackageParser.Package>(); 6540 } 6541 res.add(pkg); 6542 try { 6543 updateSharedLibrariesLPw(pkg, changingPkg); 6544 } catch (PackageManagerException e) { 6545 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6546 } 6547 } 6548 } 6549 return res; 6550 } 6551 6552 /** 6553 * Derive the value of the {@code cpuAbiOverride} based on the provided 6554 * value and an optional stored value from the package settings. 6555 */ 6556 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6557 String cpuAbiOverride = null; 6558 6559 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6560 cpuAbiOverride = null; 6561 } else if (abiOverride != null) { 6562 cpuAbiOverride = abiOverride; 6563 } else if (settings != null) { 6564 cpuAbiOverride = settings.cpuAbiOverrideString; 6565 } 6566 6567 return cpuAbiOverride; 6568 } 6569 6570 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6571 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6572 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6573 try { 6574 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6575 } finally { 6576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6577 } 6578 } 6579 6580 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6581 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6582 boolean success = false; 6583 try { 6584 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6585 currentTime, user); 6586 success = true; 6587 return res; 6588 } finally { 6589 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6590 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6591 } 6592 } 6593 } 6594 6595 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6596 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6597 final File scanFile = new File(pkg.codePath); 6598 if (pkg.applicationInfo.getCodePath() == null || 6599 pkg.applicationInfo.getResourcePath() == null) { 6600 // Bail out. The resource and code paths haven't been set. 6601 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6602 "Code and resource paths haven't been set correctly"); 6603 } 6604 6605 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6606 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6607 } else { 6608 // Only allow system apps to be flagged as core apps. 6609 pkg.coreApp = false; 6610 } 6611 6612 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6613 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6614 } 6615 6616 if (mCustomResolverComponentName != null && 6617 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6618 setUpCustomResolverActivity(pkg); 6619 } 6620 6621 if (pkg.packageName.equals("android")) { 6622 synchronized (mPackages) { 6623 if (mAndroidApplication != null) { 6624 Slog.w(TAG, "*************************************************"); 6625 Slog.w(TAG, "Core android package being redefined. Skipping."); 6626 Slog.w(TAG, " file=" + scanFile); 6627 Slog.w(TAG, "*************************************************"); 6628 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6629 "Core android package being redefined. Skipping."); 6630 } 6631 6632 // Set up information for our fall-back user intent resolution activity. 6633 mPlatformPackage = pkg; 6634 pkg.mVersionCode = mSdkVersion; 6635 mAndroidApplication = pkg.applicationInfo; 6636 6637 if (!mResolverReplaced) { 6638 mResolveActivity.applicationInfo = mAndroidApplication; 6639 mResolveActivity.name = ResolverActivity.class.getName(); 6640 mResolveActivity.packageName = mAndroidApplication.packageName; 6641 mResolveActivity.processName = "system:ui"; 6642 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6643 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6644 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6645 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6646 mResolveActivity.exported = true; 6647 mResolveActivity.enabled = true; 6648 mResolveInfo.activityInfo = mResolveActivity; 6649 mResolveInfo.priority = 0; 6650 mResolveInfo.preferredOrder = 0; 6651 mResolveInfo.match = 0; 6652 mResolveComponentName = new ComponentName( 6653 mAndroidApplication.packageName, mResolveActivity.name); 6654 } 6655 } 6656 } 6657 6658 if (DEBUG_PACKAGE_SCANNING) { 6659 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6660 Log.d(TAG, "Scanning package " + pkg.packageName); 6661 } 6662 6663 if (mPackages.containsKey(pkg.packageName) 6664 || mSharedLibraries.containsKey(pkg.packageName)) { 6665 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6666 "Application package " + pkg.packageName 6667 + " already installed. Skipping duplicate."); 6668 } 6669 6670 // If we're only installing presumed-existing packages, require that the 6671 // scanned APK is both already known and at the path previously established 6672 // for it. Previously unknown packages we pick up normally, but if we have an 6673 // a priori expectation about this package's install presence, enforce it. 6674 // With a singular exception for new system packages. When an OTA contains 6675 // a new system package, we allow the codepath to change from a system location 6676 // to the user-installed location. If we don't allow this change, any newer, 6677 // user-installed version of the application will be ignored. 6678 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6679 if (mExpectingBetter.containsKey(pkg.packageName)) { 6680 logCriticalInfo(Log.WARN, 6681 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6682 } else { 6683 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6684 if (known != null) { 6685 if (DEBUG_PACKAGE_SCANNING) { 6686 Log.d(TAG, "Examining " + pkg.codePath 6687 + " and requiring known paths " + known.codePathString 6688 + " & " + known.resourcePathString); 6689 } 6690 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6691 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6692 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6693 "Application package " + pkg.packageName 6694 + " found at " + pkg.applicationInfo.getCodePath() 6695 + " but expected at " + known.codePathString + "; ignoring."); 6696 } 6697 } 6698 } 6699 } 6700 6701 // Initialize package source and resource directories 6702 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6703 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6704 6705 SharedUserSetting suid = null; 6706 PackageSetting pkgSetting = null; 6707 6708 if (!isSystemApp(pkg)) { 6709 // Only system apps can use these features. 6710 pkg.mOriginalPackages = null; 6711 pkg.mRealPackage = null; 6712 pkg.mAdoptPermissions = null; 6713 } 6714 6715 // writer 6716 synchronized (mPackages) { 6717 if (pkg.mSharedUserId != null) { 6718 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6719 if (suid == null) { 6720 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6721 "Creating application package " + pkg.packageName 6722 + " for shared user failed"); 6723 } 6724 if (DEBUG_PACKAGE_SCANNING) { 6725 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6726 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6727 + "): packages=" + suid.packages); 6728 } 6729 } 6730 6731 // Check if we are renaming from an original package name. 6732 PackageSetting origPackage = null; 6733 String realName = null; 6734 if (pkg.mOriginalPackages != null) { 6735 // This package may need to be renamed to a previously 6736 // installed name. Let's check on that... 6737 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6738 if (pkg.mOriginalPackages.contains(renamed)) { 6739 // This package had originally been installed as the 6740 // original name, and we have already taken care of 6741 // transitioning to the new one. Just update the new 6742 // one to continue using the old name. 6743 realName = pkg.mRealPackage; 6744 if (!pkg.packageName.equals(renamed)) { 6745 // Callers into this function may have already taken 6746 // care of renaming the package; only do it here if 6747 // it is not already done. 6748 pkg.setPackageName(renamed); 6749 } 6750 6751 } else { 6752 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6753 if ((origPackage = mSettings.peekPackageLPr( 6754 pkg.mOriginalPackages.get(i))) != null) { 6755 // We do have the package already installed under its 6756 // original name... should we use it? 6757 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6758 // New package is not compatible with original. 6759 origPackage = null; 6760 continue; 6761 } else if (origPackage.sharedUser != null) { 6762 // Make sure uid is compatible between packages. 6763 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6764 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6765 + " to " + pkg.packageName + ": old uid " 6766 + origPackage.sharedUser.name 6767 + " differs from " + pkg.mSharedUserId); 6768 origPackage = null; 6769 continue; 6770 } 6771 } else { 6772 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6773 + pkg.packageName + " to old name " + origPackage.name); 6774 } 6775 break; 6776 } 6777 } 6778 } 6779 } 6780 6781 if (mTransferedPackages.contains(pkg.packageName)) { 6782 Slog.w(TAG, "Package " + pkg.packageName 6783 + " was transferred to another, but its .apk remains"); 6784 } 6785 6786 // Just create the setting, don't add it yet. For already existing packages 6787 // the PkgSetting exists already and doesn't have to be created. 6788 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6789 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6790 pkg.applicationInfo.primaryCpuAbi, 6791 pkg.applicationInfo.secondaryCpuAbi, 6792 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6793 user, false); 6794 if (pkgSetting == null) { 6795 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6796 "Creating application package " + pkg.packageName + " failed"); 6797 } 6798 6799 if (pkgSetting.origPackage != null) { 6800 // If we are first transitioning from an original package, 6801 // fix up the new package's name now. We need to do this after 6802 // looking up the package under its new name, so getPackageLP 6803 // can take care of fiddling things correctly. 6804 pkg.setPackageName(origPackage.name); 6805 6806 // File a report about this. 6807 String msg = "New package " + pkgSetting.realName 6808 + " renamed to replace old package " + pkgSetting.name; 6809 reportSettingsProblem(Log.WARN, msg); 6810 6811 // Make a note of it. 6812 mTransferedPackages.add(origPackage.name); 6813 6814 // No longer need to retain this. 6815 pkgSetting.origPackage = null; 6816 } 6817 6818 if (realName != null) { 6819 // Make a note of it. 6820 mTransferedPackages.add(pkg.packageName); 6821 } 6822 6823 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6824 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6825 } 6826 6827 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6828 // Check all shared libraries and map to their actual file path. 6829 // We only do this here for apps not on a system dir, because those 6830 // are the only ones that can fail an install due to this. We 6831 // will take care of the system apps by updating all of their 6832 // library paths after the scan is done. 6833 updateSharedLibrariesLPw(pkg, null); 6834 } 6835 6836 if (mFoundPolicyFile) { 6837 SELinuxMMAC.assignSeinfoValue(pkg); 6838 } 6839 6840 pkg.applicationInfo.uid = pkgSetting.appId; 6841 pkg.mExtras = pkgSetting; 6842 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6843 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6844 // We just determined the app is signed correctly, so bring 6845 // over the latest parsed certs. 6846 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6847 } else { 6848 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6849 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6850 "Package " + pkg.packageName + " upgrade keys do not match the " 6851 + "previously installed version"); 6852 } else { 6853 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6854 String msg = "System package " + pkg.packageName 6855 + " signature changed; retaining data."; 6856 reportSettingsProblem(Log.WARN, msg); 6857 } 6858 } 6859 } else { 6860 try { 6861 verifySignaturesLP(pkgSetting, pkg); 6862 // We just determined the app is signed correctly, so bring 6863 // over the latest parsed certs. 6864 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6865 } catch (PackageManagerException e) { 6866 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6867 throw e; 6868 } 6869 // The signature has changed, but this package is in the system 6870 // image... let's recover! 6871 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6872 // However... if this package is part of a shared user, but it 6873 // doesn't match the signature of the shared user, let's fail. 6874 // What this means is that you can't change the signatures 6875 // associated with an overall shared user, which doesn't seem all 6876 // that unreasonable. 6877 if (pkgSetting.sharedUser != null) { 6878 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6879 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6880 throw new PackageManagerException( 6881 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6882 "Signature mismatch for shared user : " 6883 + pkgSetting.sharedUser); 6884 } 6885 } 6886 // File a report about this. 6887 String msg = "System package " + pkg.packageName 6888 + " signature changed; retaining data."; 6889 reportSettingsProblem(Log.WARN, msg); 6890 } 6891 } 6892 // Verify that this new package doesn't have any content providers 6893 // that conflict with existing packages. Only do this if the 6894 // package isn't already installed, since we don't want to break 6895 // things that are installed. 6896 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6897 final int N = pkg.providers.size(); 6898 int i; 6899 for (i=0; i<N; i++) { 6900 PackageParser.Provider p = pkg.providers.get(i); 6901 if (p.info.authority != null) { 6902 String names[] = p.info.authority.split(";"); 6903 for (int j = 0; j < names.length; j++) { 6904 if (mProvidersByAuthority.containsKey(names[j])) { 6905 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6906 final String otherPackageName = 6907 ((other != null && other.getComponentName() != null) ? 6908 other.getComponentName().getPackageName() : "?"); 6909 throw new PackageManagerException( 6910 INSTALL_FAILED_CONFLICTING_PROVIDER, 6911 "Can't install because provider name " + names[j] 6912 + " (in package " + pkg.applicationInfo.packageName 6913 + ") is already used by " + otherPackageName); 6914 } 6915 } 6916 } 6917 } 6918 } 6919 6920 if (pkg.mAdoptPermissions != null) { 6921 // This package wants to adopt ownership of permissions from 6922 // another package. 6923 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6924 final String origName = pkg.mAdoptPermissions.get(i); 6925 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6926 if (orig != null) { 6927 if (verifyPackageUpdateLPr(orig, pkg)) { 6928 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6929 + pkg.packageName); 6930 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6931 } 6932 } 6933 } 6934 } 6935 } 6936 6937 final String pkgName = pkg.packageName; 6938 6939 final long scanFileTime = scanFile.lastModified(); 6940 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6941 pkg.applicationInfo.processName = fixProcessName( 6942 pkg.applicationInfo.packageName, 6943 pkg.applicationInfo.processName, 6944 pkg.applicationInfo.uid); 6945 6946 if (pkg != mPlatformPackage) { 6947 // This is a normal package, need to make its data directory. 6948 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 6949 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 6950 6951 boolean uidError = false; 6952 if (dataPath.exists()) { 6953 int currentUid = 0; 6954 try { 6955 StructStat stat = Os.stat(dataPath.getPath()); 6956 currentUid = stat.st_uid; 6957 } catch (ErrnoException e) { 6958 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6959 } 6960 6961 // If we have mismatched owners for the data path, we have a problem. 6962 if (currentUid != pkg.applicationInfo.uid) { 6963 boolean recovered = false; 6964 if (currentUid == 0) { 6965 // The directory somehow became owned by root. Wow. 6966 // This is probably because the system was stopped while 6967 // installd was in the middle of messing with its libs 6968 // directory. Ask installd to fix that. 6969 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6970 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6971 if (ret >= 0) { 6972 recovered = true; 6973 String msg = "Package " + pkg.packageName 6974 + " unexpectedly changed to uid 0; recovered to " + 6975 + pkg.applicationInfo.uid; 6976 reportSettingsProblem(Log.WARN, msg); 6977 } 6978 } 6979 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6980 || (scanFlags&SCAN_BOOTING) != 0)) { 6981 // If this is a system app, we can at least delete its 6982 // current data so the application will still work. 6983 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6984 if (ret >= 0) { 6985 // TODO: Kill the processes first 6986 // Old data gone! 6987 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6988 ? "System package " : "Third party package "; 6989 String msg = prefix + pkg.packageName 6990 + " has changed from uid: " 6991 + currentUid + " to " 6992 + pkg.applicationInfo.uid + "; old data erased"; 6993 reportSettingsProblem(Log.WARN, msg); 6994 recovered = true; 6995 6996 // And now re-install the app. 6997 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6998 pkg.applicationInfo.seinfo); 6999 if (ret == -1) { 7000 // Ack should not happen! 7001 msg = prefix + pkg.packageName 7002 + " could not have data directory re-created after delete."; 7003 reportSettingsProblem(Log.WARN, msg); 7004 throw new PackageManagerException( 7005 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 7006 } 7007 } 7008 if (!recovered) { 7009 mHasSystemUidErrors = true; 7010 } 7011 } else if (!recovered) { 7012 // If we allow this install to proceed, we will be broken. 7013 // Abort, abort! 7014 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7015 "scanPackageLI"); 7016 } 7017 if (!recovered) { 7018 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7019 + pkg.applicationInfo.uid + "/fs_" 7020 + currentUid; 7021 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7022 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7023 String msg = "Package " + pkg.packageName 7024 + " has mismatched uid: " 7025 + currentUid + " on disk, " 7026 + pkg.applicationInfo.uid + " in settings"; 7027 // writer 7028 synchronized (mPackages) { 7029 mSettings.mReadMessages.append(msg); 7030 mSettings.mReadMessages.append('\n'); 7031 uidError = true; 7032 if (!pkgSetting.uidError) { 7033 reportSettingsProblem(Log.ERROR, msg); 7034 } 7035 } 7036 } 7037 } 7038 7039 if (mShouldRestoreconData) { 7040 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7041 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7042 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7043 } 7044 } else { 7045 if (DEBUG_PACKAGE_SCANNING) { 7046 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7047 Log.v(TAG, "Want this data dir: " + dataPath); 7048 } 7049 //invoke installer to do the actual installation 7050 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7051 pkg.applicationInfo.seinfo); 7052 if (ret < 0) { 7053 // Error from installer 7054 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7055 "Unable to create data dirs [errorCode=" + ret + "]"); 7056 } 7057 } 7058 7059 // Get all of our default paths setup 7060 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7061 7062 pkgSetting.uidError = uidError; 7063 } 7064 7065 final String path = scanFile.getPath(); 7066 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7067 7068 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7069 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7070 7071 // Some system apps still use directory structure for native libraries 7072 // in which case we might end up not detecting abi solely based on apk 7073 // structure. Try to detect abi based on directory structure. 7074 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7075 pkg.applicationInfo.primaryCpuAbi == null) { 7076 setBundledAppAbisAndRoots(pkg, pkgSetting); 7077 setNativeLibraryPaths(pkg); 7078 } 7079 7080 } else { 7081 if ((scanFlags & SCAN_MOVE) != 0) { 7082 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7083 // but we already have this packages package info in the PackageSetting. We just 7084 // use that and derive the native library path based on the new codepath. 7085 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7086 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7087 } 7088 7089 // Set native library paths again. For moves, the path will be updated based on the 7090 // ABIs we've determined above. For non-moves, the path will be updated based on the 7091 // ABIs we determined during compilation, but the path will depend on the final 7092 // package path (after the rename away from the stage path). 7093 setNativeLibraryPaths(pkg); 7094 } 7095 7096 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7097 final int[] userIds = sUserManager.getUserIds(); 7098 synchronized (mInstallLock) { 7099 // Make sure all user data directories are ready to roll; we're okay 7100 // if they already exist 7101 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7102 for (int userId : userIds) { 7103 if (userId != UserHandle.USER_SYSTEM) { 7104 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7105 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7106 pkg.applicationInfo.seinfo); 7107 } 7108 } 7109 } 7110 7111 // Create a native library symlink only if we have native libraries 7112 // and if the native libraries are 32 bit libraries. We do not provide 7113 // this symlink for 64 bit libraries. 7114 if (pkg.applicationInfo.primaryCpuAbi != null && 7115 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7116 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7117 try { 7118 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7119 for (int userId : userIds) { 7120 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7121 nativeLibPath, userId) < 0) { 7122 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7123 "Failed linking native library dir (user=" + userId + ")"); 7124 } 7125 } 7126 } finally { 7127 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7128 } 7129 } 7130 } 7131 7132 // This is a special case for the "system" package, where the ABI is 7133 // dictated by the zygote configuration (and init.rc). We should keep track 7134 // of this ABI so that we can deal with "normal" applications that run under 7135 // the same UID correctly. 7136 if (mPlatformPackage == pkg) { 7137 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7138 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7139 } 7140 7141 // If there's a mismatch between the abi-override in the package setting 7142 // and the abiOverride specified for the install. Warn about this because we 7143 // would've already compiled the app without taking the package setting into 7144 // account. 7145 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7146 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7147 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7148 " for package: " + pkg.packageName); 7149 } 7150 } 7151 7152 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7153 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7154 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7155 7156 // Copy the derived override back to the parsed package, so that we can 7157 // update the package settings accordingly. 7158 pkg.cpuAbiOverride = cpuAbiOverride; 7159 7160 if (DEBUG_ABI_SELECTION) { 7161 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7162 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7163 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7164 } 7165 7166 // Push the derived path down into PackageSettings so we know what to 7167 // clean up at uninstall time. 7168 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7169 7170 if (DEBUG_ABI_SELECTION) { 7171 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7172 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7173 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7174 } 7175 7176 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7177 // We don't do this here during boot because we can do it all 7178 // at once after scanning all existing packages. 7179 // 7180 // We also do this *before* we perform dexopt on this package, so that 7181 // we can avoid redundant dexopts, and also to make sure we've got the 7182 // code and package path correct. 7183 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7184 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7185 } 7186 7187 if ((scanFlags & SCAN_NO_DEX) == 0) { 7188 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7189 7190 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7191 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7192 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7193 7194 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7195 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7196 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7197 } 7198 } 7199 if (mFactoryTest && pkg.requestedPermissions.contains( 7200 android.Manifest.permission.FACTORY_TEST)) { 7201 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7202 } 7203 7204 ArrayList<PackageParser.Package> clientLibPkgs = null; 7205 7206 // writer 7207 synchronized (mPackages) { 7208 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7209 // Only system apps can add new shared libraries. 7210 if (pkg.libraryNames != null) { 7211 for (int i=0; i<pkg.libraryNames.size(); i++) { 7212 String name = pkg.libraryNames.get(i); 7213 boolean allowed = false; 7214 if (pkg.isUpdatedSystemApp()) { 7215 // New library entries can only be added through the 7216 // system image. This is important to get rid of a lot 7217 // of nasty edge cases: for example if we allowed a non- 7218 // system update of the app to add a library, then uninstalling 7219 // the update would make the library go away, and assumptions 7220 // we made such as through app install filtering would now 7221 // have allowed apps on the device which aren't compatible 7222 // with it. Better to just have the restriction here, be 7223 // conservative, and create many fewer cases that can negatively 7224 // impact the user experience. 7225 final PackageSetting sysPs = mSettings 7226 .getDisabledSystemPkgLPr(pkg.packageName); 7227 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7228 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7229 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7230 allowed = true; 7231 break; 7232 } 7233 } 7234 } 7235 } else { 7236 allowed = true; 7237 } 7238 if (allowed) { 7239 if (!mSharedLibraries.containsKey(name)) { 7240 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7241 } else if (!name.equals(pkg.packageName)) { 7242 Slog.w(TAG, "Package " + pkg.packageName + " library " 7243 + name + " already exists; skipping"); 7244 } 7245 } else { 7246 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7247 + name + " that is not declared on system image; skipping"); 7248 } 7249 } 7250 if ((scanFlags&SCAN_BOOTING) == 0) { 7251 // If we are not booting, we need to update any applications 7252 // that are clients of our shared library. If we are booting, 7253 // this will all be done once the scan is complete. 7254 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7255 } 7256 } 7257 } 7258 } 7259 7260 // We also need to dexopt any apps that are dependent on this library. Note that 7261 // if these fail, we should abort the install since installing the library will 7262 // result in some apps being broken. 7263 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7264 try { 7265 if (clientLibPkgs != null) { 7266 if ((scanFlags & SCAN_NO_DEX) == 0) { 7267 for (int i = 0; i < clientLibPkgs.size(); i++) { 7268 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7269 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7270 null /* instruction sets */, forceDex, 7271 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7272 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7273 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7274 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7275 "scanPackageLI failed to dexopt clientLibPkgs"); 7276 } 7277 } 7278 } 7279 } 7280 } finally { 7281 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7282 } 7283 7284 // Request the ActivityManager to kill the process(only for existing packages) 7285 // so that we do not end up in a confused state while the user is still using the older 7286 // version of the application while the new one gets installed. 7287 if ((scanFlags & SCAN_REPLACING) != 0) { 7288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7289 7290 killApplication(pkg.applicationInfo.packageName, 7291 pkg.applicationInfo.uid, "replace pkg"); 7292 7293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7294 } 7295 7296 // Also need to kill any apps that are dependent on the library. 7297 if (clientLibPkgs != null) { 7298 for (int i=0; i<clientLibPkgs.size(); i++) { 7299 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7300 killApplication(clientPkg.applicationInfo.packageName, 7301 clientPkg.applicationInfo.uid, "update lib"); 7302 } 7303 } 7304 7305 // Make sure we're not adding any bogus keyset info 7306 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7307 ksms.assertScannedPackageValid(pkg); 7308 7309 // writer 7310 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7311 7312 boolean createIdmapFailed = false; 7313 synchronized (mPackages) { 7314 // We don't expect installation to fail beyond this point 7315 7316 // Add the new setting to mSettings 7317 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7318 // Add the new setting to mPackages 7319 mPackages.put(pkg.applicationInfo.packageName, pkg); 7320 // Make sure we don't accidentally delete its data. 7321 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7322 while (iter.hasNext()) { 7323 PackageCleanItem item = iter.next(); 7324 if (pkgName.equals(item.packageName)) { 7325 iter.remove(); 7326 } 7327 } 7328 7329 // Take care of first install / last update times. 7330 if (currentTime != 0) { 7331 if (pkgSetting.firstInstallTime == 0) { 7332 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7333 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7334 pkgSetting.lastUpdateTime = currentTime; 7335 } 7336 } else if (pkgSetting.firstInstallTime == 0) { 7337 // We need *something*. Take time time stamp of the file. 7338 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7339 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7340 if (scanFileTime != pkgSetting.timeStamp) { 7341 // A package on the system image has changed; consider this 7342 // to be an update. 7343 pkgSetting.lastUpdateTime = scanFileTime; 7344 } 7345 } 7346 7347 // Add the package's KeySets to the global KeySetManagerService 7348 ksms.addScannedPackageLPw(pkg); 7349 7350 int N = pkg.providers.size(); 7351 StringBuilder r = null; 7352 int i; 7353 for (i=0; i<N; i++) { 7354 PackageParser.Provider p = pkg.providers.get(i); 7355 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7356 p.info.processName, pkg.applicationInfo.uid); 7357 mProviders.addProvider(p); 7358 p.syncable = p.info.isSyncable; 7359 if (p.info.authority != null) { 7360 String names[] = p.info.authority.split(";"); 7361 p.info.authority = null; 7362 for (int j = 0; j < names.length; j++) { 7363 if (j == 1 && p.syncable) { 7364 // We only want the first authority for a provider to possibly be 7365 // syncable, so if we already added this provider using a different 7366 // authority clear the syncable flag. We copy the provider before 7367 // changing it because the mProviders object contains a reference 7368 // to a provider that we don't want to change. 7369 // Only do this for the second authority since the resulting provider 7370 // object can be the same for all future authorities for this provider. 7371 p = new PackageParser.Provider(p); 7372 p.syncable = false; 7373 } 7374 if (!mProvidersByAuthority.containsKey(names[j])) { 7375 mProvidersByAuthority.put(names[j], p); 7376 if (p.info.authority == null) { 7377 p.info.authority = names[j]; 7378 } else { 7379 p.info.authority = p.info.authority + ";" + names[j]; 7380 } 7381 if (DEBUG_PACKAGE_SCANNING) { 7382 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7383 Log.d(TAG, "Registered content provider: " + names[j] 7384 + ", className = " + p.info.name + ", isSyncable = " 7385 + p.info.isSyncable); 7386 } 7387 } else { 7388 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7389 Slog.w(TAG, "Skipping provider name " + names[j] + 7390 " (in package " + pkg.applicationInfo.packageName + 7391 "): name already used by " 7392 + ((other != null && other.getComponentName() != null) 7393 ? other.getComponentName().getPackageName() : "?")); 7394 } 7395 } 7396 } 7397 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7398 if (r == null) { 7399 r = new StringBuilder(256); 7400 } else { 7401 r.append(' '); 7402 } 7403 r.append(p.info.name); 7404 } 7405 } 7406 if (r != null) { 7407 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7408 } 7409 7410 N = pkg.services.size(); 7411 r = null; 7412 for (i=0; i<N; i++) { 7413 PackageParser.Service s = pkg.services.get(i); 7414 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7415 s.info.processName, pkg.applicationInfo.uid); 7416 mServices.addService(s); 7417 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7418 if (r == null) { 7419 r = new StringBuilder(256); 7420 } else { 7421 r.append(' '); 7422 } 7423 r.append(s.info.name); 7424 } 7425 } 7426 if (r != null) { 7427 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7428 } 7429 7430 N = pkg.receivers.size(); 7431 r = null; 7432 for (i=0; i<N; i++) { 7433 PackageParser.Activity a = pkg.receivers.get(i); 7434 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7435 a.info.processName, pkg.applicationInfo.uid); 7436 mReceivers.addActivity(a, "receiver"); 7437 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7438 if (r == null) { 7439 r = new StringBuilder(256); 7440 } else { 7441 r.append(' '); 7442 } 7443 r.append(a.info.name); 7444 } 7445 } 7446 if (r != null) { 7447 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7448 } 7449 7450 N = pkg.activities.size(); 7451 r = null; 7452 for (i=0; i<N; i++) { 7453 PackageParser.Activity a = pkg.activities.get(i); 7454 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7455 a.info.processName, pkg.applicationInfo.uid); 7456 mActivities.addActivity(a, "activity"); 7457 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7458 if (r == null) { 7459 r = new StringBuilder(256); 7460 } else { 7461 r.append(' '); 7462 } 7463 r.append(a.info.name); 7464 } 7465 } 7466 if (r != null) { 7467 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7468 } 7469 7470 N = pkg.permissionGroups.size(); 7471 r = null; 7472 for (i=0; i<N; i++) { 7473 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7474 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7475 if (cur == null) { 7476 mPermissionGroups.put(pg.info.name, pg); 7477 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7478 if (r == null) { 7479 r = new StringBuilder(256); 7480 } else { 7481 r.append(' '); 7482 } 7483 r.append(pg.info.name); 7484 } 7485 } else { 7486 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7487 + pg.info.packageName + " ignored: original from " 7488 + cur.info.packageName); 7489 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7490 if (r == null) { 7491 r = new StringBuilder(256); 7492 } else { 7493 r.append(' '); 7494 } 7495 r.append("DUP:"); 7496 r.append(pg.info.name); 7497 } 7498 } 7499 } 7500 if (r != null) { 7501 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7502 } 7503 7504 N = pkg.permissions.size(); 7505 r = null; 7506 for (i=0; i<N; i++) { 7507 PackageParser.Permission p = pkg.permissions.get(i); 7508 7509 // Assume by default that we did not install this permission into the system. 7510 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7511 7512 // Now that permission groups have a special meaning, we ignore permission 7513 // groups for legacy apps to prevent unexpected behavior. In particular, 7514 // permissions for one app being granted to someone just becuase they happen 7515 // to be in a group defined by another app (before this had no implications). 7516 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7517 p.group = mPermissionGroups.get(p.info.group); 7518 // Warn for a permission in an unknown group. 7519 if (p.info.group != null && p.group == null) { 7520 Slog.w(TAG, "Permission " + p.info.name + " from package " 7521 + p.info.packageName + " in an unknown group " + p.info.group); 7522 } 7523 } 7524 7525 ArrayMap<String, BasePermission> permissionMap = 7526 p.tree ? mSettings.mPermissionTrees 7527 : mSettings.mPermissions; 7528 BasePermission bp = permissionMap.get(p.info.name); 7529 7530 // Allow system apps to redefine non-system permissions 7531 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7532 final boolean currentOwnerIsSystem = (bp.perm != null 7533 && isSystemApp(bp.perm.owner)); 7534 if (isSystemApp(p.owner)) { 7535 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7536 // It's a built-in permission and no owner, take ownership now 7537 bp.packageSetting = pkgSetting; 7538 bp.perm = p; 7539 bp.uid = pkg.applicationInfo.uid; 7540 bp.sourcePackage = p.info.packageName; 7541 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7542 } else if (!currentOwnerIsSystem) { 7543 String msg = "New decl " + p.owner + " of permission " 7544 + p.info.name + " is system; overriding " + bp.sourcePackage; 7545 reportSettingsProblem(Log.WARN, msg); 7546 bp = null; 7547 } 7548 } 7549 } 7550 7551 if (bp == null) { 7552 bp = new BasePermission(p.info.name, p.info.packageName, 7553 BasePermission.TYPE_NORMAL); 7554 permissionMap.put(p.info.name, bp); 7555 } 7556 7557 if (bp.perm == null) { 7558 if (bp.sourcePackage == null 7559 || bp.sourcePackage.equals(p.info.packageName)) { 7560 BasePermission tree = findPermissionTreeLP(p.info.name); 7561 if (tree == null 7562 || tree.sourcePackage.equals(p.info.packageName)) { 7563 bp.packageSetting = pkgSetting; 7564 bp.perm = p; 7565 bp.uid = pkg.applicationInfo.uid; 7566 bp.sourcePackage = p.info.packageName; 7567 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7568 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7569 if (r == null) { 7570 r = new StringBuilder(256); 7571 } else { 7572 r.append(' '); 7573 } 7574 r.append(p.info.name); 7575 } 7576 } else { 7577 Slog.w(TAG, "Permission " + p.info.name + " from package " 7578 + p.info.packageName + " ignored: base tree " 7579 + tree.name + " is from package " 7580 + tree.sourcePackage); 7581 } 7582 } else { 7583 Slog.w(TAG, "Permission " + p.info.name + " from package " 7584 + p.info.packageName + " ignored: original from " 7585 + bp.sourcePackage); 7586 } 7587 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7588 if (r == null) { 7589 r = new StringBuilder(256); 7590 } else { 7591 r.append(' '); 7592 } 7593 r.append("DUP:"); 7594 r.append(p.info.name); 7595 } 7596 if (bp.perm == p) { 7597 bp.protectionLevel = p.info.protectionLevel; 7598 } 7599 } 7600 7601 if (r != null) { 7602 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7603 } 7604 7605 N = pkg.instrumentation.size(); 7606 r = null; 7607 for (i=0; i<N; i++) { 7608 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7609 a.info.packageName = pkg.applicationInfo.packageName; 7610 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7611 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7612 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7613 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7614 a.info.dataDir = pkg.applicationInfo.dataDir; 7615 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7616 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7617 7618 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7619 // need other information about the application, like the ABI and what not ? 7620 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7621 mInstrumentation.put(a.getComponentName(), a); 7622 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7623 if (r == null) { 7624 r = new StringBuilder(256); 7625 } else { 7626 r.append(' '); 7627 } 7628 r.append(a.info.name); 7629 } 7630 } 7631 if (r != null) { 7632 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7633 } 7634 7635 if (pkg.protectedBroadcasts != null) { 7636 N = pkg.protectedBroadcasts.size(); 7637 for (i=0; i<N; i++) { 7638 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7639 } 7640 } 7641 7642 pkgSetting.setTimeStamp(scanFileTime); 7643 7644 // Create idmap files for pairs of (packages, overlay packages). 7645 // Note: "android", ie framework-res.apk, is handled by native layers. 7646 if (pkg.mOverlayTarget != null) { 7647 // This is an overlay package. 7648 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7649 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7650 mOverlays.put(pkg.mOverlayTarget, 7651 new ArrayMap<String, PackageParser.Package>()); 7652 } 7653 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7654 map.put(pkg.packageName, pkg); 7655 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7656 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7657 createIdmapFailed = true; 7658 } 7659 } 7660 } else if (mOverlays.containsKey(pkg.packageName) && 7661 !pkg.packageName.equals("android")) { 7662 // This is a regular package, with one or more known overlay packages. 7663 createIdmapsForPackageLI(pkg); 7664 } 7665 } 7666 7667 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7668 7669 if (createIdmapFailed) { 7670 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7671 "scanPackageLI failed to createIdmap"); 7672 } 7673 return pkg; 7674 } 7675 7676 /** 7677 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7678 * is derived purely on the basis of the contents of {@code scanFile} and 7679 * {@code cpuAbiOverride}. 7680 * 7681 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7682 */ 7683 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7684 String cpuAbiOverride, boolean extractLibs) 7685 throws PackageManagerException { 7686 // TODO: We can probably be smarter about this stuff. For installed apps, 7687 // we can calculate this information at install time once and for all. For 7688 // system apps, we can probably assume that this information doesn't change 7689 // after the first boot scan. As things stand, we do lots of unnecessary work. 7690 7691 // Give ourselves some initial paths; we'll come back for another 7692 // pass once we've determined ABI below. 7693 setNativeLibraryPaths(pkg); 7694 7695 // We would never need to extract libs for forward-locked and external packages, 7696 // since the container service will do it for us. We shouldn't attempt to 7697 // extract libs from system app when it was not updated. 7698 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7699 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7700 extractLibs = false; 7701 } 7702 7703 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7704 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7705 7706 NativeLibraryHelper.Handle handle = null; 7707 try { 7708 handle = NativeLibraryHelper.Handle.create(pkg); 7709 // TODO(multiArch): This can be null for apps that didn't go through the 7710 // usual installation process. We can calculate it again, like we 7711 // do during install time. 7712 // 7713 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7714 // unnecessary. 7715 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7716 7717 // Null out the abis so that they can be recalculated. 7718 pkg.applicationInfo.primaryCpuAbi = null; 7719 pkg.applicationInfo.secondaryCpuAbi = null; 7720 if (isMultiArch(pkg.applicationInfo)) { 7721 // Warn if we've set an abiOverride for multi-lib packages.. 7722 // By definition, we need to copy both 32 and 64 bit libraries for 7723 // such packages. 7724 if (pkg.cpuAbiOverride != null 7725 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7726 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7727 } 7728 7729 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7730 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7731 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7732 if (extractLibs) { 7733 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7734 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7735 useIsaSpecificSubdirs); 7736 } else { 7737 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7738 } 7739 } 7740 7741 maybeThrowExceptionForMultiArchCopy( 7742 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7743 7744 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7745 if (extractLibs) { 7746 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7747 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7748 useIsaSpecificSubdirs); 7749 } else { 7750 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7751 } 7752 } 7753 7754 maybeThrowExceptionForMultiArchCopy( 7755 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7756 7757 if (abi64 >= 0) { 7758 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7759 } 7760 7761 if (abi32 >= 0) { 7762 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7763 if (abi64 >= 0) { 7764 pkg.applicationInfo.secondaryCpuAbi = abi; 7765 } else { 7766 pkg.applicationInfo.primaryCpuAbi = abi; 7767 } 7768 } 7769 } else { 7770 String[] abiList = (cpuAbiOverride != null) ? 7771 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7772 7773 // Enable gross and lame hacks for apps that are built with old 7774 // SDK tools. We must scan their APKs for renderscript bitcode and 7775 // not launch them if it's present. Don't bother checking on devices 7776 // that don't have 64 bit support. 7777 boolean needsRenderScriptOverride = false; 7778 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7779 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7780 abiList = Build.SUPPORTED_32_BIT_ABIS; 7781 needsRenderScriptOverride = true; 7782 } 7783 7784 final int copyRet; 7785 if (extractLibs) { 7786 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7787 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7788 } else { 7789 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7790 } 7791 7792 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7793 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7794 "Error unpackaging native libs for app, errorCode=" + copyRet); 7795 } 7796 7797 if (copyRet >= 0) { 7798 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7799 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7800 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7801 } else if (needsRenderScriptOverride) { 7802 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7803 } 7804 } 7805 } catch (IOException ioe) { 7806 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7807 } finally { 7808 IoUtils.closeQuietly(handle); 7809 } 7810 7811 // Now that we've calculated the ABIs and determined if it's an internal app, 7812 // we will go ahead and populate the nativeLibraryPath. 7813 setNativeLibraryPaths(pkg); 7814 } 7815 7816 /** 7817 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7818 * i.e, so that all packages can be run inside a single process if required. 7819 * 7820 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7821 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7822 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7823 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7824 * updating a package that belongs to a shared user. 7825 * 7826 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7827 * adds unnecessary complexity. 7828 */ 7829 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7830 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7831 boolean bootComplete) { 7832 String requiredInstructionSet = null; 7833 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7834 requiredInstructionSet = VMRuntime.getInstructionSet( 7835 scannedPackage.applicationInfo.primaryCpuAbi); 7836 } 7837 7838 PackageSetting requirer = null; 7839 for (PackageSetting ps : packagesForUser) { 7840 // If packagesForUser contains scannedPackage, we skip it. This will happen 7841 // when scannedPackage is an update of an existing package. Without this check, 7842 // we will never be able to change the ABI of any package belonging to a shared 7843 // user, even if it's compatible with other packages. 7844 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7845 if (ps.primaryCpuAbiString == null) { 7846 continue; 7847 } 7848 7849 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7850 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7851 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7852 // this but there's not much we can do. 7853 String errorMessage = "Instruction set mismatch, " 7854 + ((requirer == null) ? "[caller]" : requirer) 7855 + " requires " + requiredInstructionSet + " whereas " + ps 7856 + " requires " + instructionSet; 7857 Slog.w(TAG, errorMessage); 7858 } 7859 7860 if (requiredInstructionSet == null) { 7861 requiredInstructionSet = instructionSet; 7862 requirer = ps; 7863 } 7864 } 7865 } 7866 7867 if (requiredInstructionSet != null) { 7868 String adjustedAbi; 7869 if (requirer != null) { 7870 // requirer != null implies that either scannedPackage was null or that scannedPackage 7871 // did not require an ABI, in which case we have to adjust scannedPackage to match 7872 // the ABI of the set (which is the same as requirer's ABI) 7873 adjustedAbi = requirer.primaryCpuAbiString; 7874 if (scannedPackage != null) { 7875 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7876 } 7877 } else { 7878 // requirer == null implies that we're updating all ABIs in the set to 7879 // match scannedPackage. 7880 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7881 } 7882 7883 for (PackageSetting ps : packagesForUser) { 7884 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7885 if (ps.primaryCpuAbiString != null) { 7886 continue; 7887 } 7888 7889 ps.primaryCpuAbiString = adjustedAbi; 7890 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7891 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7892 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7893 7894 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7895 7896 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7897 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7898 bootComplete, false /*useJit*/); 7899 7900 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7901 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7902 ps.primaryCpuAbiString = null; 7903 ps.pkg.applicationInfo.primaryCpuAbi = null; 7904 return; 7905 } else { 7906 mInstaller.rmdex(ps.codePathString, 7907 getDexCodeInstructionSet(getPreferredInstructionSet())); 7908 } 7909 } 7910 } 7911 } 7912 } 7913 } 7914 7915 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7916 synchronized (mPackages) { 7917 mResolverReplaced = true; 7918 // Set up information for custom user intent resolution activity. 7919 mResolveActivity.applicationInfo = pkg.applicationInfo; 7920 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7921 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7922 mResolveActivity.processName = pkg.applicationInfo.packageName; 7923 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7924 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7925 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7926 mResolveActivity.theme = 0; 7927 mResolveActivity.exported = true; 7928 mResolveActivity.enabled = true; 7929 mResolveInfo.activityInfo = mResolveActivity; 7930 mResolveInfo.priority = 0; 7931 mResolveInfo.preferredOrder = 0; 7932 mResolveInfo.match = 0; 7933 mResolveComponentName = mCustomResolverComponentName; 7934 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7935 mResolveComponentName); 7936 } 7937 } 7938 7939 private static String calculateBundledApkRoot(final String codePathString) { 7940 final File codePath = new File(codePathString); 7941 final File codeRoot; 7942 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7943 codeRoot = Environment.getRootDirectory(); 7944 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7945 codeRoot = Environment.getOemDirectory(); 7946 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7947 codeRoot = Environment.getVendorDirectory(); 7948 } else { 7949 // Unrecognized code path; take its top real segment as the apk root: 7950 // e.g. /something/app/blah.apk => /something 7951 try { 7952 File f = codePath.getCanonicalFile(); 7953 File parent = f.getParentFile(); // non-null because codePath is a file 7954 File tmp; 7955 while ((tmp = parent.getParentFile()) != null) { 7956 f = parent; 7957 parent = tmp; 7958 } 7959 codeRoot = f; 7960 Slog.w(TAG, "Unrecognized code path " 7961 + codePath + " - using " + codeRoot); 7962 } catch (IOException e) { 7963 // Can't canonicalize the code path -- shenanigans? 7964 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7965 return Environment.getRootDirectory().getPath(); 7966 } 7967 } 7968 return codeRoot.getPath(); 7969 } 7970 7971 /** 7972 * Derive and set the location of native libraries for the given package, 7973 * which varies depending on where and how the package was installed. 7974 */ 7975 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7976 final ApplicationInfo info = pkg.applicationInfo; 7977 final String codePath = pkg.codePath; 7978 final File codeFile = new File(codePath); 7979 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7980 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7981 7982 info.nativeLibraryRootDir = null; 7983 info.nativeLibraryRootRequiresIsa = false; 7984 info.nativeLibraryDir = null; 7985 info.secondaryNativeLibraryDir = null; 7986 7987 if (isApkFile(codeFile)) { 7988 // Monolithic install 7989 if (bundledApp) { 7990 // If "/system/lib64/apkname" exists, assume that is the per-package 7991 // native library directory to use; otherwise use "/system/lib/apkname". 7992 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7993 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7994 getPrimaryInstructionSet(info)); 7995 7996 // This is a bundled system app so choose the path based on the ABI. 7997 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7998 // is just the default path. 7999 final String apkName = deriveCodePathName(codePath); 8000 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8001 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8002 apkName).getAbsolutePath(); 8003 8004 if (info.secondaryCpuAbi != null) { 8005 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8006 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8007 secondaryLibDir, apkName).getAbsolutePath(); 8008 } 8009 } else if (asecApp) { 8010 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8011 .getAbsolutePath(); 8012 } else { 8013 final String apkName = deriveCodePathName(codePath); 8014 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8015 .getAbsolutePath(); 8016 } 8017 8018 info.nativeLibraryRootRequiresIsa = false; 8019 info.nativeLibraryDir = info.nativeLibraryRootDir; 8020 } else { 8021 // Cluster install 8022 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8023 info.nativeLibraryRootRequiresIsa = true; 8024 8025 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8026 getPrimaryInstructionSet(info)).getAbsolutePath(); 8027 8028 if (info.secondaryCpuAbi != null) { 8029 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8030 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8031 } 8032 } 8033 } 8034 8035 /** 8036 * Calculate the abis and roots for a bundled app. These can uniquely 8037 * be determined from the contents of the system partition, i.e whether 8038 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8039 * of this information, and instead assume that the system was built 8040 * sensibly. 8041 */ 8042 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8043 PackageSetting pkgSetting) { 8044 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8045 8046 // If "/system/lib64/apkname" exists, assume that is the per-package 8047 // native library directory to use; otherwise use "/system/lib/apkname". 8048 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8049 setBundledAppAbi(pkg, apkRoot, apkName); 8050 // pkgSetting might be null during rescan following uninstall of updates 8051 // to a bundled app, so accommodate that possibility. The settings in 8052 // that case will be established later from the parsed package. 8053 // 8054 // If the settings aren't null, sync them up with what we've just derived. 8055 // note that apkRoot isn't stored in the package settings. 8056 if (pkgSetting != null) { 8057 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8058 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8059 } 8060 } 8061 8062 /** 8063 * Deduces the ABI of a bundled app and sets the relevant fields on the 8064 * parsed pkg object. 8065 * 8066 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8067 * under which system libraries are installed. 8068 * @param apkName the name of the installed package. 8069 */ 8070 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8071 final File codeFile = new File(pkg.codePath); 8072 8073 final boolean has64BitLibs; 8074 final boolean has32BitLibs; 8075 if (isApkFile(codeFile)) { 8076 // Monolithic install 8077 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8078 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8079 } else { 8080 // Cluster install 8081 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8082 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8083 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8084 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8085 has64BitLibs = (new File(rootDir, isa)).exists(); 8086 } else { 8087 has64BitLibs = false; 8088 } 8089 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8090 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8091 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8092 has32BitLibs = (new File(rootDir, isa)).exists(); 8093 } else { 8094 has32BitLibs = false; 8095 } 8096 } 8097 8098 if (has64BitLibs && !has32BitLibs) { 8099 // The package has 64 bit libs, but not 32 bit libs. Its primary 8100 // ABI should be 64 bit. We can safely assume here that the bundled 8101 // native libraries correspond to the most preferred ABI in the list. 8102 8103 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8104 pkg.applicationInfo.secondaryCpuAbi = null; 8105 } else if (has32BitLibs && !has64BitLibs) { 8106 // The package has 32 bit libs but not 64 bit libs. Its primary 8107 // ABI should be 32 bit. 8108 8109 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8110 pkg.applicationInfo.secondaryCpuAbi = null; 8111 } else if (has32BitLibs && has64BitLibs) { 8112 // The application has both 64 and 32 bit bundled libraries. We check 8113 // here that the app declares multiArch support, and warn if it doesn't. 8114 // 8115 // We will be lenient here and record both ABIs. The primary will be the 8116 // ABI that's higher on the list, i.e, a device that's configured to prefer 8117 // 64 bit apps will see a 64 bit primary ABI, 8118 8119 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8120 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8121 } 8122 8123 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8124 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8125 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8126 } else { 8127 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8128 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8129 } 8130 } else { 8131 pkg.applicationInfo.primaryCpuAbi = null; 8132 pkg.applicationInfo.secondaryCpuAbi = null; 8133 } 8134 } 8135 8136 private void killApplication(String pkgName, int appId, String reason) { 8137 // Request the ActivityManager to kill the process(only for existing packages) 8138 // so that we do not end up in a confused state while the user is still using the older 8139 // version of the application while the new one gets installed. 8140 IActivityManager am = ActivityManagerNative.getDefault(); 8141 if (am != null) { 8142 try { 8143 am.killApplicationWithAppId(pkgName, appId, reason); 8144 } catch (RemoteException e) { 8145 } 8146 } 8147 } 8148 8149 void removePackageLI(PackageSetting ps, boolean chatty) { 8150 if (DEBUG_INSTALL) { 8151 if (chatty) 8152 Log.d(TAG, "Removing package " + ps.name); 8153 } 8154 8155 // writer 8156 synchronized (mPackages) { 8157 mPackages.remove(ps.name); 8158 final PackageParser.Package pkg = ps.pkg; 8159 if (pkg != null) { 8160 cleanPackageDataStructuresLILPw(pkg, chatty); 8161 } 8162 } 8163 } 8164 8165 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8166 if (DEBUG_INSTALL) { 8167 if (chatty) 8168 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8169 } 8170 8171 // writer 8172 synchronized (mPackages) { 8173 mPackages.remove(pkg.applicationInfo.packageName); 8174 cleanPackageDataStructuresLILPw(pkg, chatty); 8175 } 8176 } 8177 8178 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8179 int N = pkg.providers.size(); 8180 StringBuilder r = null; 8181 int i; 8182 for (i=0; i<N; i++) { 8183 PackageParser.Provider p = pkg.providers.get(i); 8184 mProviders.removeProvider(p); 8185 if (p.info.authority == null) { 8186 8187 /* There was another ContentProvider with this authority when 8188 * this app was installed so this authority is null, 8189 * Ignore it as we don't have to unregister the provider. 8190 */ 8191 continue; 8192 } 8193 String names[] = p.info.authority.split(";"); 8194 for (int j = 0; j < names.length; j++) { 8195 if (mProvidersByAuthority.get(names[j]) == p) { 8196 mProvidersByAuthority.remove(names[j]); 8197 if (DEBUG_REMOVE) { 8198 if (chatty) 8199 Log.d(TAG, "Unregistered content provider: " + names[j] 8200 + ", className = " + p.info.name + ", isSyncable = " 8201 + p.info.isSyncable); 8202 } 8203 } 8204 } 8205 if (DEBUG_REMOVE && chatty) { 8206 if (r == null) { 8207 r = new StringBuilder(256); 8208 } else { 8209 r.append(' '); 8210 } 8211 r.append(p.info.name); 8212 } 8213 } 8214 if (r != null) { 8215 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8216 } 8217 8218 N = pkg.services.size(); 8219 r = null; 8220 for (i=0; i<N; i++) { 8221 PackageParser.Service s = pkg.services.get(i); 8222 mServices.removeService(s); 8223 if (chatty) { 8224 if (r == null) { 8225 r = new StringBuilder(256); 8226 } else { 8227 r.append(' '); 8228 } 8229 r.append(s.info.name); 8230 } 8231 } 8232 if (r != null) { 8233 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8234 } 8235 8236 N = pkg.receivers.size(); 8237 r = null; 8238 for (i=0; i<N; i++) { 8239 PackageParser.Activity a = pkg.receivers.get(i); 8240 mReceivers.removeActivity(a, "receiver"); 8241 if (DEBUG_REMOVE && chatty) { 8242 if (r == null) { 8243 r = new StringBuilder(256); 8244 } else { 8245 r.append(' '); 8246 } 8247 r.append(a.info.name); 8248 } 8249 } 8250 if (r != null) { 8251 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8252 } 8253 8254 N = pkg.activities.size(); 8255 r = null; 8256 for (i=0; i<N; i++) { 8257 PackageParser.Activity a = pkg.activities.get(i); 8258 mActivities.removeActivity(a, "activity"); 8259 if (DEBUG_REMOVE && chatty) { 8260 if (r == null) { 8261 r = new StringBuilder(256); 8262 } else { 8263 r.append(' '); 8264 } 8265 r.append(a.info.name); 8266 } 8267 } 8268 if (r != null) { 8269 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8270 } 8271 8272 N = pkg.permissions.size(); 8273 r = null; 8274 for (i=0; i<N; i++) { 8275 PackageParser.Permission p = pkg.permissions.get(i); 8276 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8277 if (bp == null) { 8278 bp = mSettings.mPermissionTrees.get(p.info.name); 8279 } 8280 if (bp != null && bp.perm == p) { 8281 bp.perm = null; 8282 if (DEBUG_REMOVE && chatty) { 8283 if (r == null) { 8284 r = new StringBuilder(256); 8285 } else { 8286 r.append(' '); 8287 } 8288 r.append(p.info.name); 8289 } 8290 } 8291 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8292 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8293 if (appOpPerms != null) { 8294 appOpPerms.remove(pkg.packageName); 8295 } 8296 } 8297 } 8298 if (r != null) { 8299 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8300 } 8301 8302 N = pkg.requestedPermissions.size(); 8303 r = null; 8304 for (i=0; i<N; i++) { 8305 String perm = pkg.requestedPermissions.get(i); 8306 BasePermission bp = mSettings.mPermissions.get(perm); 8307 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8308 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8309 if (appOpPerms != null) { 8310 appOpPerms.remove(pkg.packageName); 8311 if (appOpPerms.isEmpty()) { 8312 mAppOpPermissionPackages.remove(perm); 8313 } 8314 } 8315 } 8316 } 8317 if (r != null) { 8318 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8319 } 8320 8321 N = pkg.instrumentation.size(); 8322 r = null; 8323 for (i=0; i<N; i++) { 8324 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8325 mInstrumentation.remove(a.getComponentName()); 8326 if (DEBUG_REMOVE && chatty) { 8327 if (r == null) { 8328 r = new StringBuilder(256); 8329 } else { 8330 r.append(' '); 8331 } 8332 r.append(a.info.name); 8333 } 8334 } 8335 if (r != null) { 8336 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8337 } 8338 8339 r = null; 8340 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8341 // Only system apps can hold shared libraries. 8342 if (pkg.libraryNames != null) { 8343 for (i=0; i<pkg.libraryNames.size(); i++) { 8344 String name = pkg.libraryNames.get(i); 8345 SharedLibraryEntry cur = mSharedLibraries.get(name); 8346 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8347 mSharedLibraries.remove(name); 8348 if (DEBUG_REMOVE && chatty) { 8349 if (r == null) { 8350 r = new StringBuilder(256); 8351 } else { 8352 r.append(' '); 8353 } 8354 r.append(name); 8355 } 8356 } 8357 } 8358 } 8359 } 8360 if (r != null) { 8361 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8362 } 8363 } 8364 8365 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8366 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8367 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8368 return true; 8369 } 8370 } 8371 return false; 8372 } 8373 8374 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8375 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8376 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8377 8378 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8379 int flags) { 8380 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8381 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8382 } 8383 8384 private void updatePermissionsLPw(String changingPkg, 8385 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8386 // Make sure there are no dangling permission trees. 8387 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8388 while (it.hasNext()) { 8389 final BasePermission bp = it.next(); 8390 if (bp.packageSetting == null) { 8391 // We may not yet have parsed the package, so just see if 8392 // we still know about its settings. 8393 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8394 } 8395 if (bp.packageSetting == null) { 8396 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8397 + " from package " + bp.sourcePackage); 8398 it.remove(); 8399 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8400 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8401 Slog.i(TAG, "Removing old permission tree: " + bp.name 8402 + " from package " + bp.sourcePackage); 8403 flags |= UPDATE_PERMISSIONS_ALL; 8404 it.remove(); 8405 } 8406 } 8407 } 8408 8409 // Make sure all dynamic permissions have been assigned to a package, 8410 // and make sure there are no dangling permissions. 8411 it = mSettings.mPermissions.values().iterator(); 8412 while (it.hasNext()) { 8413 final BasePermission bp = it.next(); 8414 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8415 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8416 + bp.name + " pkg=" + bp.sourcePackage 8417 + " info=" + bp.pendingInfo); 8418 if (bp.packageSetting == null && bp.pendingInfo != null) { 8419 final BasePermission tree = findPermissionTreeLP(bp.name); 8420 if (tree != null && tree.perm != null) { 8421 bp.packageSetting = tree.packageSetting; 8422 bp.perm = new PackageParser.Permission(tree.perm.owner, 8423 new PermissionInfo(bp.pendingInfo)); 8424 bp.perm.info.packageName = tree.perm.info.packageName; 8425 bp.perm.info.name = bp.name; 8426 bp.uid = tree.uid; 8427 } 8428 } 8429 } 8430 if (bp.packageSetting == null) { 8431 // We may not yet have parsed the package, so just see if 8432 // we still know about its settings. 8433 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8434 } 8435 if (bp.packageSetting == null) { 8436 Slog.w(TAG, "Removing dangling permission: " + bp.name 8437 + " from package " + bp.sourcePackage); 8438 it.remove(); 8439 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8440 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8441 Slog.i(TAG, "Removing old permission: " + bp.name 8442 + " from package " + bp.sourcePackage); 8443 flags |= UPDATE_PERMISSIONS_ALL; 8444 it.remove(); 8445 } 8446 } 8447 } 8448 8449 // Now update the permissions for all packages, in particular 8450 // replace the granted permissions of the system packages. 8451 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8452 for (PackageParser.Package pkg : mPackages.values()) { 8453 if (pkg != pkgInfo) { 8454 // Only replace for packages on requested volume 8455 final String volumeUuid = getVolumeUuidForPackage(pkg); 8456 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8457 && Objects.equals(replaceVolumeUuid, volumeUuid); 8458 grantPermissionsLPw(pkg, replace, changingPkg); 8459 } 8460 } 8461 } 8462 8463 if (pkgInfo != null) { 8464 // Only replace for packages on requested volume 8465 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8466 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8467 && Objects.equals(replaceVolumeUuid, volumeUuid); 8468 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8469 } 8470 } 8471 8472 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8473 String packageOfInterest) { 8474 // IMPORTANT: There are two types of permissions: install and runtime. 8475 // Install time permissions are granted when the app is installed to 8476 // all device users and users added in the future. Runtime permissions 8477 // are granted at runtime explicitly to specific users. Normal and signature 8478 // protected permissions are install time permissions. Dangerous permissions 8479 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8480 // otherwise they are runtime permissions. This function does not manage 8481 // runtime permissions except for the case an app targeting Lollipop MR1 8482 // being upgraded to target a newer SDK, in which case dangerous permissions 8483 // are transformed from install time to runtime ones. 8484 8485 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8486 if (ps == null) { 8487 return; 8488 } 8489 8490 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8491 8492 PermissionsState permissionsState = ps.getPermissionsState(); 8493 PermissionsState origPermissions = permissionsState; 8494 8495 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8496 8497 boolean runtimePermissionsRevoked = false; 8498 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8499 8500 boolean changedInstallPermission = false; 8501 8502 if (replace) { 8503 ps.installPermissionsFixed = false; 8504 if (!ps.isSharedUser()) { 8505 origPermissions = new PermissionsState(permissionsState); 8506 permissionsState.reset(); 8507 } else { 8508 // We need to know only about runtime permission changes since the 8509 // calling code always writes the install permissions state but 8510 // the runtime ones are written only if changed. The only cases of 8511 // changed runtime permissions here are promotion of an install to 8512 // runtime and revocation of a runtime from a shared user. 8513 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8514 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8515 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8516 runtimePermissionsRevoked = true; 8517 } 8518 } 8519 } 8520 8521 permissionsState.setGlobalGids(mGlobalGids); 8522 8523 final int N = pkg.requestedPermissions.size(); 8524 for (int i=0; i<N; i++) { 8525 final String name = pkg.requestedPermissions.get(i); 8526 final BasePermission bp = mSettings.mPermissions.get(name); 8527 8528 if (DEBUG_INSTALL) { 8529 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8530 } 8531 8532 if (bp == null || bp.packageSetting == null) { 8533 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8534 Slog.w(TAG, "Unknown permission " + name 8535 + " in package " + pkg.packageName); 8536 } 8537 continue; 8538 } 8539 8540 final String perm = bp.name; 8541 boolean allowedSig = false; 8542 int grant = GRANT_DENIED; 8543 8544 // Keep track of app op permissions. 8545 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8546 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8547 if (pkgs == null) { 8548 pkgs = new ArraySet<>(); 8549 mAppOpPermissionPackages.put(bp.name, pkgs); 8550 } 8551 pkgs.add(pkg.packageName); 8552 } 8553 8554 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8555 switch (level) { 8556 case PermissionInfo.PROTECTION_NORMAL: { 8557 // For all apps normal permissions are install time ones. 8558 grant = GRANT_INSTALL; 8559 } break; 8560 8561 case PermissionInfo.PROTECTION_DANGEROUS: { 8562 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8563 // For legacy apps dangerous permissions are install time ones. 8564 grant = GRANT_INSTALL_LEGACY; 8565 } else if (origPermissions.hasInstallPermission(bp.name)) { 8566 // For legacy apps that became modern, install becomes runtime. 8567 grant = GRANT_UPGRADE; 8568 } else if (mPromoteSystemApps 8569 && isSystemApp(ps) 8570 && mExistingSystemPackages.contains(ps.name)) { 8571 // For legacy system apps, install becomes runtime. 8572 // We cannot check hasInstallPermission() for system apps since those 8573 // permissions were granted implicitly and not persisted pre-M. 8574 grant = GRANT_UPGRADE; 8575 } else { 8576 // For modern apps keep runtime permissions unchanged. 8577 grant = GRANT_RUNTIME; 8578 } 8579 } break; 8580 8581 case PermissionInfo.PROTECTION_SIGNATURE: { 8582 // For all apps signature permissions are install time ones. 8583 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8584 if (allowedSig) { 8585 grant = GRANT_INSTALL; 8586 } 8587 } break; 8588 } 8589 8590 if (DEBUG_INSTALL) { 8591 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8592 } 8593 8594 if (grant != GRANT_DENIED) { 8595 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8596 // If this is an existing, non-system package, then 8597 // we can't add any new permissions to it. 8598 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8599 // Except... if this is a permission that was added 8600 // to the platform (note: need to only do this when 8601 // updating the platform). 8602 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8603 grant = GRANT_DENIED; 8604 } 8605 } 8606 } 8607 8608 switch (grant) { 8609 case GRANT_INSTALL: { 8610 // Revoke this as runtime permission to handle the case of 8611 // a runtime permission being downgraded to an install one. 8612 for (int userId : UserManagerService.getInstance().getUserIds()) { 8613 if (origPermissions.getRuntimePermissionState( 8614 bp.name, userId) != null) { 8615 // Revoke the runtime permission and clear the flags. 8616 origPermissions.revokeRuntimePermission(bp, userId); 8617 origPermissions.updatePermissionFlags(bp, userId, 8618 PackageManager.MASK_PERMISSION_FLAGS, 0); 8619 // If we revoked a permission permission, we have to write. 8620 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8621 changedRuntimePermissionUserIds, userId); 8622 } 8623 } 8624 // Grant an install permission. 8625 if (permissionsState.grantInstallPermission(bp) != 8626 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8627 changedInstallPermission = true; 8628 } 8629 } break; 8630 8631 case GRANT_INSTALL_LEGACY: { 8632 // Grant an install permission. 8633 if (permissionsState.grantInstallPermission(bp) != 8634 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8635 changedInstallPermission = true; 8636 } 8637 } break; 8638 8639 case GRANT_RUNTIME: { 8640 // Grant previously granted runtime permissions. 8641 for (int userId : UserManagerService.getInstance().getUserIds()) { 8642 PermissionState permissionState = origPermissions 8643 .getRuntimePermissionState(bp.name, userId); 8644 final int flags = permissionState != null 8645 ? permissionState.getFlags() : 0; 8646 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8647 if (permissionsState.grantRuntimePermission(bp, userId) == 8648 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8649 // If we cannot put the permission as it was, we have to write. 8650 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8651 changedRuntimePermissionUserIds, userId); 8652 } 8653 } 8654 // Propagate the permission flags. 8655 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8656 } 8657 } break; 8658 8659 case GRANT_UPGRADE: { 8660 // Grant runtime permissions for a previously held install permission. 8661 PermissionState permissionState = origPermissions 8662 .getInstallPermissionState(bp.name); 8663 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8664 8665 if (origPermissions.revokeInstallPermission(bp) 8666 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8667 // We will be transferring the permission flags, so clear them. 8668 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8669 PackageManager.MASK_PERMISSION_FLAGS, 0); 8670 changedInstallPermission = true; 8671 } 8672 8673 // If the permission is not to be promoted to runtime we ignore it and 8674 // also its other flags as they are not applicable to install permissions. 8675 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8676 for (int userId : currentUserIds) { 8677 if (permissionsState.grantRuntimePermission(bp, userId) != 8678 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8679 // Transfer the permission flags. 8680 permissionsState.updatePermissionFlags(bp, userId, 8681 flags, flags); 8682 // If we granted the permission, we have to write. 8683 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8684 changedRuntimePermissionUserIds, userId); 8685 } 8686 } 8687 } 8688 } break; 8689 8690 default: { 8691 if (packageOfInterest == null 8692 || packageOfInterest.equals(pkg.packageName)) { 8693 Slog.w(TAG, "Not granting permission " + perm 8694 + " to package " + pkg.packageName 8695 + " because it was previously installed without"); 8696 } 8697 } break; 8698 } 8699 } else { 8700 if (permissionsState.revokeInstallPermission(bp) != 8701 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8702 // Also drop the permission flags. 8703 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8704 PackageManager.MASK_PERMISSION_FLAGS, 0); 8705 changedInstallPermission = true; 8706 Slog.i(TAG, "Un-granting permission " + perm 8707 + " from package " + pkg.packageName 8708 + " (protectionLevel=" + bp.protectionLevel 8709 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8710 + ")"); 8711 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8712 // Don't print warning for app op permissions, since it is fine for them 8713 // not to be granted, there is a UI for the user to decide. 8714 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8715 Slog.w(TAG, "Not granting permission " + perm 8716 + " to package " + pkg.packageName 8717 + " (protectionLevel=" + bp.protectionLevel 8718 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8719 + ")"); 8720 } 8721 } 8722 } 8723 } 8724 8725 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8726 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8727 // This is the first that we have heard about this package, so the 8728 // permissions we have now selected are fixed until explicitly 8729 // changed. 8730 ps.installPermissionsFixed = true; 8731 } 8732 8733 // Persist the runtime permissions state for users with changes. If permissions 8734 // were revoked because no app in the shared user declares them we have to 8735 // write synchronously to avoid losing runtime permissions state. 8736 for (int userId : changedRuntimePermissionUserIds) { 8737 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8738 } 8739 8740 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8741 } 8742 8743 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8744 boolean allowed = false; 8745 final int NP = PackageParser.NEW_PERMISSIONS.length; 8746 for (int ip=0; ip<NP; ip++) { 8747 final PackageParser.NewPermissionInfo npi 8748 = PackageParser.NEW_PERMISSIONS[ip]; 8749 if (npi.name.equals(perm) 8750 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8751 allowed = true; 8752 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8753 + pkg.packageName); 8754 break; 8755 } 8756 } 8757 return allowed; 8758 } 8759 8760 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8761 BasePermission bp, PermissionsState origPermissions) { 8762 boolean allowed; 8763 allowed = (compareSignatures( 8764 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8765 == PackageManager.SIGNATURE_MATCH) 8766 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8767 == PackageManager.SIGNATURE_MATCH); 8768 if (!allowed && (bp.protectionLevel 8769 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8770 if (isSystemApp(pkg)) { 8771 // For updated system applications, a system permission 8772 // is granted only if it had been defined by the original application. 8773 if (pkg.isUpdatedSystemApp()) { 8774 final PackageSetting sysPs = mSettings 8775 .getDisabledSystemPkgLPr(pkg.packageName); 8776 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8777 // If the original was granted this permission, we take 8778 // that grant decision as read and propagate it to the 8779 // update. 8780 if (sysPs.isPrivileged()) { 8781 allowed = true; 8782 } 8783 } else { 8784 // The system apk may have been updated with an older 8785 // version of the one on the data partition, but which 8786 // granted a new system permission that it didn't have 8787 // before. In this case we do want to allow the app to 8788 // now get the new permission if the ancestral apk is 8789 // privileged to get it. 8790 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8791 for (int j=0; 8792 j<sysPs.pkg.requestedPermissions.size(); j++) { 8793 if (perm.equals( 8794 sysPs.pkg.requestedPermissions.get(j))) { 8795 allowed = true; 8796 break; 8797 } 8798 } 8799 } 8800 } 8801 } else { 8802 allowed = isPrivilegedApp(pkg); 8803 } 8804 } 8805 } 8806 if (!allowed) { 8807 if (!allowed && (bp.protectionLevel 8808 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8809 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8810 // If this was a previously normal/dangerous permission that got moved 8811 // to a system permission as part of the runtime permission redesign, then 8812 // we still want to blindly grant it to old apps. 8813 allowed = true; 8814 } 8815 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8816 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8817 // If this permission is to be granted to the system installer and 8818 // this app is an installer, then it gets the permission. 8819 allowed = true; 8820 } 8821 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8822 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8823 // If this permission is to be granted to the system verifier and 8824 // this app is a verifier, then it gets the permission. 8825 allowed = true; 8826 } 8827 if (!allowed && (bp.protectionLevel 8828 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8829 && isSystemApp(pkg)) { 8830 // Any pre-installed system app is allowed to get this permission. 8831 allowed = true; 8832 } 8833 if (!allowed && (bp.protectionLevel 8834 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8835 // For development permissions, a development permission 8836 // is granted only if it was already granted. 8837 allowed = origPermissions.hasInstallPermission(perm); 8838 } 8839 } 8840 return allowed; 8841 } 8842 8843 final class ActivityIntentResolver 8844 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8845 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8846 boolean defaultOnly, int userId) { 8847 if (!sUserManager.exists(userId)) return null; 8848 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8849 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8850 } 8851 8852 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8853 int userId) { 8854 if (!sUserManager.exists(userId)) return null; 8855 mFlags = flags; 8856 return super.queryIntent(intent, resolvedType, 8857 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8858 } 8859 8860 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8861 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8862 if (!sUserManager.exists(userId)) return null; 8863 if (packageActivities == null) { 8864 return null; 8865 } 8866 mFlags = flags; 8867 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8868 final int N = packageActivities.size(); 8869 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8870 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8871 8872 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8873 for (int i = 0; i < N; ++i) { 8874 intentFilters = packageActivities.get(i).intents; 8875 if (intentFilters != null && intentFilters.size() > 0) { 8876 PackageParser.ActivityIntentInfo[] array = 8877 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8878 intentFilters.toArray(array); 8879 listCut.add(array); 8880 } 8881 } 8882 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8883 } 8884 8885 public final void addActivity(PackageParser.Activity a, String type) { 8886 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8887 mActivities.put(a.getComponentName(), a); 8888 if (DEBUG_SHOW_INFO) 8889 Log.v( 8890 TAG, " " + type + " " + 8891 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8892 if (DEBUG_SHOW_INFO) 8893 Log.v(TAG, " Class=" + a.info.name); 8894 final int NI = a.intents.size(); 8895 for (int j=0; j<NI; j++) { 8896 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8897 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8898 intent.setPriority(0); 8899 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8900 + a.className + " with priority > 0, forcing to 0"); 8901 } 8902 if (DEBUG_SHOW_INFO) { 8903 Log.v(TAG, " IntentFilter:"); 8904 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8905 } 8906 if (!intent.debugCheck()) { 8907 Log.w(TAG, "==> For Activity " + a.info.name); 8908 } 8909 addFilter(intent); 8910 } 8911 } 8912 8913 public final void removeActivity(PackageParser.Activity a, String type) { 8914 mActivities.remove(a.getComponentName()); 8915 if (DEBUG_SHOW_INFO) { 8916 Log.v(TAG, " " + type + " " 8917 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8918 : a.info.name) + ":"); 8919 Log.v(TAG, " Class=" + a.info.name); 8920 } 8921 final int NI = a.intents.size(); 8922 for (int j=0; j<NI; j++) { 8923 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8924 if (DEBUG_SHOW_INFO) { 8925 Log.v(TAG, " IntentFilter:"); 8926 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8927 } 8928 removeFilter(intent); 8929 } 8930 } 8931 8932 @Override 8933 protected boolean allowFilterResult( 8934 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8935 ActivityInfo filterAi = filter.activity.info; 8936 for (int i=dest.size()-1; i>=0; i--) { 8937 ActivityInfo destAi = dest.get(i).activityInfo; 8938 if (destAi.name == filterAi.name 8939 && destAi.packageName == filterAi.packageName) { 8940 return false; 8941 } 8942 } 8943 return true; 8944 } 8945 8946 @Override 8947 protected ActivityIntentInfo[] newArray(int size) { 8948 return new ActivityIntentInfo[size]; 8949 } 8950 8951 @Override 8952 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8953 if (!sUserManager.exists(userId)) return true; 8954 PackageParser.Package p = filter.activity.owner; 8955 if (p != null) { 8956 PackageSetting ps = (PackageSetting)p.mExtras; 8957 if (ps != null) { 8958 // System apps are never considered stopped for purposes of 8959 // filtering, because there may be no way for the user to 8960 // actually re-launch them. 8961 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8962 && ps.getStopped(userId); 8963 } 8964 } 8965 return false; 8966 } 8967 8968 @Override 8969 protected boolean isPackageForFilter(String packageName, 8970 PackageParser.ActivityIntentInfo info) { 8971 return packageName.equals(info.activity.owner.packageName); 8972 } 8973 8974 @Override 8975 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8976 int match, int userId) { 8977 if (!sUserManager.exists(userId)) return null; 8978 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8979 return null; 8980 } 8981 final PackageParser.Activity activity = info.activity; 8982 if (mSafeMode && (activity.info.applicationInfo.flags 8983 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8984 return null; 8985 } 8986 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8987 if (ps == null) { 8988 return null; 8989 } 8990 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8991 ps.readUserState(userId), userId); 8992 if (ai == null) { 8993 return null; 8994 } 8995 final ResolveInfo res = new ResolveInfo(); 8996 res.activityInfo = ai; 8997 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8998 res.filter = info; 8999 } 9000 if (info != null) { 9001 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9002 } 9003 res.priority = info.getPriority(); 9004 res.preferredOrder = activity.owner.mPreferredOrder; 9005 //System.out.println("Result: " + res.activityInfo.className + 9006 // " = " + res.priority); 9007 res.match = match; 9008 res.isDefault = info.hasDefault; 9009 res.labelRes = info.labelRes; 9010 res.nonLocalizedLabel = info.nonLocalizedLabel; 9011 if (userNeedsBadging(userId)) { 9012 res.noResourceId = true; 9013 } else { 9014 res.icon = info.icon; 9015 } 9016 res.iconResourceId = info.icon; 9017 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9018 return res; 9019 } 9020 9021 @Override 9022 protected void sortResults(List<ResolveInfo> results) { 9023 Collections.sort(results, mResolvePrioritySorter); 9024 } 9025 9026 @Override 9027 protected void dumpFilter(PrintWriter out, String prefix, 9028 PackageParser.ActivityIntentInfo filter) { 9029 out.print(prefix); out.print( 9030 Integer.toHexString(System.identityHashCode(filter.activity))); 9031 out.print(' '); 9032 filter.activity.printComponentShortName(out); 9033 out.print(" filter "); 9034 out.println(Integer.toHexString(System.identityHashCode(filter))); 9035 } 9036 9037 @Override 9038 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9039 return filter.activity; 9040 } 9041 9042 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9043 PackageParser.Activity activity = (PackageParser.Activity)label; 9044 out.print(prefix); out.print( 9045 Integer.toHexString(System.identityHashCode(activity))); 9046 out.print(' '); 9047 activity.printComponentShortName(out); 9048 if (count > 1) { 9049 out.print(" ("); out.print(count); out.print(" filters)"); 9050 } 9051 out.println(); 9052 } 9053 9054// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9055// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9056// final List<ResolveInfo> retList = Lists.newArrayList(); 9057// while (i.hasNext()) { 9058// final ResolveInfo resolveInfo = i.next(); 9059// if (isEnabledLP(resolveInfo.activityInfo)) { 9060// retList.add(resolveInfo); 9061// } 9062// } 9063// return retList; 9064// } 9065 9066 // Keys are String (activity class name), values are Activity. 9067 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9068 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9069 private int mFlags; 9070 } 9071 9072 private final class ServiceIntentResolver 9073 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9074 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9075 boolean defaultOnly, int userId) { 9076 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9077 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9078 } 9079 9080 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9081 int userId) { 9082 if (!sUserManager.exists(userId)) return null; 9083 mFlags = flags; 9084 return super.queryIntent(intent, resolvedType, 9085 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9086 } 9087 9088 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9089 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9090 if (!sUserManager.exists(userId)) return null; 9091 if (packageServices == null) { 9092 return null; 9093 } 9094 mFlags = flags; 9095 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9096 final int N = packageServices.size(); 9097 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9098 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9099 9100 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9101 for (int i = 0; i < N; ++i) { 9102 intentFilters = packageServices.get(i).intents; 9103 if (intentFilters != null && intentFilters.size() > 0) { 9104 PackageParser.ServiceIntentInfo[] array = 9105 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9106 intentFilters.toArray(array); 9107 listCut.add(array); 9108 } 9109 } 9110 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9111 } 9112 9113 public final void addService(PackageParser.Service s) { 9114 mServices.put(s.getComponentName(), s); 9115 if (DEBUG_SHOW_INFO) { 9116 Log.v(TAG, " " 9117 + (s.info.nonLocalizedLabel != null 9118 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9119 Log.v(TAG, " Class=" + s.info.name); 9120 } 9121 final int NI = s.intents.size(); 9122 int j; 9123 for (j=0; j<NI; j++) { 9124 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9125 if (DEBUG_SHOW_INFO) { 9126 Log.v(TAG, " IntentFilter:"); 9127 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9128 } 9129 if (!intent.debugCheck()) { 9130 Log.w(TAG, "==> For Service " + s.info.name); 9131 } 9132 addFilter(intent); 9133 } 9134 } 9135 9136 public final void removeService(PackageParser.Service s) { 9137 mServices.remove(s.getComponentName()); 9138 if (DEBUG_SHOW_INFO) { 9139 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9140 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9141 Log.v(TAG, " Class=" + s.info.name); 9142 } 9143 final int NI = s.intents.size(); 9144 int j; 9145 for (j=0; j<NI; j++) { 9146 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9147 if (DEBUG_SHOW_INFO) { 9148 Log.v(TAG, " IntentFilter:"); 9149 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9150 } 9151 removeFilter(intent); 9152 } 9153 } 9154 9155 @Override 9156 protected boolean allowFilterResult( 9157 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9158 ServiceInfo filterSi = filter.service.info; 9159 for (int i=dest.size()-1; i>=0; i--) { 9160 ServiceInfo destAi = dest.get(i).serviceInfo; 9161 if (destAi.name == filterSi.name 9162 && destAi.packageName == filterSi.packageName) { 9163 return false; 9164 } 9165 } 9166 return true; 9167 } 9168 9169 @Override 9170 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9171 return new PackageParser.ServiceIntentInfo[size]; 9172 } 9173 9174 @Override 9175 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9176 if (!sUserManager.exists(userId)) return true; 9177 PackageParser.Package p = filter.service.owner; 9178 if (p != null) { 9179 PackageSetting ps = (PackageSetting)p.mExtras; 9180 if (ps != null) { 9181 // System apps are never considered stopped for purposes of 9182 // filtering, because there may be no way for the user to 9183 // actually re-launch them. 9184 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9185 && ps.getStopped(userId); 9186 } 9187 } 9188 return false; 9189 } 9190 9191 @Override 9192 protected boolean isPackageForFilter(String packageName, 9193 PackageParser.ServiceIntentInfo info) { 9194 return packageName.equals(info.service.owner.packageName); 9195 } 9196 9197 @Override 9198 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9199 int match, int userId) { 9200 if (!sUserManager.exists(userId)) return null; 9201 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9202 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9203 return null; 9204 } 9205 final PackageParser.Service service = info.service; 9206 if (mSafeMode && (service.info.applicationInfo.flags 9207 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9208 return null; 9209 } 9210 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9211 if (ps == null) { 9212 return null; 9213 } 9214 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9215 ps.readUserState(userId), userId); 9216 if (si == null) { 9217 return null; 9218 } 9219 final ResolveInfo res = new ResolveInfo(); 9220 res.serviceInfo = si; 9221 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9222 res.filter = filter; 9223 } 9224 res.priority = info.getPriority(); 9225 res.preferredOrder = service.owner.mPreferredOrder; 9226 res.match = match; 9227 res.isDefault = info.hasDefault; 9228 res.labelRes = info.labelRes; 9229 res.nonLocalizedLabel = info.nonLocalizedLabel; 9230 res.icon = info.icon; 9231 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9232 return res; 9233 } 9234 9235 @Override 9236 protected void sortResults(List<ResolveInfo> results) { 9237 Collections.sort(results, mResolvePrioritySorter); 9238 } 9239 9240 @Override 9241 protected void dumpFilter(PrintWriter out, String prefix, 9242 PackageParser.ServiceIntentInfo filter) { 9243 out.print(prefix); out.print( 9244 Integer.toHexString(System.identityHashCode(filter.service))); 9245 out.print(' '); 9246 filter.service.printComponentShortName(out); 9247 out.print(" filter "); 9248 out.println(Integer.toHexString(System.identityHashCode(filter))); 9249 } 9250 9251 @Override 9252 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9253 return filter.service; 9254 } 9255 9256 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9257 PackageParser.Service service = (PackageParser.Service)label; 9258 out.print(prefix); out.print( 9259 Integer.toHexString(System.identityHashCode(service))); 9260 out.print(' '); 9261 service.printComponentShortName(out); 9262 if (count > 1) { 9263 out.print(" ("); out.print(count); out.print(" filters)"); 9264 } 9265 out.println(); 9266 } 9267 9268// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9269// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9270// final List<ResolveInfo> retList = Lists.newArrayList(); 9271// while (i.hasNext()) { 9272// final ResolveInfo resolveInfo = (ResolveInfo) i; 9273// if (isEnabledLP(resolveInfo.serviceInfo)) { 9274// retList.add(resolveInfo); 9275// } 9276// } 9277// return retList; 9278// } 9279 9280 // Keys are String (activity class name), values are Activity. 9281 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9282 = new ArrayMap<ComponentName, PackageParser.Service>(); 9283 private int mFlags; 9284 }; 9285 9286 private final class ProviderIntentResolver 9287 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9288 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9289 boolean defaultOnly, int userId) { 9290 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9291 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9292 } 9293 9294 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9295 int userId) { 9296 if (!sUserManager.exists(userId)) 9297 return null; 9298 mFlags = flags; 9299 return super.queryIntent(intent, resolvedType, 9300 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9301 } 9302 9303 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9304 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9305 if (!sUserManager.exists(userId)) 9306 return null; 9307 if (packageProviders == null) { 9308 return null; 9309 } 9310 mFlags = flags; 9311 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9312 final int N = packageProviders.size(); 9313 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9314 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9315 9316 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9317 for (int i = 0; i < N; ++i) { 9318 intentFilters = packageProviders.get(i).intents; 9319 if (intentFilters != null && intentFilters.size() > 0) { 9320 PackageParser.ProviderIntentInfo[] array = 9321 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9322 intentFilters.toArray(array); 9323 listCut.add(array); 9324 } 9325 } 9326 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9327 } 9328 9329 public final void addProvider(PackageParser.Provider p) { 9330 if (mProviders.containsKey(p.getComponentName())) { 9331 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9332 return; 9333 } 9334 9335 mProviders.put(p.getComponentName(), p); 9336 if (DEBUG_SHOW_INFO) { 9337 Log.v(TAG, " " 9338 + (p.info.nonLocalizedLabel != null 9339 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9340 Log.v(TAG, " Class=" + p.info.name); 9341 } 9342 final int NI = p.intents.size(); 9343 int j; 9344 for (j = 0; j < NI; j++) { 9345 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9346 if (DEBUG_SHOW_INFO) { 9347 Log.v(TAG, " IntentFilter:"); 9348 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9349 } 9350 if (!intent.debugCheck()) { 9351 Log.w(TAG, "==> For Provider " + p.info.name); 9352 } 9353 addFilter(intent); 9354 } 9355 } 9356 9357 public final void removeProvider(PackageParser.Provider p) { 9358 mProviders.remove(p.getComponentName()); 9359 if (DEBUG_SHOW_INFO) { 9360 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9361 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9362 Log.v(TAG, " Class=" + p.info.name); 9363 } 9364 final int NI = p.intents.size(); 9365 int j; 9366 for (j = 0; j < NI; j++) { 9367 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9368 if (DEBUG_SHOW_INFO) { 9369 Log.v(TAG, " IntentFilter:"); 9370 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9371 } 9372 removeFilter(intent); 9373 } 9374 } 9375 9376 @Override 9377 protected boolean allowFilterResult( 9378 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9379 ProviderInfo filterPi = filter.provider.info; 9380 for (int i = dest.size() - 1; i >= 0; i--) { 9381 ProviderInfo destPi = dest.get(i).providerInfo; 9382 if (destPi.name == filterPi.name 9383 && destPi.packageName == filterPi.packageName) { 9384 return false; 9385 } 9386 } 9387 return true; 9388 } 9389 9390 @Override 9391 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9392 return new PackageParser.ProviderIntentInfo[size]; 9393 } 9394 9395 @Override 9396 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9397 if (!sUserManager.exists(userId)) 9398 return true; 9399 PackageParser.Package p = filter.provider.owner; 9400 if (p != null) { 9401 PackageSetting ps = (PackageSetting) p.mExtras; 9402 if (ps != null) { 9403 // System apps are never considered stopped for purposes of 9404 // filtering, because there may be no way for the user to 9405 // actually re-launch them. 9406 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9407 && ps.getStopped(userId); 9408 } 9409 } 9410 return false; 9411 } 9412 9413 @Override 9414 protected boolean isPackageForFilter(String packageName, 9415 PackageParser.ProviderIntentInfo info) { 9416 return packageName.equals(info.provider.owner.packageName); 9417 } 9418 9419 @Override 9420 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9421 int match, int userId) { 9422 if (!sUserManager.exists(userId)) 9423 return null; 9424 final PackageParser.ProviderIntentInfo info = filter; 9425 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9426 return null; 9427 } 9428 final PackageParser.Provider provider = info.provider; 9429 if (mSafeMode && (provider.info.applicationInfo.flags 9430 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9431 return null; 9432 } 9433 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9434 if (ps == null) { 9435 return null; 9436 } 9437 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9438 ps.readUserState(userId), userId); 9439 if (pi == null) { 9440 return null; 9441 } 9442 final ResolveInfo res = new ResolveInfo(); 9443 res.providerInfo = pi; 9444 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9445 res.filter = filter; 9446 } 9447 res.priority = info.getPriority(); 9448 res.preferredOrder = provider.owner.mPreferredOrder; 9449 res.match = match; 9450 res.isDefault = info.hasDefault; 9451 res.labelRes = info.labelRes; 9452 res.nonLocalizedLabel = info.nonLocalizedLabel; 9453 res.icon = info.icon; 9454 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9455 return res; 9456 } 9457 9458 @Override 9459 protected void sortResults(List<ResolveInfo> results) { 9460 Collections.sort(results, mResolvePrioritySorter); 9461 } 9462 9463 @Override 9464 protected void dumpFilter(PrintWriter out, String prefix, 9465 PackageParser.ProviderIntentInfo filter) { 9466 out.print(prefix); 9467 out.print( 9468 Integer.toHexString(System.identityHashCode(filter.provider))); 9469 out.print(' '); 9470 filter.provider.printComponentShortName(out); 9471 out.print(" filter "); 9472 out.println(Integer.toHexString(System.identityHashCode(filter))); 9473 } 9474 9475 @Override 9476 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9477 return filter.provider; 9478 } 9479 9480 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9481 PackageParser.Provider provider = (PackageParser.Provider)label; 9482 out.print(prefix); out.print( 9483 Integer.toHexString(System.identityHashCode(provider))); 9484 out.print(' '); 9485 provider.printComponentShortName(out); 9486 if (count > 1) { 9487 out.print(" ("); out.print(count); out.print(" filters)"); 9488 } 9489 out.println(); 9490 } 9491 9492 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9493 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9494 private int mFlags; 9495 }; 9496 9497 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9498 new Comparator<ResolveInfo>() { 9499 public int compare(ResolveInfo r1, ResolveInfo r2) { 9500 int v1 = r1.priority; 9501 int v2 = r2.priority; 9502 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9503 if (v1 != v2) { 9504 return (v1 > v2) ? -1 : 1; 9505 } 9506 v1 = r1.preferredOrder; 9507 v2 = r2.preferredOrder; 9508 if (v1 != v2) { 9509 return (v1 > v2) ? -1 : 1; 9510 } 9511 if (r1.isDefault != r2.isDefault) { 9512 return r1.isDefault ? -1 : 1; 9513 } 9514 v1 = r1.match; 9515 v2 = r2.match; 9516 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9517 if (v1 != v2) { 9518 return (v1 > v2) ? -1 : 1; 9519 } 9520 if (r1.system != r2.system) { 9521 return r1.system ? -1 : 1; 9522 } 9523 return 0; 9524 } 9525 }; 9526 9527 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9528 new Comparator<ProviderInfo>() { 9529 public int compare(ProviderInfo p1, ProviderInfo p2) { 9530 final int v1 = p1.initOrder; 9531 final int v2 = p2.initOrder; 9532 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9533 } 9534 }; 9535 9536 final void sendPackageBroadcast(final String action, final String pkg, 9537 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9538 final int[] userIds) { 9539 mHandler.post(new Runnable() { 9540 @Override 9541 public void run() { 9542 try { 9543 final IActivityManager am = ActivityManagerNative.getDefault(); 9544 if (am == null) return; 9545 final int[] resolvedUserIds; 9546 if (userIds == null) { 9547 resolvedUserIds = am.getRunningUserIds(); 9548 } else { 9549 resolvedUserIds = userIds; 9550 } 9551 for (int id : resolvedUserIds) { 9552 final Intent intent = new Intent(action, 9553 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9554 if (extras != null) { 9555 intent.putExtras(extras); 9556 } 9557 if (targetPkg != null) { 9558 intent.setPackage(targetPkg); 9559 } 9560 // Modify the UID when posting to other users 9561 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9562 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9563 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9564 intent.putExtra(Intent.EXTRA_UID, uid); 9565 } 9566 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9567 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9568 if (DEBUG_BROADCASTS) { 9569 RuntimeException here = new RuntimeException("here"); 9570 here.fillInStackTrace(); 9571 Slog.d(TAG, "Sending to user " + id + ": " 9572 + intent.toShortString(false, true, false, false) 9573 + " " + intent.getExtras(), here); 9574 } 9575 am.broadcastIntent(null, intent, null, finishedReceiver, 9576 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9577 null, finishedReceiver != null, false, id); 9578 } 9579 } catch (RemoteException ex) { 9580 } 9581 } 9582 }); 9583 } 9584 9585 /** 9586 * Check if the external storage media is available. This is true if there 9587 * is a mounted external storage medium or if the external storage is 9588 * emulated. 9589 */ 9590 private boolean isExternalMediaAvailable() { 9591 return mMediaMounted || Environment.isExternalStorageEmulated(); 9592 } 9593 9594 @Override 9595 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9596 // writer 9597 synchronized (mPackages) { 9598 if (!isExternalMediaAvailable()) { 9599 // If the external storage is no longer mounted at this point, 9600 // the caller may not have been able to delete all of this 9601 // packages files and can not delete any more. Bail. 9602 return null; 9603 } 9604 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9605 if (lastPackage != null) { 9606 pkgs.remove(lastPackage); 9607 } 9608 if (pkgs.size() > 0) { 9609 return pkgs.get(0); 9610 } 9611 } 9612 return null; 9613 } 9614 9615 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9616 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9617 userId, andCode ? 1 : 0, packageName); 9618 if (mSystemReady) { 9619 msg.sendToTarget(); 9620 } else { 9621 if (mPostSystemReadyMessages == null) { 9622 mPostSystemReadyMessages = new ArrayList<>(); 9623 } 9624 mPostSystemReadyMessages.add(msg); 9625 } 9626 } 9627 9628 void startCleaningPackages() { 9629 // reader 9630 synchronized (mPackages) { 9631 if (!isExternalMediaAvailable()) { 9632 return; 9633 } 9634 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9635 return; 9636 } 9637 } 9638 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9639 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9640 IActivityManager am = ActivityManagerNative.getDefault(); 9641 if (am != null) { 9642 try { 9643 am.startService(null, intent, null, mContext.getOpPackageName(), 9644 UserHandle.USER_SYSTEM); 9645 } catch (RemoteException e) { 9646 } 9647 } 9648 } 9649 9650 @Override 9651 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9652 int installFlags, String installerPackageName, VerificationParams verificationParams, 9653 String packageAbiOverride) { 9654 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9655 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9656 } 9657 9658 @Override 9659 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9660 int installFlags, String installerPackageName, VerificationParams verificationParams, 9661 String packageAbiOverride, int userId) { 9662 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9663 9664 final int callingUid = Binder.getCallingUid(); 9665 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9666 9667 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9668 try { 9669 if (observer != null) { 9670 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9671 } 9672 } catch (RemoteException re) { 9673 } 9674 return; 9675 } 9676 9677 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9678 installFlags |= PackageManager.INSTALL_FROM_ADB; 9679 9680 } else { 9681 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9682 // about installerPackageName. 9683 9684 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9685 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9686 } 9687 9688 UserHandle user; 9689 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9690 user = UserHandle.ALL; 9691 } else { 9692 user = new UserHandle(userId); 9693 } 9694 9695 // Only system components can circumvent runtime permissions when installing. 9696 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9697 && mContext.checkCallingOrSelfPermission(Manifest.permission 9698 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9699 throw new SecurityException("You need the " 9700 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9701 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9702 } 9703 9704 verificationParams.setInstallerUid(callingUid); 9705 9706 final File originFile = new File(originPath); 9707 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9708 9709 final Message msg = mHandler.obtainMessage(INIT_COPY); 9710 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9711 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9712 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9713 msg.obj = params; 9714 9715 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9716 System.identityHashCode(msg.obj)); 9717 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9718 System.identityHashCode(msg.obj)); 9719 9720 mHandler.sendMessage(msg); 9721 } 9722 9723 void installStage(String packageName, File stagedDir, String stagedCid, 9724 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9725 String installerPackageName, int installerUid, UserHandle user) { 9726 final VerificationParams verifParams = new VerificationParams( 9727 null, sessionParams.originatingUri, sessionParams.referrerUri, 9728 sessionParams.originatingUid, null); 9729 verifParams.setInstallerUid(installerUid); 9730 9731 final OriginInfo origin; 9732 if (stagedDir != null) { 9733 origin = OriginInfo.fromStagedFile(stagedDir); 9734 } else { 9735 origin = OriginInfo.fromStagedContainer(stagedCid); 9736 } 9737 9738 final Message msg = mHandler.obtainMessage(INIT_COPY); 9739 final InstallParams params = new InstallParams(origin, null, observer, 9740 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9741 verifParams, user, sessionParams.abiOverride, 9742 sessionParams.grantedRuntimePermissions); 9743 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9744 msg.obj = params; 9745 9746 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9747 System.identityHashCode(msg.obj)); 9748 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9749 System.identityHashCode(msg.obj)); 9750 9751 mHandler.sendMessage(msg); 9752 } 9753 9754 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9755 Bundle extras = new Bundle(1); 9756 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9757 9758 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9759 packageName, extras, null, null, new int[] {userId}); 9760 try { 9761 IActivityManager am = ActivityManagerNative.getDefault(); 9762 final boolean isSystem = 9763 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9764 if (isSystem && am.isUserRunning(userId, false)) { 9765 // The just-installed/enabled app is bundled on the system, so presumed 9766 // to be able to run automatically without needing an explicit launch. 9767 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9768 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9769 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9770 .setPackage(packageName); 9771 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9772 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9773 } 9774 } catch (RemoteException e) { 9775 // shouldn't happen 9776 Slog.w(TAG, "Unable to bootstrap installed package", e); 9777 } 9778 } 9779 9780 @Override 9781 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9782 int userId) { 9783 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9784 PackageSetting pkgSetting; 9785 final int uid = Binder.getCallingUid(); 9786 enforceCrossUserPermission(uid, userId, true, true, 9787 "setApplicationHiddenSetting for user " + userId); 9788 9789 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9790 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9791 return false; 9792 } 9793 9794 long callingId = Binder.clearCallingIdentity(); 9795 try { 9796 boolean sendAdded = false; 9797 boolean sendRemoved = false; 9798 // writer 9799 synchronized (mPackages) { 9800 pkgSetting = mSettings.mPackages.get(packageName); 9801 if (pkgSetting == null) { 9802 return false; 9803 } 9804 if (pkgSetting.getHidden(userId) != hidden) { 9805 pkgSetting.setHidden(hidden, userId); 9806 mSettings.writePackageRestrictionsLPr(userId); 9807 if (hidden) { 9808 sendRemoved = true; 9809 } else { 9810 sendAdded = true; 9811 } 9812 } 9813 } 9814 if (sendAdded) { 9815 sendPackageAddedForUser(packageName, pkgSetting, userId); 9816 return true; 9817 } 9818 if (sendRemoved) { 9819 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9820 "hiding pkg"); 9821 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9822 return true; 9823 } 9824 } finally { 9825 Binder.restoreCallingIdentity(callingId); 9826 } 9827 return false; 9828 } 9829 9830 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9831 int userId) { 9832 final PackageRemovedInfo info = new PackageRemovedInfo(); 9833 info.removedPackage = packageName; 9834 info.removedUsers = new int[] {userId}; 9835 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9836 info.sendBroadcast(false, false, false); 9837 } 9838 9839 /** 9840 * Returns true if application is not found or there was an error. Otherwise it returns 9841 * the hidden state of the package for the given user. 9842 */ 9843 @Override 9844 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9845 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9846 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9847 false, "getApplicationHidden for user " + userId); 9848 PackageSetting pkgSetting; 9849 long callingId = Binder.clearCallingIdentity(); 9850 try { 9851 // writer 9852 synchronized (mPackages) { 9853 pkgSetting = mSettings.mPackages.get(packageName); 9854 if (pkgSetting == null) { 9855 return true; 9856 } 9857 return pkgSetting.getHidden(userId); 9858 } 9859 } finally { 9860 Binder.restoreCallingIdentity(callingId); 9861 } 9862 } 9863 9864 /** 9865 * @hide 9866 */ 9867 @Override 9868 public int installExistingPackageAsUser(String packageName, int userId) { 9869 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9870 null); 9871 PackageSetting pkgSetting; 9872 final int uid = Binder.getCallingUid(); 9873 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9874 + userId); 9875 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9876 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9877 } 9878 9879 long callingId = Binder.clearCallingIdentity(); 9880 try { 9881 boolean sendAdded = false; 9882 9883 // writer 9884 synchronized (mPackages) { 9885 pkgSetting = mSettings.mPackages.get(packageName); 9886 if (pkgSetting == null) { 9887 return PackageManager.INSTALL_FAILED_INVALID_URI; 9888 } 9889 if (!pkgSetting.getInstalled(userId)) { 9890 pkgSetting.setInstalled(true, userId); 9891 pkgSetting.setHidden(false, userId); 9892 mSettings.writePackageRestrictionsLPr(userId); 9893 sendAdded = true; 9894 } 9895 } 9896 9897 if (sendAdded) { 9898 sendPackageAddedForUser(packageName, pkgSetting, userId); 9899 } 9900 } finally { 9901 Binder.restoreCallingIdentity(callingId); 9902 } 9903 9904 return PackageManager.INSTALL_SUCCEEDED; 9905 } 9906 9907 boolean isUserRestricted(int userId, String restrictionKey) { 9908 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9909 if (restrictions.getBoolean(restrictionKey, false)) { 9910 Log.w(TAG, "User is restricted: " + restrictionKey); 9911 return true; 9912 } 9913 return false; 9914 } 9915 9916 @Override 9917 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9918 mContext.enforceCallingOrSelfPermission( 9919 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9920 "Only package verification agents can verify applications"); 9921 9922 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9923 final PackageVerificationResponse response = new PackageVerificationResponse( 9924 verificationCode, Binder.getCallingUid()); 9925 msg.arg1 = id; 9926 msg.obj = response; 9927 mHandler.sendMessage(msg); 9928 } 9929 9930 @Override 9931 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9932 long millisecondsToDelay) { 9933 mContext.enforceCallingOrSelfPermission( 9934 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9935 "Only package verification agents can extend verification timeouts"); 9936 9937 final PackageVerificationState state = mPendingVerification.get(id); 9938 final PackageVerificationResponse response = new PackageVerificationResponse( 9939 verificationCodeAtTimeout, Binder.getCallingUid()); 9940 9941 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9942 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9943 } 9944 if (millisecondsToDelay < 0) { 9945 millisecondsToDelay = 0; 9946 } 9947 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9948 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9949 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9950 } 9951 9952 if ((state != null) && !state.timeoutExtended()) { 9953 state.extendTimeout(); 9954 9955 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9956 msg.arg1 = id; 9957 msg.obj = response; 9958 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9959 } 9960 } 9961 9962 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9963 int verificationCode, UserHandle user) { 9964 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9965 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9966 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9967 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9968 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9969 9970 mContext.sendBroadcastAsUser(intent, user, 9971 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9972 } 9973 9974 private ComponentName matchComponentForVerifier(String packageName, 9975 List<ResolveInfo> receivers) { 9976 ActivityInfo targetReceiver = null; 9977 9978 final int NR = receivers.size(); 9979 for (int i = 0; i < NR; i++) { 9980 final ResolveInfo info = receivers.get(i); 9981 if (info.activityInfo == null) { 9982 continue; 9983 } 9984 9985 if (packageName.equals(info.activityInfo.packageName)) { 9986 targetReceiver = info.activityInfo; 9987 break; 9988 } 9989 } 9990 9991 if (targetReceiver == null) { 9992 return null; 9993 } 9994 9995 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9996 } 9997 9998 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9999 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10000 if (pkgInfo.verifiers.length == 0) { 10001 return null; 10002 } 10003 10004 final int N = pkgInfo.verifiers.length; 10005 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10006 for (int i = 0; i < N; i++) { 10007 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10008 10009 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10010 receivers); 10011 if (comp == null) { 10012 continue; 10013 } 10014 10015 final int verifierUid = getUidForVerifier(verifierInfo); 10016 if (verifierUid == -1) { 10017 continue; 10018 } 10019 10020 if (DEBUG_VERIFY) { 10021 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10022 + " with the correct signature"); 10023 } 10024 sufficientVerifiers.add(comp); 10025 verificationState.addSufficientVerifier(verifierUid); 10026 } 10027 10028 return sufficientVerifiers; 10029 } 10030 10031 private int getUidForVerifier(VerifierInfo verifierInfo) { 10032 synchronized (mPackages) { 10033 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10034 if (pkg == null) { 10035 return -1; 10036 } else if (pkg.mSignatures.length != 1) { 10037 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10038 + " has more than one signature; ignoring"); 10039 return -1; 10040 } 10041 10042 /* 10043 * If the public key of the package's signature does not match 10044 * our expected public key, then this is a different package and 10045 * we should skip. 10046 */ 10047 10048 final byte[] expectedPublicKey; 10049 try { 10050 final Signature verifierSig = pkg.mSignatures[0]; 10051 final PublicKey publicKey = verifierSig.getPublicKey(); 10052 expectedPublicKey = publicKey.getEncoded(); 10053 } catch (CertificateException e) { 10054 return -1; 10055 } 10056 10057 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10058 10059 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10060 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10061 + " does not have the expected public key; ignoring"); 10062 return -1; 10063 } 10064 10065 return pkg.applicationInfo.uid; 10066 } 10067 } 10068 10069 @Override 10070 public void finishPackageInstall(int token) { 10071 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10072 10073 if (DEBUG_INSTALL) { 10074 Slog.v(TAG, "BM finishing package install for " + token); 10075 } 10076 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10077 10078 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10079 mHandler.sendMessage(msg); 10080 } 10081 10082 /** 10083 * Get the verification agent timeout. 10084 * 10085 * @return verification timeout in milliseconds 10086 */ 10087 private long getVerificationTimeout() { 10088 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10089 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10090 DEFAULT_VERIFICATION_TIMEOUT); 10091 } 10092 10093 /** 10094 * Get the default verification agent response code. 10095 * 10096 * @return default verification response code 10097 */ 10098 private int getDefaultVerificationResponse() { 10099 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10100 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10101 DEFAULT_VERIFICATION_RESPONSE); 10102 } 10103 10104 /** 10105 * Check whether or not package verification has been enabled. 10106 * 10107 * @return true if verification should be performed 10108 */ 10109 private boolean isVerificationEnabled(int userId, int installFlags) { 10110 if (!DEFAULT_VERIFY_ENABLE) { 10111 return false; 10112 } 10113 // TODO: fix b/25118622; don't bypass verification 10114 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10115 return false; 10116 } 10117 10118 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10119 10120 // Check if installing from ADB 10121 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10122 // Do not run verification in a test harness environment 10123 if (ActivityManager.isRunningInTestHarness()) { 10124 return false; 10125 } 10126 if (ensureVerifyAppsEnabled) { 10127 return true; 10128 } 10129 // Check if the developer does not want package verification for ADB installs 10130 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10131 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10132 return false; 10133 } 10134 } 10135 10136 if (ensureVerifyAppsEnabled) { 10137 return true; 10138 } 10139 10140 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10141 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10142 } 10143 10144 @Override 10145 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10146 throws RemoteException { 10147 mContext.enforceCallingOrSelfPermission( 10148 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10149 "Only intentfilter verification agents can verify applications"); 10150 10151 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10152 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10153 Binder.getCallingUid(), verificationCode, failedDomains); 10154 msg.arg1 = id; 10155 msg.obj = response; 10156 mHandler.sendMessage(msg); 10157 } 10158 10159 @Override 10160 public int getIntentVerificationStatus(String packageName, int userId) { 10161 synchronized (mPackages) { 10162 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10163 } 10164 } 10165 10166 @Override 10167 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10168 mContext.enforceCallingOrSelfPermission( 10169 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10170 10171 boolean result = false; 10172 synchronized (mPackages) { 10173 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10174 } 10175 if (result) { 10176 scheduleWritePackageRestrictionsLocked(userId); 10177 } 10178 return result; 10179 } 10180 10181 @Override 10182 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10183 synchronized (mPackages) { 10184 return mSettings.getIntentFilterVerificationsLPr(packageName); 10185 } 10186 } 10187 10188 @Override 10189 public List<IntentFilter> getAllIntentFilters(String packageName) { 10190 if (TextUtils.isEmpty(packageName)) { 10191 return Collections.<IntentFilter>emptyList(); 10192 } 10193 synchronized (mPackages) { 10194 PackageParser.Package pkg = mPackages.get(packageName); 10195 if (pkg == null || pkg.activities == null) { 10196 return Collections.<IntentFilter>emptyList(); 10197 } 10198 final int count = pkg.activities.size(); 10199 ArrayList<IntentFilter> result = new ArrayList<>(); 10200 for (int n=0; n<count; n++) { 10201 PackageParser.Activity activity = pkg.activities.get(n); 10202 if (activity.intents != null || activity.intents.size() > 0) { 10203 result.addAll(activity.intents); 10204 } 10205 } 10206 return result; 10207 } 10208 } 10209 10210 @Override 10211 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10212 mContext.enforceCallingOrSelfPermission( 10213 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10214 10215 synchronized (mPackages) { 10216 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10217 if (packageName != null) { 10218 result |= updateIntentVerificationStatus(packageName, 10219 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10220 userId); 10221 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10222 packageName, userId); 10223 } 10224 return result; 10225 } 10226 } 10227 10228 @Override 10229 public String getDefaultBrowserPackageName(int userId) { 10230 synchronized (mPackages) { 10231 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10232 } 10233 } 10234 10235 /** 10236 * Get the "allow unknown sources" setting. 10237 * 10238 * @return the current "allow unknown sources" setting 10239 */ 10240 private int getUnknownSourcesSettings() { 10241 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10242 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10243 -1); 10244 } 10245 10246 @Override 10247 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10248 final int uid = Binder.getCallingUid(); 10249 // writer 10250 synchronized (mPackages) { 10251 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10252 if (targetPackageSetting == null) { 10253 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10254 } 10255 10256 PackageSetting installerPackageSetting; 10257 if (installerPackageName != null) { 10258 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10259 if (installerPackageSetting == null) { 10260 throw new IllegalArgumentException("Unknown installer package: " 10261 + installerPackageName); 10262 } 10263 } else { 10264 installerPackageSetting = null; 10265 } 10266 10267 Signature[] callerSignature; 10268 Object obj = mSettings.getUserIdLPr(uid); 10269 if (obj != null) { 10270 if (obj instanceof SharedUserSetting) { 10271 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10272 } else if (obj instanceof PackageSetting) { 10273 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10274 } else { 10275 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10276 } 10277 } else { 10278 throw new SecurityException("Unknown calling uid " + uid); 10279 } 10280 10281 // Verify: can't set installerPackageName to a package that is 10282 // not signed with the same cert as the caller. 10283 if (installerPackageSetting != null) { 10284 if (compareSignatures(callerSignature, 10285 installerPackageSetting.signatures.mSignatures) 10286 != PackageManager.SIGNATURE_MATCH) { 10287 throw new SecurityException( 10288 "Caller does not have same cert as new installer package " 10289 + installerPackageName); 10290 } 10291 } 10292 10293 // Verify: if target already has an installer package, it must 10294 // be signed with the same cert as the caller. 10295 if (targetPackageSetting.installerPackageName != null) { 10296 PackageSetting setting = mSettings.mPackages.get( 10297 targetPackageSetting.installerPackageName); 10298 // If the currently set package isn't valid, then it's always 10299 // okay to change it. 10300 if (setting != null) { 10301 if (compareSignatures(callerSignature, 10302 setting.signatures.mSignatures) 10303 != PackageManager.SIGNATURE_MATCH) { 10304 throw new SecurityException( 10305 "Caller does not have same cert as old installer package " 10306 + targetPackageSetting.installerPackageName); 10307 } 10308 } 10309 } 10310 10311 // Okay! 10312 targetPackageSetting.installerPackageName = installerPackageName; 10313 scheduleWriteSettingsLocked(); 10314 } 10315 } 10316 10317 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10318 // Queue up an async operation since the package installation may take a little while. 10319 mHandler.post(new Runnable() { 10320 public void run() { 10321 mHandler.removeCallbacks(this); 10322 // Result object to be returned 10323 PackageInstalledInfo res = new PackageInstalledInfo(); 10324 res.returnCode = currentStatus; 10325 res.uid = -1; 10326 res.pkg = null; 10327 res.removedInfo = new PackageRemovedInfo(); 10328 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10329 args.doPreInstall(res.returnCode); 10330 synchronized (mInstallLock) { 10331 installPackageTracedLI(args, res); 10332 } 10333 args.doPostInstall(res.returnCode, res.uid); 10334 } 10335 10336 // A restore should be performed at this point if (a) the install 10337 // succeeded, (b) the operation is not an update, and (c) the new 10338 // package has not opted out of backup participation. 10339 final boolean update = res.removedInfo.removedPackage != null; 10340 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10341 boolean doRestore = !update 10342 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10343 10344 // Set up the post-install work request bookkeeping. This will be used 10345 // and cleaned up by the post-install event handling regardless of whether 10346 // there's a restore pass performed. Token values are >= 1. 10347 int token; 10348 if (mNextInstallToken < 0) mNextInstallToken = 1; 10349 token = mNextInstallToken++; 10350 10351 PostInstallData data = new PostInstallData(args, res); 10352 mRunningInstalls.put(token, data); 10353 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10354 10355 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10356 // Pass responsibility to the Backup Manager. It will perform a 10357 // restore if appropriate, then pass responsibility back to the 10358 // Package Manager to run the post-install observer callbacks 10359 // and broadcasts. 10360 IBackupManager bm = IBackupManager.Stub.asInterface( 10361 ServiceManager.getService(Context.BACKUP_SERVICE)); 10362 if (bm != null) { 10363 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10364 + " to BM for possible restore"); 10365 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10366 try { 10367 // TODO: http://b/22388012 10368 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10369 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10370 } else { 10371 doRestore = false; 10372 } 10373 } catch (RemoteException e) { 10374 // can't happen; the backup manager is local 10375 } catch (Exception e) { 10376 Slog.e(TAG, "Exception trying to enqueue restore", e); 10377 doRestore = false; 10378 } 10379 } else { 10380 Slog.e(TAG, "Backup Manager not found!"); 10381 doRestore = false; 10382 } 10383 } 10384 10385 if (!doRestore) { 10386 // No restore possible, or the Backup Manager was mysteriously not 10387 // available -- just fire the post-install work request directly. 10388 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10389 10390 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10391 10392 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10393 mHandler.sendMessage(msg); 10394 } 10395 } 10396 }); 10397 } 10398 10399 private abstract class HandlerParams { 10400 private static final int MAX_RETRIES = 4; 10401 10402 /** 10403 * Number of times startCopy() has been attempted and had a non-fatal 10404 * error. 10405 */ 10406 private int mRetries = 0; 10407 10408 /** User handle for the user requesting the information or installation. */ 10409 private final UserHandle mUser; 10410 String traceMethod; 10411 int traceCookie; 10412 10413 HandlerParams(UserHandle user) { 10414 mUser = user; 10415 } 10416 10417 UserHandle getUser() { 10418 return mUser; 10419 } 10420 10421 HandlerParams setTraceMethod(String traceMethod) { 10422 this.traceMethod = traceMethod; 10423 return this; 10424 } 10425 10426 HandlerParams setTraceCookie(int traceCookie) { 10427 this.traceCookie = traceCookie; 10428 return this; 10429 } 10430 10431 final boolean startCopy() { 10432 boolean res; 10433 try { 10434 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10435 10436 if (++mRetries > MAX_RETRIES) { 10437 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10438 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10439 handleServiceError(); 10440 return false; 10441 } else { 10442 handleStartCopy(); 10443 res = true; 10444 } 10445 } catch (RemoteException e) { 10446 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10447 mHandler.sendEmptyMessage(MCS_RECONNECT); 10448 res = false; 10449 } 10450 handleReturnCode(); 10451 return res; 10452 } 10453 10454 final void serviceError() { 10455 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10456 handleServiceError(); 10457 handleReturnCode(); 10458 } 10459 10460 abstract void handleStartCopy() throws RemoteException; 10461 abstract void handleServiceError(); 10462 abstract void handleReturnCode(); 10463 } 10464 10465 class MeasureParams extends HandlerParams { 10466 private final PackageStats mStats; 10467 private boolean mSuccess; 10468 10469 private final IPackageStatsObserver mObserver; 10470 10471 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10472 super(new UserHandle(stats.userHandle)); 10473 mObserver = observer; 10474 mStats = stats; 10475 } 10476 10477 @Override 10478 public String toString() { 10479 return "MeasureParams{" 10480 + Integer.toHexString(System.identityHashCode(this)) 10481 + " " + mStats.packageName + "}"; 10482 } 10483 10484 @Override 10485 void handleStartCopy() throws RemoteException { 10486 synchronized (mInstallLock) { 10487 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10488 } 10489 10490 if (mSuccess) { 10491 final boolean mounted; 10492 if (Environment.isExternalStorageEmulated()) { 10493 mounted = true; 10494 } else { 10495 final String status = Environment.getExternalStorageState(); 10496 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10497 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10498 } 10499 10500 if (mounted) { 10501 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10502 10503 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10504 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10505 10506 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10507 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10508 10509 // Always subtract cache size, since it's a subdirectory 10510 mStats.externalDataSize -= mStats.externalCacheSize; 10511 10512 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10513 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10514 10515 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10516 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10517 } 10518 } 10519 } 10520 10521 @Override 10522 void handleReturnCode() { 10523 if (mObserver != null) { 10524 try { 10525 mObserver.onGetStatsCompleted(mStats, mSuccess); 10526 } catch (RemoteException e) { 10527 Slog.i(TAG, "Observer no longer exists."); 10528 } 10529 } 10530 } 10531 10532 @Override 10533 void handleServiceError() { 10534 Slog.e(TAG, "Could not measure application " + mStats.packageName 10535 + " external storage"); 10536 } 10537 } 10538 10539 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10540 throws RemoteException { 10541 long result = 0; 10542 for (File path : paths) { 10543 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10544 } 10545 return result; 10546 } 10547 10548 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10549 for (File path : paths) { 10550 try { 10551 mcs.clearDirectory(path.getAbsolutePath()); 10552 } catch (RemoteException e) { 10553 } 10554 } 10555 } 10556 10557 static class OriginInfo { 10558 /** 10559 * Location where install is coming from, before it has been 10560 * copied/renamed into place. This could be a single monolithic APK 10561 * file, or a cluster directory. This location may be untrusted. 10562 */ 10563 final File file; 10564 final String cid; 10565 10566 /** 10567 * Flag indicating that {@link #file} or {@link #cid} has already been 10568 * staged, meaning downstream users don't need to defensively copy the 10569 * contents. 10570 */ 10571 final boolean staged; 10572 10573 /** 10574 * Flag indicating that {@link #file} or {@link #cid} is an already 10575 * installed app that is being moved. 10576 */ 10577 final boolean existing; 10578 10579 final String resolvedPath; 10580 final File resolvedFile; 10581 10582 static OriginInfo fromNothing() { 10583 return new OriginInfo(null, null, false, false); 10584 } 10585 10586 static OriginInfo fromUntrustedFile(File file) { 10587 return new OriginInfo(file, null, false, false); 10588 } 10589 10590 static OriginInfo fromExistingFile(File file) { 10591 return new OriginInfo(file, null, false, true); 10592 } 10593 10594 static OriginInfo fromStagedFile(File file) { 10595 return new OriginInfo(file, null, true, false); 10596 } 10597 10598 static OriginInfo fromStagedContainer(String cid) { 10599 return new OriginInfo(null, cid, true, false); 10600 } 10601 10602 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10603 this.file = file; 10604 this.cid = cid; 10605 this.staged = staged; 10606 this.existing = existing; 10607 10608 if (cid != null) { 10609 resolvedPath = PackageHelper.getSdDir(cid); 10610 resolvedFile = new File(resolvedPath); 10611 } else if (file != null) { 10612 resolvedPath = file.getAbsolutePath(); 10613 resolvedFile = file; 10614 } else { 10615 resolvedPath = null; 10616 resolvedFile = null; 10617 } 10618 } 10619 } 10620 10621 class MoveInfo { 10622 final int moveId; 10623 final String fromUuid; 10624 final String toUuid; 10625 final String packageName; 10626 final String dataAppName; 10627 final int appId; 10628 final String seinfo; 10629 10630 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10631 String dataAppName, int appId, String seinfo) { 10632 this.moveId = moveId; 10633 this.fromUuid = fromUuid; 10634 this.toUuid = toUuid; 10635 this.packageName = packageName; 10636 this.dataAppName = dataAppName; 10637 this.appId = appId; 10638 this.seinfo = seinfo; 10639 } 10640 } 10641 10642 class InstallParams extends HandlerParams { 10643 final OriginInfo origin; 10644 final MoveInfo move; 10645 final IPackageInstallObserver2 observer; 10646 int installFlags; 10647 final String installerPackageName; 10648 final String volumeUuid; 10649 final VerificationParams verificationParams; 10650 private InstallArgs mArgs; 10651 private int mRet; 10652 final String packageAbiOverride; 10653 final String[] grantedRuntimePermissions; 10654 10655 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10656 int installFlags, String installerPackageName, String volumeUuid, 10657 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10658 String[] grantedPermissions) { 10659 super(user); 10660 this.origin = origin; 10661 this.move = move; 10662 this.observer = observer; 10663 this.installFlags = installFlags; 10664 this.installerPackageName = installerPackageName; 10665 this.volumeUuid = volumeUuid; 10666 this.verificationParams = verificationParams; 10667 this.packageAbiOverride = packageAbiOverride; 10668 this.grantedRuntimePermissions = grantedPermissions; 10669 } 10670 10671 @Override 10672 public String toString() { 10673 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10674 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10675 } 10676 10677 public ManifestDigest getManifestDigest() { 10678 if (verificationParams == null) { 10679 return null; 10680 } 10681 return verificationParams.getManifestDigest(); 10682 } 10683 10684 private int installLocationPolicy(PackageInfoLite pkgLite) { 10685 String packageName = pkgLite.packageName; 10686 int installLocation = pkgLite.installLocation; 10687 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10688 // reader 10689 synchronized (mPackages) { 10690 PackageParser.Package pkg = mPackages.get(packageName); 10691 if (pkg != null) { 10692 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10693 // Check for downgrading. 10694 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10695 try { 10696 checkDowngrade(pkg, pkgLite); 10697 } catch (PackageManagerException e) { 10698 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10699 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10700 } 10701 } 10702 // Check for updated system application. 10703 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10704 if (onSd) { 10705 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10706 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10707 } 10708 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10709 } else { 10710 if (onSd) { 10711 // Install flag overrides everything. 10712 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10713 } 10714 // If current upgrade specifies particular preference 10715 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10716 // Application explicitly specified internal. 10717 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10718 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10719 // App explictly prefers external. Let policy decide 10720 } else { 10721 // Prefer previous location 10722 if (isExternal(pkg)) { 10723 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10724 } 10725 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10726 } 10727 } 10728 } else { 10729 // Invalid install. Return error code 10730 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10731 } 10732 } 10733 } 10734 // All the special cases have been taken care of. 10735 // Return result based on recommended install location. 10736 if (onSd) { 10737 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10738 } 10739 return pkgLite.recommendedInstallLocation; 10740 } 10741 10742 /* 10743 * Invoke remote method to get package information and install 10744 * location values. Override install location based on default 10745 * policy if needed and then create install arguments based 10746 * on the install location. 10747 */ 10748 public void handleStartCopy() throws RemoteException { 10749 int ret = PackageManager.INSTALL_SUCCEEDED; 10750 10751 // If we're already staged, we've firmly committed to an install location 10752 if (origin.staged) { 10753 if (origin.file != null) { 10754 installFlags |= PackageManager.INSTALL_INTERNAL; 10755 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10756 } else if (origin.cid != null) { 10757 installFlags |= PackageManager.INSTALL_EXTERNAL; 10758 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10759 } else { 10760 throw new IllegalStateException("Invalid stage location"); 10761 } 10762 } 10763 10764 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10765 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10766 PackageInfoLite pkgLite = null; 10767 10768 if (onInt && onSd) { 10769 // Check if both bits are set. 10770 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10771 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10772 } else { 10773 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10774 packageAbiOverride); 10775 10776 /* 10777 * If we have too little free space, try to free cache 10778 * before giving up. 10779 */ 10780 if (!origin.staged && pkgLite.recommendedInstallLocation 10781 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10782 // TODO: focus freeing disk space on the target device 10783 final StorageManager storage = StorageManager.from(mContext); 10784 final long lowThreshold = storage.getStorageLowBytes( 10785 Environment.getDataDirectory()); 10786 10787 final long sizeBytes = mContainerService.calculateInstalledSize( 10788 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10789 10790 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10791 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10792 installFlags, packageAbiOverride); 10793 } 10794 10795 /* 10796 * The cache free must have deleted the file we 10797 * downloaded to install. 10798 * 10799 * TODO: fix the "freeCache" call to not delete 10800 * the file we care about. 10801 */ 10802 if (pkgLite.recommendedInstallLocation 10803 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10804 pkgLite.recommendedInstallLocation 10805 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10806 } 10807 } 10808 } 10809 10810 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10811 int loc = pkgLite.recommendedInstallLocation; 10812 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10813 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10814 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10815 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10816 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10817 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10818 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10819 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10820 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10821 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10822 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10823 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10824 } else { 10825 // Override with defaults if needed. 10826 loc = installLocationPolicy(pkgLite); 10827 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10828 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10829 } else if (!onSd && !onInt) { 10830 // Override install location with flags 10831 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10832 // Set the flag to install on external media. 10833 installFlags |= PackageManager.INSTALL_EXTERNAL; 10834 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10835 } else { 10836 // Make sure the flag for installing on external 10837 // media is unset 10838 installFlags |= PackageManager.INSTALL_INTERNAL; 10839 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10840 } 10841 } 10842 } 10843 } 10844 10845 final InstallArgs args = createInstallArgs(this); 10846 mArgs = args; 10847 10848 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10849 // TODO: http://b/22976637 10850 // Apps installed for "all" users use the device owner to verify the app 10851 UserHandle verifierUser = getUser(); 10852 if (verifierUser == UserHandle.ALL) { 10853 verifierUser = UserHandle.SYSTEM; 10854 } 10855 10856 /* 10857 * Determine if we have any installed package verifiers. If we 10858 * do, then we'll defer to them to verify the packages. 10859 */ 10860 final int requiredUid = mRequiredVerifierPackage == null ? -1 10861 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10862 if (!origin.existing && requiredUid != -1 10863 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10864 final Intent verification = new Intent( 10865 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10866 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10867 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10868 PACKAGE_MIME_TYPE); 10869 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10870 10871 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10872 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10873 verifierUser.getIdentifier()); 10874 10875 if (DEBUG_VERIFY) { 10876 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10877 + verification.toString() + " with " + pkgLite.verifiers.length 10878 + " optional verifiers"); 10879 } 10880 10881 final int verificationId = mPendingVerificationToken++; 10882 10883 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10884 10885 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10886 installerPackageName); 10887 10888 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10889 installFlags); 10890 10891 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10892 pkgLite.packageName); 10893 10894 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10895 pkgLite.versionCode); 10896 10897 if (verificationParams != null) { 10898 if (verificationParams.getVerificationURI() != null) { 10899 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10900 verificationParams.getVerificationURI()); 10901 } 10902 if (verificationParams.getOriginatingURI() != null) { 10903 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10904 verificationParams.getOriginatingURI()); 10905 } 10906 if (verificationParams.getReferrer() != null) { 10907 verification.putExtra(Intent.EXTRA_REFERRER, 10908 verificationParams.getReferrer()); 10909 } 10910 if (verificationParams.getOriginatingUid() >= 0) { 10911 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10912 verificationParams.getOriginatingUid()); 10913 } 10914 if (verificationParams.getInstallerUid() >= 0) { 10915 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10916 verificationParams.getInstallerUid()); 10917 } 10918 } 10919 10920 final PackageVerificationState verificationState = new PackageVerificationState( 10921 requiredUid, args); 10922 10923 mPendingVerification.append(verificationId, verificationState); 10924 10925 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10926 receivers, verificationState); 10927 10928 /* 10929 * If any sufficient verifiers were listed in the package 10930 * manifest, attempt to ask them. 10931 */ 10932 if (sufficientVerifiers != null) { 10933 final int N = sufficientVerifiers.size(); 10934 if (N == 0) { 10935 Slog.i(TAG, "Additional verifiers required, but none installed."); 10936 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10937 } else { 10938 for (int i = 0; i < N; i++) { 10939 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10940 10941 final Intent sufficientIntent = new Intent(verification); 10942 sufficientIntent.setComponent(verifierComponent); 10943 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10944 } 10945 } 10946 } 10947 10948 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10949 mRequiredVerifierPackage, receivers); 10950 if (ret == PackageManager.INSTALL_SUCCEEDED 10951 && mRequiredVerifierPackage != null) { 10952 Trace.asyncTraceBegin( 10953 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10954 /* 10955 * Send the intent to the required verification agent, 10956 * but only start the verification timeout after the 10957 * target BroadcastReceivers have run. 10958 */ 10959 verification.setComponent(requiredVerifierComponent); 10960 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10961 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10962 new BroadcastReceiver() { 10963 @Override 10964 public void onReceive(Context context, Intent intent) { 10965 final Message msg = mHandler 10966 .obtainMessage(CHECK_PENDING_VERIFICATION); 10967 msg.arg1 = verificationId; 10968 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10969 } 10970 }, null, 0, null, null); 10971 10972 /* 10973 * We don't want the copy to proceed until verification 10974 * succeeds, so null out this field. 10975 */ 10976 mArgs = null; 10977 } 10978 } else { 10979 /* 10980 * No package verification is enabled, so immediately start 10981 * the remote call to initiate copy using temporary file. 10982 */ 10983 ret = args.copyApk(mContainerService, true); 10984 } 10985 } 10986 10987 mRet = ret; 10988 } 10989 10990 @Override 10991 void handleReturnCode() { 10992 // If mArgs is null, then MCS couldn't be reached. When it 10993 // reconnects, it will try again to install. At that point, this 10994 // will succeed. 10995 if (mArgs != null) { 10996 processPendingInstall(mArgs, mRet); 10997 } 10998 } 10999 11000 @Override 11001 void handleServiceError() { 11002 mArgs = createInstallArgs(this); 11003 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11004 } 11005 11006 public boolean isForwardLocked() { 11007 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11008 } 11009 } 11010 11011 /** 11012 * Used during creation of InstallArgs 11013 * 11014 * @param installFlags package installation flags 11015 * @return true if should be installed on external storage 11016 */ 11017 private static boolean installOnExternalAsec(int installFlags) { 11018 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11019 return false; 11020 } 11021 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11022 return true; 11023 } 11024 return false; 11025 } 11026 11027 /** 11028 * Used during creation of InstallArgs 11029 * 11030 * @param installFlags package installation flags 11031 * @return true if should be installed as forward locked 11032 */ 11033 private static boolean installForwardLocked(int installFlags) { 11034 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11035 } 11036 11037 private InstallArgs createInstallArgs(InstallParams params) { 11038 if (params.move != null) { 11039 return new MoveInstallArgs(params); 11040 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11041 return new AsecInstallArgs(params); 11042 } else { 11043 return new FileInstallArgs(params); 11044 } 11045 } 11046 11047 /** 11048 * Create args that describe an existing installed package. Typically used 11049 * when cleaning up old installs, or used as a move source. 11050 */ 11051 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11052 String resourcePath, String[] instructionSets) { 11053 final boolean isInAsec; 11054 if (installOnExternalAsec(installFlags)) { 11055 /* Apps on SD card are always in ASEC containers. */ 11056 isInAsec = true; 11057 } else if (installForwardLocked(installFlags) 11058 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11059 /* 11060 * Forward-locked apps are only in ASEC containers if they're the 11061 * new style 11062 */ 11063 isInAsec = true; 11064 } else { 11065 isInAsec = false; 11066 } 11067 11068 if (isInAsec) { 11069 return new AsecInstallArgs(codePath, instructionSets, 11070 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11071 } else { 11072 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11073 } 11074 } 11075 11076 static abstract class InstallArgs { 11077 /** @see InstallParams#origin */ 11078 final OriginInfo origin; 11079 /** @see InstallParams#move */ 11080 final MoveInfo move; 11081 11082 final IPackageInstallObserver2 observer; 11083 // Always refers to PackageManager flags only 11084 final int installFlags; 11085 final String installerPackageName; 11086 final String volumeUuid; 11087 final ManifestDigest manifestDigest; 11088 final UserHandle user; 11089 final String abiOverride; 11090 final String[] installGrantPermissions; 11091 /** If non-null, drop an async trace when the install completes */ 11092 final String traceMethod; 11093 final int traceCookie; 11094 11095 // The list of instruction sets supported by this app. This is currently 11096 // only used during the rmdex() phase to clean up resources. We can get rid of this 11097 // if we move dex files under the common app path. 11098 /* nullable */ String[] instructionSets; 11099 11100 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11101 int installFlags, String installerPackageName, String volumeUuid, 11102 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11103 String abiOverride, String[] installGrantPermissions, 11104 String traceMethod, int traceCookie) { 11105 this.origin = origin; 11106 this.move = move; 11107 this.installFlags = installFlags; 11108 this.observer = observer; 11109 this.installerPackageName = installerPackageName; 11110 this.volumeUuid = volumeUuid; 11111 this.manifestDigest = manifestDigest; 11112 this.user = user; 11113 this.instructionSets = instructionSets; 11114 this.abiOverride = abiOverride; 11115 this.installGrantPermissions = installGrantPermissions; 11116 this.traceMethod = traceMethod; 11117 this.traceCookie = traceCookie; 11118 } 11119 11120 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11121 abstract int doPreInstall(int status); 11122 11123 /** 11124 * Rename package into final resting place. All paths on the given 11125 * scanned package should be updated to reflect the rename. 11126 */ 11127 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11128 abstract int doPostInstall(int status, int uid); 11129 11130 /** @see PackageSettingBase#codePathString */ 11131 abstract String getCodePath(); 11132 /** @see PackageSettingBase#resourcePathString */ 11133 abstract String getResourcePath(); 11134 11135 // Need installer lock especially for dex file removal. 11136 abstract void cleanUpResourcesLI(); 11137 abstract boolean doPostDeleteLI(boolean delete); 11138 11139 /** 11140 * Called before the source arguments are copied. This is used mostly 11141 * for MoveParams when it needs to read the source file to put it in the 11142 * destination. 11143 */ 11144 int doPreCopy() { 11145 return PackageManager.INSTALL_SUCCEEDED; 11146 } 11147 11148 /** 11149 * Called after the source arguments are copied. This is used mostly for 11150 * MoveParams when it needs to read the source file to put it in the 11151 * destination. 11152 * 11153 * @return 11154 */ 11155 int doPostCopy(int uid) { 11156 return PackageManager.INSTALL_SUCCEEDED; 11157 } 11158 11159 protected boolean isFwdLocked() { 11160 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11161 } 11162 11163 protected boolean isExternalAsec() { 11164 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11165 } 11166 11167 UserHandle getUser() { 11168 return user; 11169 } 11170 } 11171 11172 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11173 if (!allCodePaths.isEmpty()) { 11174 if (instructionSets == null) { 11175 throw new IllegalStateException("instructionSet == null"); 11176 } 11177 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11178 for (String codePath : allCodePaths) { 11179 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11180 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11181 if (retCode < 0) { 11182 Slog.w(TAG, "Couldn't remove dex file for package: " 11183 + " at location " + codePath + ", retcode=" + retCode); 11184 // we don't consider this to be a failure of the core package deletion 11185 } 11186 } 11187 } 11188 } 11189 } 11190 11191 /** 11192 * Logic to handle installation of non-ASEC applications, including copying 11193 * and renaming logic. 11194 */ 11195 class FileInstallArgs extends InstallArgs { 11196 private File codeFile; 11197 private File resourceFile; 11198 11199 // Example topology: 11200 // /data/app/com.example/base.apk 11201 // /data/app/com.example/split_foo.apk 11202 // /data/app/com.example/lib/arm/libfoo.so 11203 // /data/app/com.example/lib/arm64/libfoo.so 11204 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11205 11206 /** New install */ 11207 FileInstallArgs(InstallParams params) { 11208 super(params.origin, params.move, params.observer, params.installFlags, 11209 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11210 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11211 params.grantedRuntimePermissions, 11212 params.traceMethod, params.traceCookie); 11213 if (isFwdLocked()) { 11214 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11215 } 11216 } 11217 11218 /** Existing install */ 11219 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11220 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11221 null, null, null, 0); 11222 this.codeFile = (codePath != null) ? new File(codePath) : null; 11223 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11224 } 11225 11226 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11227 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11228 try { 11229 return doCopyApk(imcs, temp); 11230 } finally { 11231 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11232 } 11233 } 11234 11235 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11236 if (origin.staged) { 11237 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11238 codeFile = origin.file; 11239 resourceFile = origin.file; 11240 return PackageManager.INSTALL_SUCCEEDED; 11241 } 11242 11243 try { 11244 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11245 codeFile = tempDir; 11246 resourceFile = tempDir; 11247 } catch (IOException e) { 11248 Slog.w(TAG, "Failed to create copy file: " + e); 11249 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11250 } 11251 11252 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11253 @Override 11254 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11255 if (!FileUtils.isValidExtFilename(name)) { 11256 throw new IllegalArgumentException("Invalid filename: " + name); 11257 } 11258 try { 11259 final File file = new File(codeFile, name); 11260 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11261 O_RDWR | O_CREAT, 0644); 11262 Os.chmod(file.getAbsolutePath(), 0644); 11263 return new ParcelFileDescriptor(fd); 11264 } catch (ErrnoException e) { 11265 throw new RemoteException("Failed to open: " + e.getMessage()); 11266 } 11267 } 11268 }; 11269 11270 int ret = PackageManager.INSTALL_SUCCEEDED; 11271 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11272 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11273 Slog.e(TAG, "Failed to copy package"); 11274 return ret; 11275 } 11276 11277 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11278 NativeLibraryHelper.Handle handle = null; 11279 try { 11280 handle = NativeLibraryHelper.Handle.create(codeFile); 11281 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11282 abiOverride); 11283 } catch (IOException e) { 11284 Slog.e(TAG, "Copying native libraries failed", e); 11285 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11286 } finally { 11287 IoUtils.closeQuietly(handle); 11288 } 11289 11290 return ret; 11291 } 11292 11293 int doPreInstall(int status) { 11294 if (status != PackageManager.INSTALL_SUCCEEDED) { 11295 cleanUp(); 11296 } 11297 return status; 11298 } 11299 11300 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11301 if (status != PackageManager.INSTALL_SUCCEEDED) { 11302 cleanUp(); 11303 return false; 11304 } 11305 11306 final File targetDir = codeFile.getParentFile(); 11307 final File beforeCodeFile = codeFile; 11308 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11309 11310 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11311 try { 11312 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11313 } catch (ErrnoException e) { 11314 Slog.w(TAG, "Failed to rename", e); 11315 return false; 11316 } 11317 11318 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11319 Slog.w(TAG, "Failed to restorecon"); 11320 return false; 11321 } 11322 11323 // Reflect the rename internally 11324 codeFile = afterCodeFile; 11325 resourceFile = afterCodeFile; 11326 11327 // Reflect the rename in scanned details 11328 pkg.codePath = afterCodeFile.getAbsolutePath(); 11329 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11330 pkg.baseCodePath); 11331 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11332 pkg.splitCodePaths); 11333 11334 // Reflect the rename in app info 11335 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11336 pkg.applicationInfo.setCodePath(pkg.codePath); 11337 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11338 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11339 pkg.applicationInfo.setResourcePath(pkg.codePath); 11340 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11341 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11342 11343 return true; 11344 } 11345 11346 int doPostInstall(int status, int uid) { 11347 if (status != PackageManager.INSTALL_SUCCEEDED) { 11348 cleanUp(); 11349 } 11350 return status; 11351 } 11352 11353 @Override 11354 String getCodePath() { 11355 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11356 } 11357 11358 @Override 11359 String getResourcePath() { 11360 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11361 } 11362 11363 private boolean cleanUp() { 11364 if (codeFile == null || !codeFile.exists()) { 11365 return false; 11366 } 11367 11368 if (codeFile.isDirectory()) { 11369 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11370 } else { 11371 codeFile.delete(); 11372 } 11373 11374 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11375 resourceFile.delete(); 11376 } 11377 11378 return true; 11379 } 11380 11381 void cleanUpResourcesLI() { 11382 // Try enumerating all code paths before deleting 11383 List<String> allCodePaths = Collections.EMPTY_LIST; 11384 if (codeFile != null && codeFile.exists()) { 11385 try { 11386 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11387 allCodePaths = pkg.getAllCodePaths(); 11388 } catch (PackageParserException e) { 11389 // Ignored; we tried our best 11390 } 11391 } 11392 11393 cleanUp(); 11394 removeDexFiles(allCodePaths, instructionSets); 11395 } 11396 11397 boolean doPostDeleteLI(boolean delete) { 11398 // XXX err, shouldn't we respect the delete flag? 11399 cleanUpResourcesLI(); 11400 return true; 11401 } 11402 } 11403 11404 private boolean isAsecExternal(String cid) { 11405 final String asecPath = PackageHelper.getSdFilesystem(cid); 11406 return !asecPath.startsWith(mAsecInternalPath); 11407 } 11408 11409 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11410 PackageManagerException { 11411 if (copyRet < 0) { 11412 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11413 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11414 throw new PackageManagerException(copyRet, message); 11415 } 11416 } 11417 } 11418 11419 /** 11420 * Extract the MountService "container ID" from the full code path of an 11421 * .apk. 11422 */ 11423 static String cidFromCodePath(String fullCodePath) { 11424 int eidx = fullCodePath.lastIndexOf("/"); 11425 String subStr1 = fullCodePath.substring(0, eidx); 11426 int sidx = subStr1.lastIndexOf("/"); 11427 return subStr1.substring(sidx+1, eidx); 11428 } 11429 11430 /** 11431 * Logic to handle installation of ASEC applications, including copying and 11432 * renaming logic. 11433 */ 11434 class AsecInstallArgs extends InstallArgs { 11435 static final String RES_FILE_NAME = "pkg.apk"; 11436 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11437 11438 String cid; 11439 String packagePath; 11440 String resourcePath; 11441 11442 /** New install */ 11443 AsecInstallArgs(InstallParams params) { 11444 super(params.origin, params.move, params.observer, params.installFlags, 11445 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11446 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11447 params.grantedRuntimePermissions, 11448 params.traceMethod, params.traceCookie); 11449 } 11450 11451 /** Existing install */ 11452 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11453 boolean isExternal, boolean isForwardLocked) { 11454 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11455 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11456 instructionSets, null, null, null, 0); 11457 // Hackily pretend we're still looking at a full code path 11458 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11459 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11460 } 11461 11462 // Extract cid from fullCodePath 11463 int eidx = fullCodePath.lastIndexOf("/"); 11464 String subStr1 = fullCodePath.substring(0, eidx); 11465 int sidx = subStr1.lastIndexOf("/"); 11466 cid = subStr1.substring(sidx+1, eidx); 11467 setMountPath(subStr1); 11468 } 11469 11470 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11471 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11472 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11473 instructionSets, null, null, null, 0); 11474 this.cid = cid; 11475 setMountPath(PackageHelper.getSdDir(cid)); 11476 } 11477 11478 void createCopyFile() { 11479 cid = mInstallerService.allocateExternalStageCidLegacy(); 11480 } 11481 11482 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11483 if (origin.staged) { 11484 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11485 cid = origin.cid; 11486 setMountPath(PackageHelper.getSdDir(cid)); 11487 return PackageManager.INSTALL_SUCCEEDED; 11488 } 11489 11490 if (temp) { 11491 createCopyFile(); 11492 } else { 11493 /* 11494 * Pre-emptively destroy the container since it's destroyed if 11495 * copying fails due to it existing anyway. 11496 */ 11497 PackageHelper.destroySdDir(cid); 11498 } 11499 11500 final String newMountPath = imcs.copyPackageToContainer( 11501 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11502 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11503 11504 if (newMountPath != null) { 11505 setMountPath(newMountPath); 11506 return PackageManager.INSTALL_SUCCEEDED; 11507 } else { 11508 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11509 } 11510 } 11511 11512 @Override 11513 String getCodePath() { 11514 return packagePath; 11515 } 11516 11517 @Override 11518 String getResourcePath() { 11519 return resourcePath; 11520 } 11521 11522 int doPreInstall(int status) { 11523 if (status != PackageManager.INSTALL_SUCCEEDED) { 11524 // Destroy container 11525 PackageHelper.destroySdDir(cid); 11526 } else { 11527 boolean mounted = PackageHelper.isContainerMounted(cid); 11528 if (!mounted) { 11529 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11530 Process.SYSTEM_UID); 11531 if (newMountPath != null) { 11532 setMountPath(newMountPath); 11533 } else { 11534 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11535 } 11536 } 11537 } 11538 return status; 11539 } 11540 11541 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11542 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11543 String newMountPath = null; 11544 if (PackageHelper.isContainerMounted(cid)) { 11545 // Unmount the container 11546 if (!PackageHelper.unMountSdDir(cid)) { 11547 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11548 return false; 11549 } 11550 } 11551 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11552 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11553 " which might be stale. Will try to clean up."); 11554 // Clean up the stale container and proceed to recreate. 11555 if (!PackageHelper.destroySdDir(newCacheId)) { 11556 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11557 return false; 11558 } 11559 // Successfully cleaned up stale container. Try to rename again. 11560 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11561 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11562 + " inspite of cleaning it up."); 11563 return false; 11564 } 11565 } 11566 if (!PackageHelper.isContainerMounted(newCacheId)) { 11567 Slog.w(TAG, "Mounting container " + newCacheId); 11568 newMountPath = PackageHelper.mountSdDir(newCacheId, 11569 getEncryptKey(), Process.SYSTEM_UID); 11570 } else { 11571 newMountPath = PackageHelper.getSdDir(newCacheId); 11572 } 11573 if (newMountPath == null) { 11574 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11575 return false; 11576 } 11577 Log.i(TAG, "Succesfully renamed " + cid + 11578 " to " + newCacheId + 11579 " at new path: " + newMountPath); 11580 cid = newCacheId; 11581 11582 final File beforeCodeFile = new File(packagePath); 11583 setMountPath(newMountPath); 11584 final File afterCodeFile = new File(packagePath); 11585 11586 // Reflect the rename in scanned details 11587 pkg.codePath = afterCodeFile.getAbsolutePath(); 11588 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11589 pkg.baseCodePath); 11590 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11591 pkg.splitCodePaths); 11592 11593 // Reflect the rename in app info 11594 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11595 pkg.applicationInfo.setCodePath(pkg.codePath); 11596 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11597 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11598 pkg.applicationInfo.setResourcePath(pkg.codePath); 11599 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11600 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11601 11602 return true; 11603 } 11604 11605 private void setMountPath(String mountPath) { 11606 final File mountFile = new File(mountPath); 11607 11608 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11609 if (monolithicFile.exists()) { 11610 packagePath = monolithicFile.getAbsolutePath(); 11611 if (isFwdLocked()) { 11612 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11613 } else { 11614 resourcePath = packagePath; 11615 } 11616 } else { 11617 packagePath = mountFile.getAbsolutePath(); 11618 resourcePath = packagePath; 11619 } 11620 } 11621 11622 int doPostInstall(int status, int uid) { 11623 if (status != PackageManager.INSTALL_SUCCEEDED) { 11624 cleanUp(); 11625 } else { 11626 final int groupOwner; 11627 final String protectedFile; 11628 if (isFwdLocked()) { 11629 groupOwner = UserHandle.getSharedAppGid(uid); 11630 protectedFile = RES_FILE_NAME; 11631 } else { 11632 groupOwner = -1; 11633 protectedFile = null; 11634 } 11635 11636 if (uid < Process.FIRST_APPLICATION_UID 11637 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11638 Slog.e(TAG, "Failed to finalize " + cid); 11639 PackageHelper.destroySdDir(cid); 11640 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11641 } 11642 11643 boolean mounted = PackageHelper.isContainerMounted(cid); 11644 if (!mounted) { 11645 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11646 } 11647 } 11648 return status; 11649 } 11650 11651 private void cleanUp() { 11652 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11653 11654 // Destroy secure container 11655 PackageHelper.destroySdDir(cid); 11656 } 11657 11658 private List<String> getAllCodePaths() { 11659 final File codeFile = new File(getCodePath()); 11660 if (codeFile != null && codeFile.exists()) { 11661 try { 11662 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11663 return pkg.getAllCodePaths(); 11664 } catch (PackageParserException e) { 11665 // Ignored; we tried our best 11666 } 11667 } 11668 return Collections.EMPTY_LIST; 11669 } 11670 11671 void cleanUpResourcesLI() { 11672 // Enumerate all code paths before deleting 11673 cleanUpResourcesLI(getAllCodePaths()); 11674 } 11675 11676 private void cleanUpResourcesLI(List<String> allCodePaths) { 11677 cleanUp(); 11678 removeDexFiles(allCodePaths, instructionSets); 11679 } 11680 11681 String getPackageName() { 11682 return getAsecPackageName(cid); 11683 } 11684 11685 boolean doPostDeleteLI(boolean delete) { 11686 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11687 final List<String> allCodePaths = getAllCodePaths(); 11688 boolean mounted = PackageHelper.isContainerMounted(cid); 11689 if (mounted) { 11690 // Unmount first 11691 if (PackageHelper.unMountSdDir(cid)) { 11692 mounted = false; 11693 } 11694 } 11695 if (!mounted && delete) { 11696 cleanUpResourcesLI(allCodePaths); 11697 } 11698 return !mounted; 11699 } 11700 11701 @Override 11702 int doPreCopy() { 11703 if (isFwdLocked()) { 11704 if (!PackageHelper.fixSdPermissions(cid, 11705 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11706 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11707 } 11708 } 11709 11710 return PackageManager.INSTALL_SUCCEEDED; 11711 } 11712 11713 @Override 11714 int doPostCopy(int uid) { 11715 if (isFwdLocked()) { 11716 if (uid < Process.FIRST_APPLICATION_UID 11717 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11718 RES_FILE_NAME)) { 11719 Slog.e(TAG, "Failed to finalize " + cid); 11720 PackageHelper.destroySdDir(cid); 11721 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11722 } 11723 } 11724 11725 return PackageManager.INSTALL_SUCCEEDED; 11726 } 11727 } 11728 11729 /** 11730 * Logic to handle movement of existing installed applications. 11731 */ 11732 class MoveInstallArgs extends InstallArgs { 11733 private File codeFile; 11734 private File resourceFile; 11735 11736 /** New install */ 11737 MoveInstallArgs(InstallParams params) { 11738 super(params.origin, params.move, params.observer, params.installFlags, 11739 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11740 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11741 params.grantedRuntimePermissions, 11742 params.traceMethod, params.traceCookie); 11743 } 11744 11745 int copyApk(IMediaContainerService imcs, boolean temp) { 11746 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11747 + move.fromUuid + " to " + move.toUuid); 11748 synchronized (mInstaller) { 11749 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11750 move.dataAppName, move.appId, move.seinfo) != 0) { 11751 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11752 } 11753 } 11754 11755 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11756 resourceFile = codeFile; 11757 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11758 11759 return PackageManager.INSTALL_SUCCEEDED; 11760 } 11761 11762 int doPreInstall(int status) { 11763 if (status != PackageManager.INSTALL_SUCCEEDED) { 11764 cleanUp(move.toUuid); 11765 } 11766 return status; 11767 } 11768 11769 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11770 if (status != PackageManager.INSTALL_SUCCEEDED) { 11771 cleanUp(move.toUuid); 11772 return false; 11773 } 11774 11775 // Reflect the move in app info 11776 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11777 pkg.applicationInfo.setCodePath(pkg.codePath); 11778 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11779 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11780 pkg.applicationInfo.setResourcePath(pkg.codePath); 11781 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11782 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11783 11784 return true; 11785 } 11786 11787 int doPostInstall(int status, int uid) { 11788 if (status == PackageManager.INSTALL_SUCCEEDED) { 11789 cleanUp(move.fromUuid); 11790 } else { 11791 cleanUp(move.toUuid); 11792 } 11793 return status; 11794 } 11795 11796 @Override 11797 String getCodePath() { 11798 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11799 } 11800 11801 @Override 11802 String getResourcePath() { 11803 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11804 } 11805 11806 private boolean cleanUp(String volumeUuid) { 11807 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11808 move.dataAppName); 11809 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11810 synchronized (mInstallLock) { 11811 // Clean up both app data and code 11812 removeDataDirsLI(volumeUuid, move.packageName); 11813 if (codeFile.isDirectory()) { 11814 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11815 } else { 11816 codeFile.delete(); 11817 } 11818 } 11819 return true; 11820 } 11821 11822 void cleanUpResourcesLI() { 11823 throw new UnsupportedOperationException(); 11824 } 11825 11826 boolean doPostDeleteLI(boolean delete) { 11827 throw new UnsupportedOperationException(); 11828 } 11829 } 11830 11831 static String getAsecPackageName(String packageCid) { 11832 int idx = packageCid.lastIndexOf("-"); 11833 if (idx == -1) { 11834 return packageCid; 11835 } 11836 return packageCid.substring(0, idx); 11837 } 11838 11839 // Utility method used to create code paths based on package name and available index. 11840 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11841 String idxStr = ""; 11842 int idx = 1; 11843 // Fall back to default value of idx=1 if prefix is not 11844 // part of oldCodePath 11845 if (oldCodePath != null) { 11846 String subStr = oldCodePath; 11847 // Drop the suffix right away 11848 if (suffix != null && subStr.endsWith(suffix)) { 11849 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11850 } 11851 // If oldCodePath already contains prefix find out the 11852 // ending index to either increment or decrement. 11853 int sidx = subStr.lastIndexOf(prefix); 11854 if (sidx != -1) { 11855 subStr = subStr.substring(sidx + prefix.length()); 11856 if (subStr != null) { 11857 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11858 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11859 } 11860 try { 11861 idx = Integer.parseInt(subStr); 11862 if (idx <= 1) { 11863 idx++; 11864 } else { 11865 idx--; 11866 } 11867 } catch(NumberFormatException e) { 11868 } 11869 } 11870 } 11871 } 11872 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11873 return prefix + idxStr; 11874 } 11875 11876 private File getNextCodePath(File targetDir, String packageName) { 11877 int suffix = 1; 11878 File result; 11879 do { 11880 result = new File(targetDir, packageName + "-" + suffix); 11881 suffix++; 11882 } while (result.exists()); 11883 return result; 11884 } 11885 11886 // Utility method that returns the relative package path with respect 11887 // to the installation directory. Like say for /data/data/com.test-1.apk 11888 // string com.test-1 is returned. 11889 static String deriveCodePathName(String codePath) { 11890 if (codePath == null) { 11891 return null; 11892 } 11893 final File codeFile = new File(codePath); 11894 final String name = codeFile.getName(); 11895 if (codeFile.isDirectory()) { 11896 return name; 11897 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11898 final int lastDot = name.lastIndexOf('.'); 11899 return name.substring(0, lastDot); 11900 } else { 11901 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11902 return null; 11903 } 11904 } 11905 11906 class PackageInstalledInfo { 11907 String name; 11908 int uid; 11909 // The set of users that originally had this package installed. 11910 int[] origUsers; 11911 // The set of users that now have this package installed. 11912 int[] newUsers; 11913 PackageParser.Package pkg; 11914 int returnCode; 11915 String returnMsg; 11916 PackageRemovedInfo removedInfo; 11917 11918 public void setError(int code, String msg) { 11919 returnCode = code; 11920 returnMsg = msg; 11921 Slog.w(TAG, msg); 11922 } 11923 11924 public void setError(String msg, PackageParserException e) { 11925 returnCode = e.error; 11926 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11927 Slog.w(TAG, msg, e); 11928 } 11929 11930 public void setError(String msg, PackageManagerException e) { 11931 returnCode = e.error; 11932 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11933 Slog.w(TAG, msg, e); 11934 } 11935 11936 // In some error cases we want to convey more info back to the observer 11937 String origPackage; 11938 String origPermission; 11939 } 11940 11941 /* 11942 * Install a non-existing package. 11943 */ 11944 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11945 UserHandle user, String installerPackageName, String volumeUuid, 11946 PackageInstalledInfo res) { 11947 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11948 11949 // Remember this for later, in case we need to rollback this install 11950 String pkgName = pkg.packageName; 11951 11952 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11953 // TODO: b/23350563 11954 final boolean dataDirExists = Environment 11955 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11956 11957 synchronized(mPackages) { 11958 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11959 // A package with the same name is already installed, though 11960 // it has been renamed to an older name. The package we 11961 // are trying to install should be installed as an update to 11962 // the existing one, but that has not been requested, so bail. 11963 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11964 + " without first uninstalling package running as " 11965 + mSettings.mRenamedPackages.get(pkgName)); 11966 return; 11967 } 11968 if (mPackages.containsKey(pkgName)) { 11969 // Don't allow installation over an existing package with the same name. 11970 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11971 + " without first uninstalling."); 11972 return; 11973 } 11974 } 11975 11976 try { 11977 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11978 System.currentTimeMillis(), user); 11979 11980 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11981 // delete the partially installed application. the data directory will have to be 11982 // restored if it was already existing 11983 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11984 // remove package from internal structures. Note that we want deletePackageX to 11985 // delete the package data and cache directories that it created in 11986 // scanPackageLocked, unless those directories existed before we even tried to 11987 // install. 11988 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11989 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11990 res.removedInfo, true); 11991 } 11992 11993 } catch (PackageManagerException e) { 11994 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11995 } 11996 11997 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11998 } 11999 12000 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12001 // Can't rotate keys during boot or if sharedUser. 12002 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12003 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12004 return false; 12005 } 12006 // app is using upgradeKeySets; make sure all are valid 12007 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12008 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12009 for (int i = 0; i < upgradeKeySets.length; i++) { 12010 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12011 Slog.wtf(TAG, "Package " 12012 + (oldPs.name != null ? oldPs.name : "<null>") 12013 + " contains upgrade-key-set reference to unknown key-set: " 12014 + upgradeKeySets[i] 12015 + " reverting to signatures check."); 12016 return false; 12017 } 12018 } 12019 return true; 12020 } 12021 12022 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12023 // Upgrade keysets are being used. Determine if new package has a superset of the 12024 // required keys. 12025 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12026 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12027 for (int i = 0; i < upgradeKeySets.length; i++) { 12028 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12029 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12030 return true; 12031 } 12032 } 12033 return false; 12034 } 12035 12036 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12037 UserHandle user, String installerPackageName, String volumeUuid, 12038 PackageInstalledInfo res) { 12039 final PackageParser.Package oldPackage; 12040 final String pkgName = pkg.packageName; 12041 final int[] allUsers; 12042 final boolean[] perUserInstalled; 12043 12044 // First find the old package info and check signatures 12045 synchronized(mPackages) { 12046 oldPackage = mPackages.get(pkgName); 12047 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12048 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12049 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12050 if(!checkUpgradeKeySetLP(ps, pkg)) { 12051 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12052 "New package not signed by keys specified by upgrade-keysets: " 12053 + pkgName); 12054 return; 12055 } 12056 } else { 12057 // default to original signature matching 12058 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12059 != PackageManager.SIGNATURE_MATCH) { 12060 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12061 "New package has a different signature: " + pkgName); 12062 return; 12063 } 12064 } 12065 12066 // In case of rollback, remember per-user/profile install state 12067 allUsers = sUserManager.getUserIds(); 12068 perUserInstalled = new boolean[allUsers.length]; 12069 for (int i = 0; i < allUsers.length; i++) { 12070 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12071 } 12072 } 12073 12074 boolean sysPkg = (isSystemApp(oldPackage)); 12075 if (sysPkg) { 12076 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12077 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12078 } else { 12079 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12080 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12081 } 12082 } 12083 12084 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12085 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12086 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12087 String volumeUuid, PackageInstalledInfo res) { 12088 String pkgName = deletedPackage.packageName; 12089 boolean deletedPkg = true; 12090 boolean updatedSettings = false; 12091 12092 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12093 + deletedPackage); 12094 long origUpdateTime; 12095 if (pkg.mExtras != null) { 12096 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12097 } else { 12098 origUpdateTime = 0; 12099 } 12100 12101 // First delete the existing package while retaining the data directory 12102 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12103 res.removedInfo, true)) { 12104 // If the existing package wasn't successfully deleted 12105 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12106 deletedPkg = false; 12107 } else { 12108 // Successfully deleted the old package; proceed with replace. 12109 12110 // If deleted package lived in a container, give users a chance to 12111 // relinquish resources before killing. 12112 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12113 if (DEBUG_INSTALL) { 12114 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12115 } 12116 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12117 final ArrayList<String> pkgList = new ArrayList<String>(1); 12118 pkgList.add(deletedPackage.applicationInfo.packageName); 12119 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12120 } 12121 12122 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12123 try { 12124 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12125 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12126 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12127 perUserInstalled, res, user); 12128 updatedSettings = true; 12129 } catch (PackageManagerException e) { 12130 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12131 } 12132 } 12133 12134 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12135 // remove package from internal structures. Note that we want deletePackageX to 12136 // delete the package data and cache directories that it created in 12137 // scanPackageLocked, unless those directories existed before we even tried to 12138 // install. 12139 if(updatedSettings) { 12140 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12141 deletePackageLI( 12142 pkgName, null, true, allUsers, perUserInstalled, 12143 PackageManager.DELETE_KEEP_DATA, 12144 res.removedInfo, true); 12145 } 12146 // Since we failed to install the new package we need to restore the old 12147 // package that we deleted. 12148 if (deletedPkg) { 12149 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12150 File restoreFile = new File(deletedPackage.codePath); 12151 // Parse old package 12152 boolean oldExternal = isExternal(deletedPackage); 12153 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12154 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12155 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12156 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12157 try { 12158 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12159 null); 12160 } catch (PackageManagerException e) { 12161 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12162 + e.getMessage()); 12163 return; 12164 } 12165 // Restore of old package succeeded. Update permissions. 12166 // writer 12167 synchronized (mPackages) { 12168 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12169 UPDATE_PERMISSIONS_ALL); 12170 // can downgrade to reader 12171 mSettings.writeLPr(); 12172 } 12173 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12174 } 12175 } 12176 } 12177 12178 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12179 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12180 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12181 String volumeUuid, PackageInstalledInfo res) { 12182 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12183 + ", old=" + deletedPackage); 12184 boolean disabledSystem = false; 12185 boolean updatedSettings = false; 12186 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12187 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12188 != 0) { 12189 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12190 } 12191 String packageName = deletedPackage.packageName; 12192 if (packageName == null) { 12193 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12194 "Attempt to delete null packageName."); 12195 return; 12196 } 12197 PackageParser.Package oldPkg; 12198 PackageSetting oldPkgSetting; 12199 // reader 12200 synchronized (mPackages) { 12201 oldPkg = mPackages.get(packageName); 12202 oldPkgSetting = mSettings.mPackages.get(packageName); 12203 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12204 (oldPkgSetting == null)) { 12205 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12206 "Couldn't find package:" + packageName + " information"); 12207 return; 12208 } 12209 } 12210 12211 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12212 12213 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12214 res.removedInfo.removedPackage = packageName; 12215 // Remove existing system package 12216 removePackageLI(oldPkgSetting, true); 12217 // writer 12218 synchronized (mPackages) { 12219 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12220 if (!disabledSystem && deletedPackage != null) { 12221 // We didn't need to disable the .apk as a current system package, 12222 // which means we are replacing another update that is already 12223 // installed. We need to make sure to delete the older one's .apk. 12224 res.removedInfo.args = createInstallArgsForExisting(0, 12225 deletedPackage.applicationInfo.getCodePath(), 12226 deletedPackage.applicationInfo.getResourcePath(), 12227 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12228 } else { 12229 res.removedInfo.args = null; 12230 } 12231 } 12232 12233 // Successfully disabled the old package. Now proceed with re-installation 12234 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12235 12236 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12237 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12238 12239 PackageParser.Package newPackage = null; 12240 try { 12241 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12242 if (newPackage.mExtras != null) { 12243 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12244 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12245 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12246 12247 // is the update attempting to change shared user? that isn't going to work... 12248 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12249 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12250 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12251 + " to " + newPkgSetting.sharedUser); 12252 updatedSettings = true; 12253 } 12254 } 12255 12256 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12257 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12258 perUserInstalled, res, user); 12259 updatedSettings = true; 12260 } 12261 12262 } catch (PackageManagerException e) { 12263 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12264 } 12265 12266 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12267 // Re installation failed. Restore old information 12268 // Remove new pkg information 12269 if (newPackage != null) { 12270 removeInstalledPackageLI(newPackage, true); 12271 } 12272 // Add back the old system package 12273 try { 12274 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12275 } catch (PackageManagerException e) { 12276 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12277 } 12278 // Restore the old system information in Settings 12279 synchronized (mPackages) { 12280 if (disabledSystem) { 12281 mSettings.enableSystemPackageLPw(packageName); 12282 } 12283 if (updatedSettings) { 12284 mSettings.setInstallerPackageName(packageName, 12285 oldPkgSetting.installerPackageName); 12286 } 12287 mSettings.writeLPr(); 12288 } 12289 } 12290 } 12291 12292 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12293 // Collect all used permissions in the UID 12294 ArraySet<String> usedPermissions = new ArraySet<>(); 12295 final int packageCount = su.packages.size(); 12296 for (int i = 0; i < packageCount; i++) { 12297 PackageSetting ps = su.packages.valueAt(i); 12298 if (ps.pkg == null) { 12299 continue; 12300 } 12301 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12302 for (int j = 0; j < requestedPermCount; j++) { 12303 String permission = ps.pkg.requestedPermissions.get(j); 12304 BasePermission bp = mSettings.mPermissions.get(permission); 12305 if (bp != null) { 12306 usedPermissions.add(permission); 12307 } 12308 } 12309 } 12310 12311 PermissionsState permissionsState = su.getPermissionsState(); 12312 // Prune install permissions 12313 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12314 final int installPermCount = installPermStates.size(); 12315 for (int i = installPermCount - 1; i >= 0; i--) { 12316 PermissionState permissionState = installPermStates.get(i); 12317 if (!usedPermissions.contains(permissionState.getName())) { 12318 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12319 if (bp != null) { 12320 permissionsState.revokeInstallPermission(bp); 12321 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12322 PackageManager.MASK_PERMISSION_FLAGS, 0); 12323 } 12324 } 12325 } 12326 12327 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12328 12329 // Prune runtime permissions 12330 for (int userId : allUserIds) { 12331 List<PermissionState> runtimePermStates = permissionsState 12332 .getRuntimePermissionStates(userId); 12333 final int runtimePermCount = runtimePermStates.size(); 12334 for (int i = runtimePermCount - 1; i >= 0; i--) { 12335 PermissionState permissionState = runtimePermStates.get(i); 12336 if (!usedPermissions.contains(permissionState.getName())) { 12337 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12338 if (bp != null) { 12339 permissionsState.revokeRuntimePermission(bp, userId); 12340 permissionsState.updatePermissionFlags(bp, userId, 12341 PackageManager.MASK_PERMISSION_FLAGS, 0); 12342 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12343 runtimePermissionChangedUserIds, userId); 12344 } 12345 } 12346 } 12347 } 12348 12349 return runtimePermissionChangedUserIds; 12350 } 12351 12352 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12353 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12354 UserHandle user) { 12355 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12356 12357 String pkgName = newPackage.packageName; 12358 synchronized (mPackages) { 12359 //write settings. the installStatus will be incomplete at this stage. 12360 //note that the new package setting would have already been 12361 //added to mPackages. It hasn't been persisted yet. 12362 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12363 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12364 mSettings.writeLPr(); 12365 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12366 } 12367 12368 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12369 synchronized (mPackages) { 12370 updatePermissionsLPw(newPackage.packageName, newPackage, 12371 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12372 ? UPDATE_PERMISSIONS_ALL : 0)); 12373 // For system-bundled packages, we assume that installing an upgraded version 12374 // of the package implies that the user actually wants to run that new code, 12375 // so we enable the package. 12376 PackageSetting ps = mSettings.mPackages.get(pkgName); 12377 if (ps != null) { 12378 if (isSystemApp(newPackage)) { 12379 // NB: implicit assumption that system package upgrades apply to all users 12380 if (DEBUG_INSTALL) { 12381 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12382 } 12383 if (res.origUsers != null) { 12384 for (int userHandle : res.origUsers) { 12385 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12386 userHandle, installerPackageName); 12387 } 12388 } 12389 // Also convey the prior install/uninstall state 12390 if (allUsers != null && perUserInstalled != null) { 12391 for (int i = 0; i < allUsers.length; i++) { 12392 if (DEBUG_INSTALL) { 12393 Slog.d(TAG, " user " + allUsers[i] 12394 + " => " + perUserInstalled[i]); 12395 } 12396 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12397 } 12398 // these install state changes will be persisted in the 12399 // upcoming call to mSettings.writeLPr(). 12400 } 12401 } 12402 // It's implied that when a user requests installation, they want the app to be 12403 // installed and enabled. 12404 int userId = user.getIdentifier(); 12405 if (userId != UserHandle.USER_ALL) { 12406 ps.setInstalled(true, userId); 12407 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12408 } 12409 } 12410 res.name = pkgName; 12411 res.uid = newPackage.applicationInfo.uid; 12412 res.pkg = newPackage; 12413 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12414 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12415 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12416 //to update install status 12417 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12418 mSettings.writeLPr(); 12419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12420 } 12421 12422 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12423 } 12424 12425 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12426 try { 12427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12428 installPackageLI(args, res); 12429 } finally { 12430 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12431 } 12432 } 12433 12434 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12435 final int installFlags = args.installFlags; 12436 final String installerPackageName = args.installerPackageName; 12437 final String volumeUuid = args.volumeUuid; 12438 final File tmpPackageFile = new File(args.getCodePath()); 12439 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12440 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12441 || (args.volumeUuid != null)); 12442 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12443 boolean replace = false; 12444 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12445 if (args.move != null) { 12446 // moving a complete application; perfom an initial scan on the new install location 12447 scanFlags |= SCAN_INITIAL; 12448 } 12449 // Result object to be returned 12450 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12451 12452 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12453 12454 // Retrieve PackageSettings and parse package 12455 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12456 | PackageParser.PARSE_ENFORCE_CODE 12457 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12458 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12459 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12460 PackageParser pp = new PackageParser(); 12461 pp.setSeparateProcesses(mSeparateProcesses); 12462 pp.setDisplayMetrics(mMetrics); 12463 12464 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12465 final PackageParser.Package pkg; 12466 try { 12467 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12468 } catch (PackageParserException e) { 12469 res.setError("Failed parse during installPackageLI", e); 12470 return; 12471 } finally { 12472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12473 } 12474 12475 // Mark that we have an install time CPU ABI override. 12476 pkg.cpuAbiOverride = args.abiOverride; 12477 12478 String pkgName = res.name = pkg.packageName; 12479 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12480 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12481 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12482 return; 12483 } 12484 } 12485 12486 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12487 try { 12488 pp.collectCertificates(pkg, parseFlags); 12489 } catch (PackageParserException e) { 12490 res.setError("Failed collect during installPackageLI", e); 12491 return; 12492 } finally { 12493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12494 } 12495 12496 /* If the installer passed in a manifest digest, compare it now. */ 12497 if (args.manifestDigest != null) { 12498 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12499 try { 12500 pp.collectManifestDigest(pkg); 12501 } catch (PackageParserException e) { 12502 res.setError("Failed collect during installPackageLI", e); 12503 return; 12504 } finally { 12505 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12506 } 12507 12508 if (DEBUG_INSTALL) { 12509 final String parsedManifest = pkg.manifestDigest == null ? "null" 12510 : pkg.manifestDigest.toString(); 12511 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12512 + parsedManifest); 12513 } 12514 12515 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12516 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12517 return; 12518 } 12519 } else if (DEBUG_INSTALL) { 12520 final String parsedManifest = pkg.manifestDigest == null 12521 ? "null" : pkg.manifestDigest.toString(); 12522 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12523 } 12524 12525 // Get rid of all references to package scan path via parser. 12526 pp = null; 12527 String oldCodePath = null; 12528 boolean systemApp = false; 12529 synchronized (mPackages) { 12530 // Check if installing already existing package 12531 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12532 String oldName = mSettings.mRenamedPackages.get(pkgName); 12533 if (pkg.mOriginalPackages != null 12534 && pkg.mOriginalPackages.contains(oldName) 12535 && mPackages.containsKey(oldName)) { 12536 // This package is derived from an original package, 12537 // and this device has been updating from that original 12538 // name. We must continue using the original name, so 12539 // rename the new package here. 12540 pkg.setPackageName(oldName); 12541 pkgName = pkg.packageName; 12542 replace = true; 12543 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12544 + oldName + " pkgName=" + pkgName); 12545 } else if (mPackages.containsKey(pkgName)) { 12546 // This package, under its official name, already exists 12547 // on the device; we should replace it. 12548 replace = true; 12549 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12550 } 12551 12552 // Prevent apps opting out from runtime permissions 12553 if (replace) { 12554 PackageParser.Package oldPackage = mPackages.get(pkgName); 12555 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12556 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12557 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12558 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12559 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12560 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12561 + " doesn't support runtime permissions but the old" 12562 + " target SDK " + oldTargetSdk + " does."); 12563 return; 12564 } 12565 } 12566 } 12567 12568 PackageSetting ps = mSettings.mPackages.get(pkgName); 12569 if (ps != null) { 12570 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12571 12572 // Quick sanity check that we're signed correctly if updating; 12573 // we'll check this again later when scanning, but we want to 12574 // bail early here before tripping over redefined permissions. 12575 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12576 if (!checkUpgradeKeySetLP(ps, pkg)) { 12577 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12578 + pkg.packageName + " upgrade keys do not match the " 12579 + "previously installed version"); 12580 return; 12581 } 12582 } else { 12583 try { 12584 verifySignaturesLP(ps, pkg); 12585 } catch (PackageManagerException e) { 12586 res.setError(e.error, e.getMessage()); 12587 return; 12588 } 12589 } 12590 12591 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12592 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12593 systemApp = (ps.pkg.applicationInfo.flags & 12594 ApplicationInfo.FLAG_SYSTEM) != 0; 12595 } 12596 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12597 } 12598 12599 // Check whether the newly-scanned package wants to define an already-defined perm 12600 int N = pkg.permissions.size(); 12601 for (int i = N-1; i >= 0; i--) { 12602 PackageParser.Permission perm = pkg.permissions.get(i); 12603 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12604 if (bp != null) { 12605 // If the defining package is signed with our cert, it's okay. This 12606 // also includes the "updating the same package" case, of course. 12607 // "updating same package" could also involve key-rotation. 12608 final boolean sigsOk; 12609 if (bp.sourcePackage.equals(pkg.packageName) 12610 && (bp.packageSetting instanceof PackageSetting) 12611 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12612 scanFlags))) { 12613 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12614 } else { 12615 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12616 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12617 } 12618 if (!sigsOk) { 12619 // If the owning package is the system itself, we log but allow 12620 // install to proceed; we fail the install on all other permission 12621 // redefinitions. 12622 if (!bp.sourcePackage.equals("android")) { 12623 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12624 + pkg.packageName + " attempting to redeclare permission " 12625 + perm.info.name + " already owned by " + bp.sourcePackage); 12626 res.origPermission = perm.info.name; 12627 res.origPackage = bp.sourcePackage; 12628 return; 12629 } else { 12630 Slog.w(TAG, "Package " + pkg.packageName 12631 + " attempting to redeclare system permission " 12632 + perm.info.name + "; ignoring new declaration"); 12633 pkg.permissions.remove(i); 12634 } 12635 } 12636 } 12637 } 12638 12639 } 12640 12641 if (systemApp && onExternal) { 12642 // Disable updates to system apps on sdcard 12643 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12644 "Cannot install updates to system apps on sdcard"); 12645 return; 12646 } 12647 12648 if (args.move != null) { 12649 // We did an in-place move, so dex is ready to roll 12650 scanFlags |= SCAN_NO_DEX; 12651 scanFlags |= SCAN_MOVE; 12652 12653 synchronized (mPackages) { 12654 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12655 if (ps == null) { 12656 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12657 "Missing settings for moved package " + pkgName); 12658 } 12659 12660 // We moved the entire application as-is, so bring over the 12661 // previously derived ABI information. 12662 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12663 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12664 } 12665 12666 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12667 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12668 scanFlags |= SCAN_NO_DEX; 12669 12670 try { 12671 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12672 true /* extract libs */); 12673 } catch (PackageManagerException pme) { 12674 Slog.e(TAG, "Error deriving application ABI", pme); 12675 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12676 return; 12677 } 12678 12679 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12680 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12681 12682 int result = mPackageDexOptimizer 12683 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12684 false /* defer */, false /* inclDependencies */, 12685 true /*bootComplete*/, quickInstall /*useJit*/); 12686 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12687 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12688 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12689 return; 12690 } 12691 } 12692 12693 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12694 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12695 return; 12696 } 12697 12698 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12699 12700 if (replace) { 12701 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12702 installerPackageName, volumeUuid, res); 12703 } else { 12704 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12705 args.user, installerPackageName, volumeUuid, res); 12706 } 12707 synchronized (mPackages) { 12708 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12709 if (ps != null) { 12710 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12711 } 12712 } 12713 } 12714 12715 private void startIntentFilterVerifications(int userId, boolean replacing, 12716 PackageParser.Package pkg) { 12717 if (mIntentFilterVerifierComponent == null) { 12718 Slog.w(TAG, "No IntentFilter verification will not be done as " 12719 + "there is no IntentFilterVerifier available!"); 12720 return; 12721 } 12722 12723 final int verifierUid = getPackageUid( 12724 mIntentFilterVerifierComponent.getPackageName(), 12725 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12726 12727 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12728 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12729 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12730 mHandler.sendMessage(msg); 12731 } 12732 12733 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12734 PackageParser.Package pkg) { 12735 int size = pkg.activities.size(); 12736 if (size == 0) { 12737 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12738 "No activity, so no need to verify any IntentFilter!"); 12739 return; 12740 } 12741 12742 final boolean hasDomainURLs = hasDomainURLs(pkg); 12743 if (!hasDomainURLs) { 12744 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12745 "No domain URLs, so no need to verify any IntentFilter!"); 12746 return; 12747 } 12748 12749 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12750 + " if any IntentFilter from the " + size 12751 + " Activities needs verification ..."); 12752 12753 int count = 0; 12754 final String packageName = pkg.packageName; 12755 12756 synchronized (mPackages) { 12757 // If this is a new install and we see that we've already run verification for this 12758 // package, we have nothing to do: it means the state was restored from backup. 12759 if (!replacing) { 12760 IntentFilterVerificationInfo ivi = 12761 mSettings.getIntentFilterVerificationLPr(packageName); 12762 if (ivi != null) { 12763 if (DEBUG_DOMAIN_VERIFICATION) { 12764 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12765 + ivi.getStatusString()); 12766 } 12767 return; 12768 } 12769 } 12770 12771 // If any filters need to be verified, then all need to be. 12772 boolean needToVerify = false; 12773 for (PackageParser.Activity a : pkg.activities) { 12774 for (ActivityIntentInfo filter : a.intents) { 12775 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12776 if (DEBUG_DOMAIN_VERIFICATION) { 12777 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12778 } 12779 needToVerify = true; 12780 break; 12781 } 12782 } 12783 } 12784 12785 if (needToVerify) { 12786 final int verificationId = mIntentFilterVerificationToken++; 12787 for (PackageParser.Activity a : pkg.activities) { 12788 for (ActivityIntentInfo filter : a.intents) { 12789 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12790 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12791 "Verification needed for IntentFilter:" + filter.toString()); 12792 mIntentFilterVerifier.addOneIntentFilterVerification( 12793 verifierUid, userId, verificationId, filter, packageName); 12794 count++; 12795 } 12796 } 12797 } 12798 } 12799 } 12800 12801 if (count > 0) { 12802 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12803 + " IntentFilter verification" + (count > 1 ? "s" : "") 12804 + " for userId:" + userId); 12805 mIntentFilterVerifier.startVerifications(userId); 12806 } else { 12807 if (DEBUG_DOMAIN_VERIFICATION) { 12808 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12809 } 12810 } 12811 } 12812 12813 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12814 final ComponentName cn = filter.activity.getComponentName(); 12815 final String packageName = cn.getPackageName(); 12816 12817 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12818 packageName); 12819 if (ivi == null) { 12820 return true; 12821 } 12822 int status = ivi.getStatus(); 12823 switch (status) { 12824 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12825 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12826 return true; 12827 12828 default: 12829 // Nothing to do 12830 return false; 12831 } 12832 } 12833 12834 private static boolean isMultiArch(PackageSetting ps) { 12835 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12836 } 12837 12838 private static boolean isMultiArch(ApplicationInfo info) { 12839 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12840 } 12841 12842 private static boolean isExternal(PackageParser.Package pkg) { 12843 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12844 } 12845 12846 private static boolean isExternal(PackageSetting ps) { 12847 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12848 } 12849 12850 private static boolean isExternal(ApplicationInfo info) { 12851 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12852 } 12853 12854 private static boolean isSystemApp(PackageParser.Package pkg) { 12855 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12856 } 12857 12858 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12859 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12860 } 12861 12862 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12863 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12864 } 12865 12866 private static boolean isSystemApp(PackageSetting ps) { 12867 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12868 } 12869 12870 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12871 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12872 } 12873 12874 private int packageFlagsToInstallFlags(PackageSetting ps) { 12875 int installFlags = 0; 12876 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12877 // This existing package was an external ASEC install when we have 12878 // the external flag without a UUID 12879 installFlags |= PackageManager.INSTALL_EXTERNAL; 12880 } 12881 if (ps.isForwardLocked()) { 12882 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12883 } 12884 return installFlags; 12885 } 12886 12887 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12888 if (isExternal(pkg)) { 12889 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12890 return StorageManager.UUID_PRIMARY_PHYSICAL; 12891 } else { 12892 return pkg.volumeUuid; 12893 } 12894 } else { 12895 return StorageManager.UUID_PRIVATE_INTERNAL; 12896 } 12897 } 12898 12899 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12900 if (isExternal(pkg)) { 12901 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12902 return mSettings.getExternalVersion(); 12903 } else { 12904 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12905 } 12906 } else { 12907 return mSettings.getInternalVersion(); 12908 } 12909 } 12910 12911 private void deleteTempPackageFiles() { 12912 final FilenameFilter filter = new FilenameFilter() { 12913 public boolean accept(File dir, String name) { 12914 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12915 } 12916 }; 12917 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12918 file.delete(); 12919 } 12920 } 12921 12922 @Override 12923 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12924 int flags) { 12925 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12926 flags); 12927 } 12928 12929 @Override 12930 public void deletePackage(final String packageName, 12931 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12932 mContext.enforceCallingOrSelfPermission( 12933 android.Manifest.permission.DELETE_PACKAGES, null); 12934 Preconditions.checkNotNull(packageName); 12935 Preconditions.checkNotNull(observer); 12936 final int uid = Binder.getCallingUid(); 12937 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12938 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12939 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12940 mContext.enforceCallingPermission( 12941 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12942 "deletePackage for user " + userId); 12943 } 12944 12945 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12946 try { 12947 observer.onPackageDeleted(packageName, 12948 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12949 } catch (RemoteException re) { 12950 } 12951 return; 12952 } 12953 12954 for (int currentUserId : users) { 12955 if (getBlockUninstallForUser(packageName, currentUserId)) { 12956 try { 12957 observer.onPackageDeleted(packageName, 12958 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 12959 } catch (RemoteException re) { 12960 } 12961 return; 12962 } 12963 } 12964 12965 if (DEBUG_REMOVE) { 12966 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12967 } 12968 // Queue up an async operation since the package deletion may take a little while. 12969 mHandler.post(new Runnable() { 12970 public void run() { 12971 mHandler.removeCallbacks(this); 12972 final int returnCode = deletePackageX(packageName, userId, flags); 12973 try { 12974 observer.onPackageDeleted(packageName, returnCode, null); 12975 } catch (RemoteException e) { 12976 Log.i(TAG, "Observer no longer exists."); 12977 } //end catch 12978 } //end run 12979 }); 12980 } 12981 12982 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12983 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12984 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12985 try { 12986 if (dpm != null) { 12987 // Does the package contains the device owner? 12988 if (dpm.isDeviceOwnerPackage(packageName)) { 12989 return true; 12990 } 12991 // Does it contain a device admin for any user? 12992 int[] users; 12993 if (userId == UserHandle.USER_ALL) { 12994 users = sUserManager.getUserIds(); 12995 } else { 12996 users = new int[]{userId}; 12997 } 12998 for (int i = 0; i < users.length; ++i) { 12999 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13000 return true; 13001 } 13002 } 13003 } 13004 } catch (RemoteException e) { 13005 } 13006 return false; 13007 } 13008 13009 /** 13010 * This method is an internal method that could be get invoked either 13011 * to delete an installed package or to clean up a failed installation. 13012 * After deleting an installed package, a broadcast is sent to notify any 13013 * listeners that the package has been installed. For cleaning up a failed 13014 * installation, the broadcast is not necessary since the package's 13015 * installation wouldn't have sent the initial broadcast either 13016 * The key steps in deleting a package are 13017 * deleting the package information in internal structures like mPackages, 13018 * deleting the packages base directories through installd 13019 * updating mSettings to reflect current status 13020 * persisting settings for later use 13021 * sending a broadcast if necessary 13022 */ 13023 private int deletePackageX(String packageName, int userId, int flags) { 13024 final PackageRemovedInfo info = new PackageRemovedInfo(); 13025 final boolean res; 13026 13027 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13028 ? UserHandle.ALL : new UserHandle(userId); 13029 13030 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13031 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13032 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13033 } 13034 13035 boolean removedForAllUsers = false; 13036 boolean systemUpdate = false; 13037 13038 // for the uninstall-updates case and restricted profiles, remember the per- 13039 // userhandle installed state 13040 int[] allUsers; 13041 boolean[] perUserInstalled; 13042 synchronized (mPackages) { 13043 PackageSetting ps = mSettings.mPackages.get(packageName); 13044 allUsers = sUserManager.getUserIds(); 13045 perUserInstalled = new boolean[allUsers.length]; 13046 for (int i = 0; i < allUsers.length; i++) { 13047 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13048 } 13049 } 13050 13051 synchronized (mInstallLock) { 13052 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13053 res = deletePackageLI(packageName, removeForUser, 13054 true, allUsers, perUserInstalled, 13055 flags | REMOVE_CHATTY, info, true); 13056 systemUpdate = info.isRemovedPackageSystemUpdate; 13057 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13058 removedForAllUsers = true; 13059 } 13060 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13061 + " removedForAllUsers=" + removedForAllUsers); 13062 } 13063 13064 if (res) { 13065 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13066 13067 // If the removed package was a system update, the old system package 13068 // was re-enabled; we need to broadcast this information 13069 if (systemUpdate) { 13070 Bundle extras = new Bundle(1); 13071 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13072 ? info.removedAppId : info.uid); 13073 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13074 13075 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13076 extras, null, null, null); 13077 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13078 extras, null, null, null); 13079 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13080 null, packageName, null, null); 13081 } 13082 } 13083 // Force a gc here. 13084 Runtime.getRuntime().gc(); 13085 // Delete the resources here after sending the broadcast to let 13086 // other processes clean up before deleting resources. 13087 if (info.args != null) { 13088 synchronized (mInstallLock) { 13089 info.args.doPostDeleteLI(true); 13090 } 13091 } 13092 13093 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13094 } 13095 13096 class PackageRemovedInfo { 13097 String removedPackage; 13098 int uid = -1; 13099 int removedAppId = -1; 13100 int[] removedUsers = null; 13101 boolean isRemovedPackageSystemUpdate = false; 13102 // Clean up resources deleted packages. 13103 InstallArgs args = null; 13104 13105 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13106 Bundle extras = new Bundle(1); 13107 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13108 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13109 if (replacing) { 13110 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13111 } 13112 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13113 if (removedPackage != null) { 13114 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13115 extras, null, null, removedUsers); 13116 if (fullRemove && !replacing) { 13117 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13118 extras, null, null, removedUsers); 13119 } 13120 } 13121 if (removedAppId >= 0) { 13122 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13123 removedUsers); 13124 } 13125 } 13126 } 13127 13128 /* 13129 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13130 * flag is not set, the data directory is removed as well. 13131 * make sure this flag is set for partially installed apps. If not its meaningless to 13132 * delete a partially installed application. 13133 */ 13134 private void removePackageDataLI(PackageSetting ps, 13135 int[] allUserHandles, boolean[] perUserInstalled, 13136 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13137 String packageName = ps.name; 13138 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13139 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13140 // Retrieve object to delete permissions for shared user later on 13141 final PackageSetting deletedPs; 13142 // reader 13143 synchronized (mPackages) { 13144 deletedPs = mSettings.mPackages.get(packageName); 13145 if (outInfo != null) { 13146 outInfo.removedPackage = packageName; 13147 outInfo.removedUsers = deletedPs != null 13148 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13149 : null; 13150 } 13151 } 13152 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13153 removeDataDirsLI(ps.volumeUuid, packageName); 13154 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13155 } 13156 // writer 13157 synchronized (mPackages) { 13158 if (deletedPs != null) { 13159 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13160 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13161 clearDefaultBrowserIfNeeded(packageName); 13162 if (outInfo != null) { 13163 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13164 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13165 } 13166 updatePermissionsLPw(deletedPs.name, null, 0); 13167 if (deletedPs.sharedUser != null) { 13168 // Remove permissions associated with package. Since runtime 13169 // permissions are per user we have to kill the removed package 13170 // or packages running under the shared user of the removed 13171 // package if revoking the permissions requested only by the removed 13172 // package is successful and this causes a change in gids. 13173 for (int userId : UserManagerService.getInstance().getUserIds()) { 13174 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13175 userId); 13176 if (userIdToKill == UserHandle.USER_ALL 13177 || userIdToKill >= UserHandle.USER_SYSTEM) { 13178 // If gids changed for this user, kill all affected packages. 13179 mHandler.post(new Runnable() { 13180 @Override 13181 public void run() { 13182 // This has to happen with no lock held. 13183 killApplication(deletedPs.name, deletedPs.appId, 13184 KILL_APP_REASON_GIDS_CHANGED); 13185 } 13186 }); 13187 break; 13188 } 13189 } 13190 } 13191 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13192 } 13193 // make sure to preserve per-user disabled state if this removal was just 13194 // a downgrade of a system app to the factory package 13195 if (allUserHandles != null && perUserInstalled != null) { 13196 if (DEBUG_REMOVE) { 13197 Slog.d(TAG, "Propagating install state across downgrade"); 13198 } 13199 for (int i = 0; i < allUserHandles.length; i++) { 13200 if (DEBUG_REMOVE) { 13201 Slog.d(TAG, " user " + allUserHandles[i] 13202 + " => " + perUserInstalled[i]); 13203 } 13204 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13205 } 13206 } 13207 } 13208 // can downgrade to reader 13209 if (writeSettings) { 13210 // Save settings now 13211 mSettings.writeLPr(); 13212 } 13213 } 13214 if (outInfo != null) { 13215 // A user ID was deleted here. Go through all users and remove it 13216 // from KeyStore. 13217 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13218 } 13219 } 13220 13221 static boolean locationIsPrivileged(File path) { 13222 try { 13223 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13224 .getCanonicalPath(); 13225 return path.getCanonicalPath().startsWith(privilegedAppDir); 13226 } catch (IOException e) { 13227 Slog.e(TAG, "Unable to access code path " + path); 13228 } 13229 return false; 13230 } 13231 13232 /* 13233 * Tries to delete system package. 13234 */ 13235 private boolean deleteSystemPackageLI(PackageSetting newPs, 13236 int[] allUserHandles, boolean[] perUserInstalled, 13237 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13238 final boolean applyUserRestrictions 13239 = (allUserHandles != null) && (perUserInstalled != null); 13240 PackageSetting disabledPs = null; 13241 // Confirm if the system package has been updated 13242 // An updated system app can be deleted. This will also have to restore 13243 // the system pkg from system partition 13244 // reader 13245 synchronized (mPackages) { 13246 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13247 } 13248 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13249 + " disabledPs=" + disabledPs); 13250 if (disabledPs == null) { 13251 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13252 return false; 13253 } else if (DEBUG_REMOVE) { 13254 Slog.d(TAG, "Deleting system pkg from data partition"); 13255 } 13256 if (DEBUG_REMOVE) { 13257 if (applyUserRestrictions) { 13258 Slog.d(TAG, "Remembering install states:"); 13259 for (int i = 0; i < allUserHandles.length; i++) { 13260 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13261 } 13262 } 13263 } 13264 // Delete the updated package 13265 outInfo.isRemovedPackageSystemUpdate = true; 13266 if (disabledPs.versionCode < newPs.versionCode) { 13267 // Delete data for downgrades 13268 flags &= ~PackageManager.DELETE_KEEP_DATA; 13269 } else { 13270 // Preserve data by setting flag 13271 flags |= PackageManager.DELETE_KEEP_DATA; 13272 } 13273 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13274 allUserHandles, perUserInstalled, outInfo, writeSettings); 13275 if (!ret) { 13276 return false; 13277 } 13278 // writer 13279 synchronized (mPackages) { 13280 // Reinstate the old system package 13281 mSettings.enableSystemPackageLPw(newPs.name); 13282 // Remove any native libraries from the upgraded package. 13283 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13284 } 13285 // Install the system package 13286 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13287 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13288 if (locationIsPrivileged(disabledPs.codePath)) { 13289 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13290 } 13291 13292 final PackageParser.Package newPkg; 13293 try { 13294 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13295 } catch (PackageManagerException e) { 13296 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13297 return false; 13298 } 13299 13300 // writer 13301 synchronized (mPackages) { 13302 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13303 13304 // Propagate the permissions state as we do not want to drop on the floor 13305 // runtime permissions. The update permissions method below will take 13306 // care of removing obsolete permissions and grant install permissions. 13307 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13308 updatePermissionsLPw(newPkg.packageName, newPkg, 13309 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13310 13311 if (applyUserRestrictions) { 13312 if (DEBUG_REMOVE) { 13313 Slog.d(TAG, "Propagating install state across reinstall"); 13314 } 13315 for (int i = 0; i < allUserHandles.length; i++) { 13316 if (DEBUG_REMOVE) { 13317 Slog.d(TAG, " user " + allUserHandles[i] 13318 + " => " + perUserInstalled[i]); 13319 } 13320 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13321 13322 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13323 } 13324 // Regardless of writeSettings we need to ensure that this restriction 13325 // state propagation is persisted 13326 mSettings.writeAllUsersPackageRestrictionsLPr(); 13327 } 13328 // can downgrade to reader here 13329 if (writeSettings) { 13330 mSettings.writeLPr(); 13331 } 13332 } 13333 return true; 13334 } 13335 13336 private boolean deleteInstalledPackageLI(PackageSetting ps, 13337 boolean deleteCodeAndResources, int flags, 13338 int[] allUserHandles, boolean[] perUserInstalled, 13339 PackageRemovedInfo outInfo, boolean writeSettings) { 13340 if (outInfo != null) { 13341 outInfo.uid = ps.appId; 13342 } 13343 13344 // Delete package data from internal structures and also remove data if flag is set 13345 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13346 13347 // Delete application code and resources 13348 if (deleteCodeAndResources && (outInfo != null)) { 13349 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13350 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13351 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13352 } 13353 return true; 13354 } 13355 13356 @Override 13357 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13358 int userId) { 13359 mContext.enforceCallingOrSelfPermission( 13360 android.Manifest.permission.DELETE_PACKAGES, null); 13361 synchronized (mPackages) { 13362 PackageSetting ps = mSettings.mPackages.get(packageName); 13363 if (ps == null) { 13364 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13365 return false; 13366 } 13367 if (!ps.getInstalled(userId)) { 13368 // Can't block uninstall for an app that is not installed or enabled. 13369 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13370 return false; 13371 } 13372 ps.setBlockUninstall(blockUninstall, userId); 13373 mSettings.writePackageRestrictionsLPr(userId); 13374 } 13375 return true; 13376 } 13377 13378 @Override 13379 public boolean getBlockUninstallForUser(String packageName, int userId) { 13380 synchronized (mPackages) { 13381 PackageSetting ps = mSettings.mPackages.get(packageName); 13382 if (ps == null) { 13383 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13384 return false; 13385 } 13386 return ps.getBlockUninstall(userId); 13387 } 13388 } 13389 13390 /* 13391 * This method handles package deletion in general 13392 */ 13393 private boolean deletePackageLI(String packageName, UserHandle user, 13394 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13395 int flags, PackageRemovedInfo outInfo, 13396 boolean writeSettings) { 13397 if (packageName == null) { 13398 Slog.w(TAG, "Attempt to delete null packageName."); 13399 return false; 13400 } 13401 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13402 PackageSetting ps; 13403 boolean dataOnly = false; 13404 int removeUser = -1; 13405 int appId = -1; 13406 synchronized (mPackages) { 13407 ps = mSettings.mPackages.get(packageName); 13408 if (ps == null) { 13409 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13410 return false; 13411 } 13412 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13413 && user.getIdentifier() != UserHandle.USER_ALL) { 13414 // The caller is asking that the package only be deleted for a single 13415 // user. To do this, we just mark its uninstalled state and delete 13416 // its data. If this is a system app, we only allow this to happen if 13417 // they have set the special DELETE_SYSTEM_APP which requests different 13418 // semantics than normal for uninstalling system apps. 13419 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13420 final int userId = user.getIdentifier(); 13421 ps.setUserState(userId, 13422 COMPONENT_ENABLED_STATE_DEFAULT, 13423 false, //installed 13424 true, //stopped 13425 true, //notLaunched 13426 false, //hidden 13427 null, null, null, 13428 false, // blockUninstall 13429 ps.readUserState(userId).domainVerificationStatus, 0); 13430 if (!isSystemApp(ps)) { 13431 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13432 // Other user still have this package installed, so all 13433 // we need to do is clear this user's data and save that 13434 // it is uninstalled. 13435 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13436 removeUser = user.getIdentifier(); 13437 appId = ps.appId; 13438 scheduleWritePackageRestrictionsLocked(removeUser); 13439 } else { 13440 // We need to set it back to 'installed' so the uninstall 13441 // broadcasts will be sent correctly. 13442 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13443 ps.setInstalled(true, user.getIdentifier()); 13444 } 13445 } else { 13446 // This is a system app, so we assume that the 13447 // other users still have this package installed, so all 13448 // we need to do is clear this user's data and save that 13449 // it is uninstalled. 13450 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13451 removeUser = user.getIdentifier(); 13452 appId = ps.appId; 13453 scheduleWritePackageRestrictionsLocked(removeUser); 13454 } 13455 } 13456 } 13457 13458 if (removeUser >= 0) { 13459 // From above, we determined that we are deleting this only 13460 // for a single user. Continue the work here. 13461 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13462 if (outInfo != null) { 13463 outInfo.removedPackage = packageName; 13464 outInfo.removedAppId = appId; 13465 outInfo.removedUsers = new int[] {removeUser}; 13466 } 13467 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13468 removeKeystoreDataIfNeeded(removeUser, appId); 13469 schedulePackageCleaning(packageName, removeUser, false); 13470 synchronized (mPackages) { 13471 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13472 scheduleWritePackageRestrictionsLocked(removeUser); 13473 } 13474 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13475 } 13476 return true; 13477 } 13478 13479 if (dataOnly) { 13480 // Delete application data first 13481 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13482 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13483 return true; 13484 } 13485 13486 boolean ret = false; 13487 if (isSystemApp(ps)) { 13488 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13489 // When an updated system application is deleted we delete the existing resources as well and 13490 // fall back to existing code in system partition 13491 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13492 flags, outInfo, writeSettings); 13493 } else { 13494 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13495 // Kill application pre-emptively especially for apps on sd. 13496 killApplication(packageName, ps.appId, "uninstall pkg"); 13497 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13498 allUserHandles, perUserInstalled, 13499 outInfo, writeSettings); 13500 } 13501 13502 return ret; 13503 } 13504 13505 private final class ClearStorageConnection implements ServiceConnection { 13506 IMediaContainerService mContainerService; 13507 13508 @Override 13509 public void onServiceConnected(ComponentName name, IBinder service) { 13510 synchronized (this) { 13511 mContainerService = IMediaContainerService.Stub.asInterface(service); 13512 notifyAll(); 13513 } 13514 } 13515 13516 @Override 13517 public void onServiceDisconnected(ComponentName name) { 13518 } 13519 } 13520 13521 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13522 final boolean mounted; 13523 if (Environment.isExternalStorageEmulated()) { 13524 mounted = true; 13525 } else { 13526 final String status = Environment.getExternalStorageState(); 13527 13528 mounted = status.equals(Environment.MEDIA_MOUNTED) 13529 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13530 } 13531 13532 if (!mounted) { 13533 return; 13534 } 13535 13536 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13537 int[] users; 13538 if (userId == UserHandle.USER_ALL) { 13539 users = sUserManager.getUserIds(); 13540 } else { 13541 users = new int[] { userId }; 13542 } 13543 final ClearStorageConnection conn = new ClearStorageConnection(); 13544 if (mContext.bindServiceAsUser( 13545 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13546 try { 13547 for (int curUser : users) { 13548 long timeout = SystemClock.uptimeMillis() + 5000; 13549 synchronized (conn) { 13550 long now = SystemClock.uptimeMillis(); 13551 while (conn.mContainerService == null && now < timeout) { 13552 try { 13553 conn.wait(timeout - now); 13554 } catch (InterruptedException e) { 13555 } 13556 } 13557 } 13558 if (conn.mContainerService == null) { 13559 return; 13560 } 13561 13562 final UserEnvironment userEnv = new UserEnvironment(curUser); 13563 clearDirectory(conn.mContainerService, 13564 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13565 if (allData) { 13566 clearDirectory(conn.mContainerService, 13567 userEnv.buildExternalStorageAppDataDirs(packageName)); 13568 clearDirectory(conn.mContainerService, 13569 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13570 } 13571 } 13572 } finally { 13573 mContext.unbindService(conn); 13574 } 13575 } 13576 } 13577 13578 @Override 13579 public void clearApplicationUserData(final String packageName, 13580 final IPackageDataObserver observer, final int userId) { 13581 mContext.enforceCallingOrSelfPermission( 13582 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13583 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13584 // Queue up an async operation since the package deletion may take a little while. 13585 mHandler.post(new Runnable() { 13586 public void run() { 13587 mHandler.removeCallbacks(this); 13588 final boolean succeeded; 13589 synchronized (mInstallLock) { 13590 succeeded = clearApplicationUserDataLI(packageName, userId); 13591 } 13592 clearExternalStorageDataSync(packageName, userId, true); 13593 if (succeeded) { 13594 // invoke DeviceStorageMonitor's update method to clear any notifications 13595 DeviceStorageMonitorInternal 13596 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13597 if (dsm != null) { 13598 dsm.checkMemory(); 13599 } 13600 } 13601 if(observer != null) { 13602 try { 13603 observer.onRemoveCompleted(packageName, succeeded); 13604 } catch (RemoteException e) { 13605 Log.i(TAG, "Observer no longer exists."); 13606 } 13607 } //end if observer 13608 } //end run 13609 }); 13610 } 13611 13612 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13613 if (packageName == null) { 13614 Slog.w(TAG, "Attempt to delete null packageName."); 13615 return false; 13616 } 13617 13618 // Try finding details about the requested package 13619 PackageParser.Package pkg; 13620 synchronized (mPackages) { 13621 pkg = mPackages.get(packageName); 13622 if (pkg == null) { 13623 final PackageSetting ps = mSettings.mPackages.get(packageName); 13624 if (ps != null) { 13625 pkg = ps.pkg; 13626 } 13627 } 13628 13629 if (pkg == null) { 13630 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13631 return false; 13632 } 13633 13634 PackageSetting ps = (PackageSetting) pkg.mExtras; 13635 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13636 } 13637 13638 // Always delete data directories for package, even if we found no other 13639 // record of app. This helps users recover from UID mismatches without 13640 // resorting to a full data wipe. 13641 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13642 if (retCode < 0) { 13643 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13644 return false; 13645 } 13646 13647 final int appId = pkg.applicationInfo.uid; 13648 removeKeystoreDataIfNeeded(userId, appId); 13649 13650 // Create a native library symlink only if we have native libraries 13651 // and if the native libraries are 32 bit libraries. We do not provide 13652 // this symlink for 64 bit libraries. 13653 if (pkg.applicationInfo.primaryCpuAbi != null && 13654 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13655 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13656 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13657 nativeLibPath, userId) < 0) { 13658 Slog.w(TAG, "Failed linking native library dir"); 13659 return false; 13660 } 13661 } 13662 13663 return true; 13664 } 13665 13666 /** 13667 * Reverts user permission state changes (permissions and flags) in 13668 * all packages for a given user. 13669 * 13670 * @param userId The device user for which to do a reset. 13671 */ 13672 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13673 final int packageCount = mPackages.size(); 13674 for (int i = 0; i < packageCount; i++) { 13675 PackageParser.Package pkg = mPackages.valueAt(i); 13676 PackageSetting ps = (PackageSetting) pkg.mExtras; 13677 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13678 } 13679 } 13680 13681 /** 13682 * Reverts user permission state changes (permissions and flags). 13683 * 13684 * @param ps The package for which to reset. 13685 * @param userId The device user for which to do a reset. 13686 */ 13687 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13688 final PackageSetting ps, final int userId) { 13689 if (ps.pkg == null) { 13690 return; 13691 } 13692 13693 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13694 | FLAG_PERMISSION_USER_FIXED 13695 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13696 13697 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13698 | FLAG_PERMISSION_POLICY_FIXED; 13699 13700 boolean writeInstallPermissions = false; 13701 boolean writeRuntimePermissions = false; 13702 13703 final int permissionCount = ps.pkg.requestedPermissions.size(); 13704 for (int i = 0; i < permissionCount; i++) { 13705 String permission = ps.pkg.requestedPermissions.get(i); 13706 13707 BasePermission bp = mSettings.mPermissions.get(permission); 13708 if (bp == null) { 13709 continue; 13710 } 13711 13712 // If shared user we just reset the state to which only this app contributed. 13713 if (ps.sharedUser != null) { 13714 boolean used = false; 13715 final int packageCount = ps.sharedUser.packages.size(); 13716 for (int j = 0; j < packageCount; j++) { 13717 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13718 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13719 && pkg.pkg.requestedPermissions.contains(permission)) { 13720 used = true; 13721 break; 13722 } 13723 } 13724 if (used) { 13725 continue; 13726 } 13727 } 13728 13729 PermissionsState permissionsState = ps.getPermissionsState(); 13730 13731 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13732 13733 // Always clear the user settable flags. 13734 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13735 bp.name) != null; 13736 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13737 if (hasInstallState) { 13738 writeInstallPermissions = true; 13739 } else { 13740 writeRuntimePermissions = true; 13741 } 13742 } 13743 13744 // Below is only runtime permission handling. 13745 if (!bp.isRuntime()) { 13746 continue; 13747 } 13748 13749 // Never clobber system or policy. 13750 if ((oldFlags & policyOrSystemFlags) != 0) { 13751 continue; 13752 } 13753 13754 // If this permission was granted by default, make sure it is. 13755 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13756 if (permissionsState.grantRuntimePermission(bp, userId) 13757 != PERMISSION_OPERATION_FAILURE) { 13758 writeRuntimePermissions = true; 13759 } 13760 } else { 13761 // Otherwise, reset the permission. 13762 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13763 switch (revokeResult) { 13764 case PERMISSION_OPERATION_SUCCESS: { 13765 writeRuntimePermissions = true; 13766 } break; 13767 13768 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13769 writeRuntimePermissions = true; 13770 final int appId = ps.appId; 13771 mHandler.post(new Runnable() { 13772 @Override 13773 public void run() { 13774 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13775 } 13776 }); 13777 } break; 13778 } 13779 } 13780 } 13781 13782 // Synchronously write as we are taking permissions away. 13783 if (writeRuntimePermissions) { 13784 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13785 } 13786 13787 // Synchronously write as we are taking permissions away. 13788 if (writeInstallPermissions) { 13789 mSettings.writeLPr(); 13790 } 13791 } 13792 13793 /** 13794 * Remove entries from the keystore daemon. Will only remove it if the 13795 * {@code appId} is valid. 13796 */ 13797 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13798 if (appId < 0) { 13799 return; 13800 } 13801 13802 final KeyStore keyStore = KeyStore.getInstance(); 13803 if (keyStore != null) { 13804 if (userId == UserHandle.USER_ALL) { 13805 for (final int individual : sUserManager.getUserIds()) { 13806 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13807 } 13808 } else { 13809 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13810 } 13811 } else { 13812 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13813 } 13814 } 13815 13816 @Override 13817 public void deleteApplicationCacheFiles(final String packageName, 13818 final IPackageDataObserver observer) { 13819 mContext.enforceCallingOrSelfPermission( 13820 android.Manifest.permission.DELETE_CACHE_FILES, null); 13821 // Queue up an async operation since the package deletion may take a little while. 13822 final int userId = UserHandle.getCallingUserId(); 13823 mHandler.post(new Runnable() { 13824 public void run() { 13825 mHandler.removeCallbacks(this); 13826 final boolean succeded; 13827 synchronized (mInstallLock) { 13828 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13829 } 13830 clearExternalStorageDataSync(packageName, userId, false); 13831 if (observer != null) { 13832 try { 13833 observer.onRemoveCompleted(packageName, succeded); 13834 } catch (RemoteException e) { 13835 Log.i(TAG, "Observer no longer exists."); 13836 } 13837 } //end if observer 13838 } //end run 13839 }); 13840 } 13841 13842 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13843 if (packageName == null) { 13844 Slog.w(TAG, "Attempt to delete null packageName."); 13845 return false; 13846 } 13847 PackageParser.Package p; 13848 synchronized (mPackages) { 13849 p = mPackages.get(packageName); 13850 } 13851 if (p == null) { 13852 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13853 return false; 13854 } 13855 final ApplicationInfo applicationInfo = p.applicationInfo; 13856 if (applicationInfo == null) { 13857 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13858 return false; 13859 } 13860 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13861 if (retCode < 0) { 13862 Slog.w(TAG, "Couldn't remove cache files for package: " 13863 + packageName + " u" + userId); 13864 return false; 13865 } 13866 return true; 13867 } 13868 13869 @Override 13870 public void getPackageSizeInfo(final String packageName, int userHandle, 13871 final IPackageStatsObserver observer) { 13872 mContext.enforceCallingOrSelfPermission( 13873 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13874 if (packageName == null) { 13875 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13876 } 13877 13878 PackageStats stats = new PackageStats(packageName, userHandle); 13879 13880 /* 13881 * Queue up an async operation since the package measurement may take a 13882 * little while. 13883 */ 13884 Message msg = mHandler.obtainMessage(INIT_COPY); 13885 msg.obj = new MeasureParams(stats, observer); 13886 mHandler.sendMessage(msg); 13887 } 13888 13889 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13890 PackageStats pStats) { 13891 if (packageName == null) { 13892 Slog.w(TAG, "Attempt to get size of null packageName."); 13893 return false; 13894 } 13895 PackageParser.Package p; 13896 boolean dataOnly = false; 13897 String libDirRoot = null; 13898 String asecPath = null; 13899 PackageSetting ps = null; 13900 synchronized (mPackages) { 13901 p = mPackages.get(packageName); 13902 ps = mSettings.mPackages.get(packageName); 13903 if(p == null) { 13904 dataOnly = true; 13905 if((ps == null) || (ps.pkg == null)) { 13906 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13907 return false; 13908 } 13909 p = ps.pkg; 13910 } 13911 if (ps != null) { 13912 libDirRoot = ps.legacyNativeLibraryPathString; 13913 } 13914 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13915 final long token = Binder.clearCallingIdentity(); 13916 try { 13917 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13918 if (secureContainerId != null) { 13919 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13920 } 13921 } finally { 13922 Binder.restoreCallingIdentity(token); 13923 } 13924 } 13925 } 13926 String publicSrcDir = null; 13927 if(!dataOnly) { 13928 final ApplicationInfo applicationInfo = p.applicationInfo; 13929 if (applicationInfo == null) { 13930 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13931 return false; 13932 } 13933 if (p.isForwardLocked()) { 13934 publicSrcDir = applicationInfo.getBaseResourcePath(); 13935 } 13936 } 13937 // TODO: extend to measure size of split APKs 13938 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13939 // not just the first level. 13940 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13941 // just the primary. 13942 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13943 13944 String apkPath; 13945 File packageDir = new File(p.codePath); 13946 13947 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13948 apkPath = packageDir.getAbsolutePath(); 13949 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13950 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13951 libDirRoot = null; 13952 } 13953 } else { 13954 apkPath = p.baseCodePath; 13955 } 13956 13957 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13958 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13959 if (res < 0) { 13960 return false; 13961 } 13962 13963 // Fix-up for forward-locked applications in ASEC containers. 13964 if (!isExternal(p)) { 13965 pStats.codeSize += pStats.externalCodeSize; 13966 pStats.externalCodeSize = 0L; 13967 } 13968 13969 return true; 13970 } 13971 13972 13973 @Override 13974 public void addPackageToPreferred(String packageName) { 13975 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13976 } 13977 13978 @Override 13979 public void removePackageFromPreferred(String packageName) { 13980 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13981 } 13982 13983 @Override 13984 public List<PackageInfo> getPreferredPackages(int flags) { 13985 return new ArrayList<PackageInfo>(); 13986 } 13987 13988 private int getUidTargetSdkVersionLockedLPr(int uid) { 13989 Object obj = mSettings.getUserIdLPr(uid); 13990 if (obj instanceof SharedUserSetting) { 13991 final SharedUserSetting sus = (SharedUserSetting) obj; 13992 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13993 final Iterator<PackageSetting> it = sus.packages.iterator(); 13994 while (it.hasNext()) { 13995 final PackageSetting ps = it.next(); 13996 if (ps.pkg != null) { 13997 int v = ps.pkg.applicationInfo.targetSdkVersion; 13998 if (v < vers) vers = v; 13999 } 14000 } 14001 return vers; 14002 } else if (obj instanceof PackageSetting) { 14003 final PackageSetting ps = (PackageSetting) obj; 14004 if (ps.pkg != null) { 14005 return ps.pkg.applicationInfo.targetSdkVersion; 14006 } 14007 } 14008 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14009 } 14010 14011 @Override 14012 public void addPreferredActivity(IntentFilter filter, int match, 14013 ComponentName[] set, ComponentName activity, int userId) { 14014 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14015 "Adding preferred"); 14016 } 14017 14018 private void addPreferredActivityInternal(IntentFilter filter, int match, 14019 ComponentName[] set, ComponentName activity, boolean always, int userId, 14020 String opname) { 14021 // writer 14022 int callingUid = Binder.getCallingUid(); 14023 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14024 if (filter.countActions() == 0) { 14025 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14026 return; 14027 } 14028 synchronized (mPackages) { 14029 if (mContext.checkCallingOrSelfPermission( 14030 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14031 != PackageManager.PERMISSION_GRANTED) { 14032 if (getUidTargetSdkVersionLockedLPr(callingUid) 14033 < Build.VERSION_CODES.FROYO) { 14034 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14035 + callingUid); 14036 return; 14037 } 14038 mContext.enforceCallingOrSelfPermission( 14039 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14040 } 14041 14042 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14043 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14044 + userId + ":"); 14045 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14046 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14047 scheduleWritePackageRestrictionsLocked(userId); 14048 } 14049 } 14050 14051 @Override 14052 public void replacePreferredActivity(IntentFilter filter, int match, 14053 ComponentName[] set, ComponentName activity, int userId) { 14054 if (filter.countActions() != 1) { 14055 throw new IllegalArgumentException( 14056 "replacePreferredActivity expects filter to have only 1 action."); 14057 } 14058 if (filter.countDataAuthorities() != 0 14059 || filter.countDataPaths() != 0 14060 || filter.countDataSchemes() > 1 14061 || filter.countDataTypes() != 0) { 14062 throw new IllegalArgumentException( 14063 "replacePreferredActivity expects filter to have no data authorities, " + 14064 "paths, or types; and at most one scheme."); 14065 } 14066 14067 final int callingUid = Binder.getCallingUid(); 14068 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14069 synchronized (mPackages) { 14070 if (mContext.checkCallingOrSelfPermission( 14071 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14072 != PackageManager.PERMISSION_GRANTED) { 14073 if (getUidTargetSdkVersionLockedLPr(callingUid) 14074 < Build.VERSION_CODES.FROYO) { 14075 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14076 + Binder.getCallingUid()); 14077 return; 14078 } 14079 mContext.enforceCallingOrSelfPermission( 14080 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14081 } 14082 14083 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14084 if (pir != null) { 14085 // Get all of the existing entries that exactly match this filter. 14086 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14087 if (existing != null && existing.size() == 1) { 14088 PreferredActivity cur = existing.get(0); 14089 if (DEBUG_PREFERRED) { 14090 Slog.i(TAG, "Checking replace of preferred:"); 14091 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14092 if (!cur.mPref.mAlways) { 14093 Slog.i(TAG, " -- CUR; not mAlways!"); 14094 } else { 14095 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14096 Slog.i(TAG, " -- CUR: mSet=" 14097 + Arrays.toString(cur.mPref.mSetComponents)); 14098 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14099 Slog.i(TAG, " -- NEW: mMatch=" 14100 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14101 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14102 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14103 } 14104 } 14105 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14106 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14107 && cur.mPref.sameSet(set)) { 14108 // Setting the preferred activity to what it happens to be already 14109 if (DEBUG_PREFERRED) { 14110 Slog.i(TAG, "Replacing with same preferred activity " 14111 + cur.mPref.mShortComponent + " for user " 14112 + userId + ":"); 14113 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14114 } 14115 return; 14116 } 14117 } 14118 14119 if (existing != null) { 14120 if (DEBUG_PREFERRED) { 14121 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14122 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14123 } 14124 for (int i = 0; i < existing.size(); i++) { 14125 PreferredActivity pa = existing.get(i); 14126 if (DEBUG_PREFERRED) { 14127 Slog.i(TAG, "Removing existing preferred activity " 14128 + pa.mPref.mComponent + ":"); 14129 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14130 } 14131 pir.removeFilter(pa); 14132 } 14133 } 14134 } 14135 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14136 "Replacing preferred"); 14137 } 14138 } 14139 14140 @Override 14141 public void clearPackagePreferredActivities(String packageName) { 14142 final int uid = Binder.getCallingUid(); 14143 // writer 14144 synchronized (mPackages) { 14145 PackageParser.Package pkg = mPackages.get(packageName); 14146 if (pkg == null || pkg.applicationInfo.uid != uid) { 14147 if (mContext.checkCallingOrSelfPermission( 14148 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14149 != PackageManager.PERMISSION_GRANTED) { 14150 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14151 < Build.VERSION_CODES.FROYO) { 14152 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14153 + Binder.getCallingUid()); 14154 return; 14155 } 14156 mContext.enforceCallingOrSelfPermission( 14157 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14158 } 14159 } 14160 14161 int user = UserHandle.getCallingUserId(); 14162 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14163 scheduleWritePackageRestrictionsLocked(user); 14164 } 14165 } 14166 } 14167 14168 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14169 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14170 ArrayList<PreferredActivity> removed = null; 14171 boolean changed = false; 14172 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14173 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14174 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14175 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14176 continue; 14177 } 14178 Iterator<PreferredActivity> it = pir.filterIterator(); 14179 while (it.hasNext()) { 14180 PreferredActivity pa = it.next(); 14181 // Mark entry for removal only if it matches the package name 14182 // and the entry is of type "always". 14183 if (packageName == null || 14184 (pa.mPref.mComponent.getPackageName().equals(packageName) 14185 && pa.mPref.mAlways)) { 14186 if (removed == null) { 14187 removed = new ArrayList<PreferredActivity>(); 14188 } 14189 removed.add(pa); 14190 } 14191 } 14192 if (removed != null) { 14193 for (int j=0; j<removed.size(); j++) { 14194 PreferredActivity pa = removed.get(j); 14195 pir.removeFilter(pa); 14196 } 14197 changed = true; 14198 } 14199 } 14200 return changed; 14201 } 14202 14203 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14204 private void clearIntentFilterVerificationsLPw(int userId) { 14205 final int packageCount = mPackages.size(); 14206 for (int i = 0; i < packageCount; i++) { 14207 PackageParser.Package pkg = mPackages.valueAt(i); 14208 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14209 } 14210 } 14211 14212 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14213 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14214 if (userId == UserHandle.USER_ALL) { 14215 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14216 sUserManager.getUserIds())) { 14217 for (int oneUserId : sUserManager.getUserIds()) { 14218 scheduleWritePackageRestrictionsLocked(oneUserId); 14219 } 14220 } 14221 } else { 14222 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14223 scheduleWritePackageRestrictionsLocked(userId); 14224 } 14225 } 14226 } 14227 14228 void clearDefaultBrowserIfNeeded(String packageName) { 14229 for (int oneUserId : sUserManager.getUserIds()) { 14230 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14231 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14232 if (packageName.equals(defaultBrowserPackageName)) { 14233 setDefaultBrowserPackageName(null, oneUserId); 14234 } 14235 } 14236 } 14237 14238 @Override 14239 public void resetApplicationPreferences(int userId) { 14240 mContext.enforceCallingOrSelfPermission( 14241 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14242 // writer 14243 synchronized (mPackages) { 14244 final long identity = Binder.clearCallingIdentity(); 14245 try { 14246 clearPackagePreferredActivitiesLPw(null, userId); 14247 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14248 // TODO: We have to reset the default SMS and Phone. This requires 14249 // significant refactoring to keep all default apps in the package 14250 // manager (cleaner but more work) or have the services provide 14251 // callbacks to the package manager to request a default app reset. 14252 applyFactoryDefaultBrowserLPw(userId); 14253 clearIntentFilterVerificationsLPw(userId); 14254 primeDomainVerificationsLPw(userId); 14255 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14256 scheduleWritePackageRestrictionsLocked(userId); 14257 } finally { 14258 Binder.restoreCallingIdentity(identity); 14259 } 14260 } 14261 } 14262 14263 @Override 14264 public int getPreferredActivities(List<IntentFilter> outFilters, 14265 List<ComponentName> outActivities, String packageName) { 14266 14267 int num = 0; 14268 final int userId = UserHandle.getCallingUserId(); 14269 // reader 14270 synchronized (mPackages) { 14271 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14272 if (pir != null) { 14273 final Iterator<PreferredActivity> it = pir.filterIterator(); 14274 while (it.hasNext()) { 14275 final PreferredActivity pa = it.next(); 14276 if (packageName == null 14277 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14278 && pa.mPref.mAlways)) { 14279 if (outFilters != null) { 14280 outFilters.add(new IntentFilter(pa)); 14281 } 14282 if (outActivities != null) { 14283 outActivities.add(pa.mPref.mComponent); 14284 } 14285 } 14286 } 14287 } 14288 } 14289 14290 return num; 14291 } 14292 14293 @Override 14294 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14295 int userId) { 14296 int callingUid = Binder.getCallingUid(); 14297 if (callingUid != Process.SYSTEM_UID) { 14298 throw new SecurityException( 14299 "addPersistentPreferredActivity can only be run by the system"); 14300 } 14301 if (filter.countActions() == 0) { 14302 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14303 return; 14304 } 14305 synchronized (mPackages) { 14306 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14307 " :"); 14308 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14309 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14310 new PersistentPreferredActivity(filter, activity)); 14311 scheduleWritePackageRestrictionsLocked(userId); 14312 } 14313 } 14314 14315 @Override 14316 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14317 int callingUid = Binder.getCallingUid(); 14318 if (callingUid != Process.SYSTEM_UID) { 14319 throw new SecurityException( 14320 "clearPackagePersistentPreferredActivities can only be run by the system"); 14321 } 14322 ArrayList<PersistentPreferredActivity> removed = null; 14323 boolean changed = false; 14324 synchronized (mPackages) { 14325 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14326 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14327 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14328 .valueAt(i); 14329 if (userId != thisUserId) { 14330 continue; 14331 } 14332 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14333 while (it.hasNext()) { 14334 PersistentPreferredActivity ppa = it.next(); 14335 // Mark entry for removal only if it matches the package name. 14336 if (ppa.mComponent.getPackageName().equals(packageName)) { 14337 if (removed == null) { 14338 removed = new ArrayList<PersistentPreferredActivity>(); 14339 } 14340 removed.add(ppa); 14341 } 14342 } 14343 if (removed != null) { 14344 for (int j=0; j<removed.size(); j++) { 14345 PersistentPreferredActivity ppa = removed.get(j); 14346 ppir.removeFilter(ppa); 14347 } 14348 changed = true; 14349 } 14350 } 14351 14352 if (changed) { 14353 scheduleWritePackageRestrictionsLocked(userId); 14354 } 14355 } 14356 } 14357 14358 /** 14359 * Common machinery for picking apart a restored XML blob and passing 14360 * it to a caller-supplied functor to be applied to the running system. 14361 */ 14362 private void restoreFromXml(XmlPullParser parser, int userId, 14363 String expectedStartTag, BlobXmlRestorer functor) 14364 throws IOException, XmlPullParserException { 14365 int type; 14366 while ((type = parser.next()) != XmlPullParser.START_TAG 14367 && type != XmlPullParser.END_DOCUMENT) { 14368 } 14369 if (type != XmlPullParser.START_TAG) { 14370 // oops didn't find a start tag?! 14371 if (DEBUG_BACKUP) { 14372 Slog.e(TAG, "Didn't find start tag during restore"); 14373 } 14374 return; 14375 } 14376 14377 // this is supposed to be TAG_PREFERRED_BACKUP 14378 if (!expectedStartTag.equals(parser.getName())) { 14379 if (DEBUG_BACKUP) { 14380 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14381 } 14382 return; 14383 } 14384 14385 // skip interfering stuff, then we're aligned with the backing implementation 14386 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14387 functor.apply(parser, userId); 14388 } 14389 14390 private interface BlobXmlRestorer { 14391 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14392 } 14393 14394 /** 14395 * Non-Binder method, support for the backup/restore mechanism: write the 14396 * full set of preferred activities in its canonical XML format. Returns the 14397 * XML output as a byte array, or null if there is none. 14398 */ 14399 @Override 14400 public byte[] getPreferredActivityBackup(int userId) { 14401 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14402 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14403 } 14404 14405 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14406 try { 14407 final XmlSerializer serializer = new FastXmlSerializer(); 14408 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14409 serializer.startDocument(null, true); 14410 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14411 14412 synchronized (mPackages) { 14413 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14414 } 14415 14416 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14417 serializer.endDocument(); 14418 serializer.flush(); 14419 } catch (Exception e) { 14420 if (DEBUG_BACKUP) { 14421 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14422 } 14423 return null; 14424 } 14425 14426 return dataStream.toByteArray(); 14427 } 14428 14429 @Override 14430 public void restorePreferredActivities(byte[] backup, int userId) { 14431 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14432 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14433 } 14434 14435 try { 14436 final XmlPullParser parser = Xml.newPullParser(); 14437 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14438 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14439 new BlobXmlRestorer() { 14440 @Override 14441 public void apply(XmlPullParser parser, int userId) 14442 throws XmlPullParserException, IOException { 14443 synchronized (mPackages) { 14444 mSettings.readPreferredActivitiesLPw(parser, userId); 14445 } 14446 } 14447 } ); 14448 } catch (Exception e) { 14449 if (DEBUG_BACKUP) { 14450 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14451 } 14452 } 14453 } 14454 14455 /** 14456 * Non-Binder method, support for the backup/restore mechanism: write the 14457 * default browser (etc) settings in its canonical XML format. Returns the default 14458 * browser XML representation as a byte array, or null if there is none. 14459 */ 14460 @Override 14461 public byte[] getDefaultAppsBackup(int userId) { 14462 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14463 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14464 } 14465 14466 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14467 try { 14468 final XmlSerializer serializer = new FastXmlSerializer(); 14469 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14470 serializer.startDocument(null, true); 14471 serializer.startTag(null, TAG_DEFAULT_APPS); 14472 14473 synchronized (mPackages) { 14474 mSettings.writeDefaultAppsLPr(serializer, userId); 14475 } 14476 14477 serializer.endTag(null, TAG_DEFAULT_APPS); 14478 serializer.endDocument(); 14479 serializer.flush(); 14480 } catch (Exception e) { 14481 if (DEBUG_BACKUP) { 14482 Slog.e(TAG, "Unable to write default apps for backup", e); 14483 } 14484 return null; 14485 } 14486 14487 return dataStream.toByteArray(); 14488 } 14489 14490 @Override 14491 public void restoreDefaultApps(byte[] backup, int userId) { 14492 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14493 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14494 } 14495 14496 try { 14497 final XmlPullParser parser = Xml.newPullParser(); 14498 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14499 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14500 new BlobXmlRestorer() { 14501 @Override 14502 public void apply(XmlPullParser parser, int userId) 14503 throws XmlPullParserException, IOException { 14504 synchronized (mPackages) { 14505 mSettings.readDefaultAppsLPw(parser, userId); 14506 } 14507 } 14508 } ); 14509 } catch (Exception e) { 14510 if (DEBUG_BACKUP) { 14511 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14512 } 14513 } 14514 } 14515 14516 @Override 14517 public byte[] getIntentFilterVerificationBackup(int userId) { 14518 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14519 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14520 } 14521 14522 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14523 try { 14524 final XmlSerializer serializer = new FastXmlSerializer(); 14525 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14526 serializer.startDocument(null, true); 14527 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14528 14529 synchronized (mPackages) { 14530 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14531 } 14532 14533 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14534 serializer.endDocument(); 14535 serializer.flush(); 14536 } catch (Exception e) { 14537 if (DEBUG_BACKUP) { 14538 Slog.e(TAG, "Unable to write default apps for backup", e); 14539 } 14540 return null; 14541 } 14542 14543 return dataStream.toByteArray(); 14544 } 14545 14546 @Override 14547 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14548 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14549 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14550 } 14551 14552 try { 14553 final XmlPullParser parser = Xml.newPullParser(); 14554 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14555 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14556 new BlobXmlRestorer() { 14557 @Override 14558 public void apply(XmlPullParser parser, int userId) 14559 throws XmlPullParserException, IOException { 14560 synchronized (mPackages) { 14561 mSettings.readAllDomainVerificationsLPr(parser, userId); 14562 mSettings.writeLPr(); 14563 } 14564 } 14565 } ); 14566 } catch (Exception e) { 14567 if (DEBUG_BACKUP) { 14568 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14569 } 14570 } 14571 } 14572 14573 @Override 14574 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14575 int sourceUserId, int targetUserId, int flags) { 14576 mContext.enforceCallingOrSelfPermission( 14577 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14578 int callingUid = Binder.getCallingUid(); 14579 enforceOwnerRights(ownerPackage, callingUid); 14580 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14581 if (intentFilter.countActions() == 0) { 14582 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14583 return; 14584 } 14585 synchronized (mPackages) { 14586 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14587 ownerPackage, targetUserId, flags); 14588 CrossProfileIntentResolver resolver = 14589 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14590 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14591 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14592 if (existing != null) { 14593 int size = existing.size(); 14594 for (int i = 0; i < size; i++) { 14595 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14596 return; 14597 } 14598 } 14599 } 14600 resolver.addFilter(newFilter); 14601 scheduleWritePackageRestrictionsLocked(sourceUserId); 14602 } 14603 } 14604 14605 @Override 14606 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14607 mContext.enforceCallingOrSelfPermission( 14608 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14609 int callingUid = Binder.getCallingUid(); 14610 enforceOwnerRights(ownerPackage, callingUid); 14611 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14612 synchronized (mPackages) { 14613 CrossProfileIntentResolver resolver = 14614 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14615 ArraySet<CrossProfileIntentFilter> set = 14616 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14617 for (CrossProfileIntentFilter filter : set) { 14618 if (filter.getOwnerPackage().equals(ownerPackage)) { 14619 resolver.removeFilter(filter); 14620 } 14621 } 14622 scheduleWritePackageRestrictionsLocked(sourceUserId); 14623 } 14624 } 14625 14626 // Enforcing that callingUid is owning pkg on userId 14627 private void enforceOwnerRights(String pkg, int callingUid) { 14628 // The system owns everything. 14629 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14630 return; 14631 } 14632 int callingUserId = UserHandle.getUserId(callingUid); 14633 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14634 if (pi == null) { 14635 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14636 + callingUserId); 14637 } 14638 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14639 throw new SecurityException("Calling uid " + callingUid 14640 + " does not own package " + pkg); 14641 } 14642 } 14643 14644 @Override 14645 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14646 Intent intent = new Intent(Intent.ACTION_MAIN); 14647 intent.addCategory(Intent.CATEGORY_HOME); 14648 14649 final int callingUserId = UserHandle.getCallingUserId(); 14650 List<ResolveInfo> list = queryIntentActivities(intent, null, 14651 PackageManager.GET_META_DATA, callingUserId); 14652 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14653 true, false, false, callingUserId); 14654 14655 allHomeCandidates.clear(); 14656 if (list != null) { 14657 for (ResolveInfo ri : list) { 14658 allHomeCandidates.add(ri); 14659 } 14660 } 14661 return (preferred == null || preferred.activityInfo == null) 14662 ? null 14663 : new ComponentName(preferred.activityInfo.packageName, 14664 preferred.activityInfo.name); 14665 } 14666 14667 @Override 14668 public void setApplicationEnabledSetting(String appPackageName, 14669 int newState, int flags, int userId, String callingPackage) { 14670 if (!sUserManager.exists(userId)) return; 14671 if (callingPackage == null) { 14672 callingPackage = Integer.toString(Binder.getCallingUid()); 14673 } 14674 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14675 } 14676 14677 @Override 14678 public void setComponentEnabledSetting(ComponentName componentName, 14679 int newState, int flags, int userId) { 14680 if (!sUserManager.exists(userId)) return; 14681 setEnabledSetting(componentName.getPackageName(), 14682 componentName.getClassName(), newState, flags, userId, null); 14683 } 14684 14685 private void setEnabledSetting(final String packageName, String className, int newState, 14686 final int flags, int userId, String callingPackage) { 14687 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14688 || newState == COMPONENT_ENABLED_STATE_ENABLED 14689 || newState == COMPONENT_ENABLED_STATE_DISABLED 14690 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14691 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14692 throw new IllegalArgumentException("Invalid new component state: " 14693 + newState); 14694 } 14695 PackageSetting pkgSetting; 14696 final int uid = Binder.getCallingUid(); 14697 final int permission = mContext.checkCallingOrSelfPermission( 14698 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14699 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14700 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14701 boolean sendNow = false; 14702 boolean isApp = (className == null); 14703 String componentName = isApp ? packageName : className; 14704 int packageUid = -1; 14705 ArrayList<String> components; 14706 14707 // writer 14708 synchronized (mPackages) { 14709 pkgSetting = mSettings.mPackages.get(packageName); 14710 if (pkgSetting == null) { 14711 if (className == null) { 14712 throw new IllegalArgumentException( 14713 "Unknown package: " + packageName); 14714 } 14715 throw new IllegalArgumentException( 14716 "Unknown component: " + packageName 14717 + "/" + className); 14718 } 14719 // Allow root and verify that userId is not being specified by a different user 14720 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14721 throw new SecurityException( 14722 "Permission Denial: attempt to change component state from pid=" 14723 + Binder.getCallingPid() 14724 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14725 } 14726 if (className == null) { 14727 // We're dealing with an application/package level state change 14728 if (pkgSetting.getEnabled(userId) == newState) { 14729 // Nothing to do 14730 return; 14731 } 14732 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14733 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14734 // Don't care about who enables an app. 14735 callingPackage = null; 14736 } 14737 pkgSetting.setEnabled(newState, userId, callingPackage); 14738 // pkgSetting.pkg.mSetEnabled = newState; 14739 } else { 14740 // We're dealing with a component level state change 14741 // First, verify that this is a valid class name. 14742 PackageParser.Package pkg = pkgSetting.pkg; 14743 if (pkg == null || !pkg.hasComponentClassName(className)) { 14744 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14745 throw new IllegalArgumentException("Component class " + className 14746 + " does not exist in " + packageName); 14747 } else { 14748 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14749 + className + " does not exist in " + packageName); 14750 } 14751 } 14752 switch (newState) { 14753 case COMPONENT_ENABLED_STATE_ENABLED: 14754 if (!pkgSetting.enableComponentLPw(className, userId)) { 14755 return; 14756 } 14757 break; 14758 case COMPONENT_ENABLED_STATE_DISABLED: 14759 if (!pkgSetting.disableComponentLPw(className, userId)) { 14760 return; 14761 } 14762 break; 14763 case COMPONENT_ENABLED_STATE_DEFAULT: 14764 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14765 return; 14766 } 14767 break; 14768 default: 14769 Slog.e(TAG, "Invalid new component state: " + newState); 14770 return; 14771 } 14772 } 14773 scheduleWritePackageRestrictionsLocked(userId); 14774 components = mPendingBroadcasts.get(userId, packageName); 14775 final boolean newPackage = components == null; 14776 if (newPackage) { 14777 components = new ArrayList<String>(); 14778 } 14779 if (!components.contains(componentName)) { 14780 components.add(componentName); 14781 } 14782 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14783 sendNow = true; 14784 // Purge entry from pending broadcast list if another one exists already 14785 // since we are sending one right away. 14786 mPendingBroadcasts.remove(userId, packageName); 14787 } else { 14788 if (newPackage) { 14789 mPendingBroadcasts.put(userId, packageName, components); 14790 } 14791 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14792 // Schedule a message 14793 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14794 } 14795 } 14796 } 14797 14798 long callingId = Binder.clearCallingIdentity(); 14799 try { 14800 if (sendNow) { 14801 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14802 sendPackageChangedBroadcast(packageName, 14803 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14804 } 14805 } finally { 14806 Binder.restoreCallingIdentity(callingId); 14807 } 14808 } 14809 14810 private void sendPackageChangedBroadcast(String packageName, 14811 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14812 if (DEBUG_INSTALL) 14813 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14814 + componentNames); 14815 Bundle extras = new Bundle(4); 14816 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14817 String nameList[] = new String[componentNames.size()]; 14818 componentNames.toArray(nameList); 14819 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14820 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14821 extras.putInt(Intent.EXTRA_UID, packageUid); 14822 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14823 new int[] {UserHandle.getUserId(packageUid)}); 14824 } 14825 14826 @Override 14827 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14828 if (!sUserManager.exists(userId)) return; 14829 final int uid = Binder.getCallingUid(); 14830 final int permission = mContext.checkCallingOrSelfPermission( 14831 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14832 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14833 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14834 // writer 14835 synchronized (mPackages) { 14836 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14837 allowedByPermission, uid, userId)) { 14838 scheduleWritePackageRestrictionsLocked(userId); 14839 } 14840 } 14841 } 14842 14843 @Override 14844 public String getInstallerPackageName(String packageName) { 14845 // reader 14846 synchronized (mPackages) { 14847 return mSettings.getInstallerPackageNameLPr(packageName); 14848 } 14849 } 14850 14851 @Override 14852 public int getApplicationEnabledSetting(String packageName, int userId) { 14853 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14854 int uid = Binder.getCallingUid(); 14855 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14856 // reader 14857 synchronized (mPackages) { 14858 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14859 } 14860 } 14861 14862 @Override 14863 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14864 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14865 int uid = Binder.getCallingUid(); 14866 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14867 // reader 14868 synchronized (mPackages) { 14869 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14870 } 14871 } 14872 14873 @Override 14874 public void enterSafeMode() { 14875 enforceSystemOrRoot("Only the system can request entering safe mode"); 14876 14877 if (!mSystemReady) { 14878 mSafeMode = true; 14879 } 14880 } 14881 14882 @Override 14883 public void systemReady() { 14884 mSystemReady = true; 14885 14886 // Read the compatibilty setting when the system is ready. 14887 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14888 mContext.getContentResolver(), 14889 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14890 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14891 if (DEBUG_SETTINGS) { 14892 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14893 } 14894 14895 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14896 14897 synchronized (mPackages) { 14898 // Verify that all of the preferred activity components actually 14899 // exist. It is possible for applications to be updated and at 14900 // that point remove a previously declared activity component that 14901 // had been set as a preferred activity. We try to clean this up 14902 // the next time we encounter that preferred activity, but it is 14903 // possible for the user flow to never be able to return to that 14904 // situation so here we do a sanity check to make sure we haven't 14905 // left any junk around. 14906 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14907 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14908 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14909 removed.clear(); 14910 for (PreferredActivity pa : pir.filterSet()) { 14911 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14912 removed.add(pa); 14913 } 14914 } 14915 if (removed.size() > 0) { 14916 for (int r=0; r<removed.size(); r++) { 14917 PreferredActivity pa = removed.get(r); 14918 Slog.w(TAG, "Removing dangling preferred activity: " 14919 + pa.mPref.mComponent); 14920 pir.removeFilter(pa); 14921 } 14922 mSettings.writePackageRestrictionsLPr( 14923 mSettings.mPreferredActivities.keyAt(i)); 14924 } 14925 } 14926 14927 for (int userId : UserManagerService.getInstance().getUserIds()) { 14928 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14929 grantPermissionsUserIds = ArrayUtils.appendInt( 14930 grantPermissionsUserIds, userId); 14931 } 14932 } 14933 } 14934 sUserManager.systemReady(); 14935 14936 // If we upgraded grant all default permissions before kicking off. 14937 for (int userId : grantPermissionsUserIds) { 14938 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14939 } 14940 14941 // Kick off any messages waiting for system ready 14942 if (mPostSystemReadyMessages != null) { 14943 for (Message msg : mPostSystemReadyMessages) { 14944 msg.sendToTarget(); 14945 } 14946 mPostSystemReadyMessages = null; 14947 } 14948 14949 // Watch for external volumes that come and go over time 14950 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14951 storage.registerListener(mStorageListener); 14952 14953 mInstallerService.systemReady(); 14954 mPackageDexOptimizer.systemReady(); 14955 14956 MountServiceInternal mountServiceInternal = LocalServices.getService( 14957 MountServiceInternal.class); 14958 mountServiceInternal.addExternalStoragePolicy( 14959 new MountServiceInternal.ExternalStorageMountPolicy() { 14960 @Override 14961 public int getMountMode(int uid, String packageName) { 14962 if (Process.isIsolated(uid)) { 14963 return Zygote.MOUNT_EXTERNAL_NONE; 14964 } 14965 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14966 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14967 } 14968 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14969 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14970 } 14971 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14972 return Zygote.MOUNT_EXTERNAL_READ; 14973 } 14974 return Zygote.MOUNT_EXTERNAL_WRITE; 14975 } 14976 14977 @Override 14978 public boolean hasExternalStorage(int uid, String packageName) { 14979 return true; 14980 } 14981 }); 14982 } 14983 14984 @Override 14985 public boolean isSafeMode() { 14986 return mSafeMode; 14987 } 14988 14989 @Override 14990 public boolean hasSystemUidErrors() { 14991 return mHasSystemUidErrors; 14992 } 14993 14994 static String arrayToString(int[] array) { 14995 StringBuffer buf = new StringBuffer(128); 14996 buf.append('['); 14997 if (array != null) { 14998 for (int i=0; i<array.length; i++) { 14999 if (i > 0) buf.append(", "); 15000 buf.append(array[i]); 15001 } 15002 } 15003 buf.append(']'); 15004 return buf.toString(); 15005 } 15006 15007 static class DumpState { 15008 public static final int DUMP_LIBS = 1 << 0; 15009 public static final int DUMP_FEATURES = 1 << 1; 15010 public static final int DUMP_RESOLVERS = 1 << 2; 15011 public static final int DUMP_PERMISSIONS = 1 << 3; 15012 public static final int DUMP_PACKAGES = 1 << 4; 15013 public static final int DUMP_SHARED_USERS = 1 << 5; 15014 public static final int DUMP_MESSAGES = 1 << 6; 15015 public static final int DUMP_PROVIDERS = 1 << 7; 15016 public static final int DUMP_VERIFIERS = 1 << 8; 15017 public static final int DUMP_PREFERRED = 1 << 9; 15018 public static final int DUMP_PREFERRED_XML = 1 << 10; 15019 public static final int DUMP_KEYSETS = 1 << 11; 15020 public static final int DUMP_VERSION = 1 << 12; 15021 public static final int DUMP_INSTALLS = 1 << 13; 15022 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 15023 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 15024 15025 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15026 15027 private int mTypes; 15028 15029 private int mOptions; 15030 15031 private boolean mTitlePrinted; 15032 15033 private SharedUserSetting mSharedUser; 15034 15035 public boolean isDumping(int type) { 15036 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15037 return true; 15038 } 15039 15040 return (mTypes & type) != 0; 15041 } 15042 15043 public void setDump(int type) { 15044 mTypes |= type; 15045 } 15046 15047 public boolean isOptionEnabled(int option) { 15048 return (mOptions & option) != 0; 15049 } 15050 15051 public void setOptionEnabled(int option) { 15052 mOptions |= option; 15053 } 15054 15055 public boolean onTitlePrinted() { 15056 final boolean printed = mTitlePrinted; 15057 mTitlePrinted = true; 15058 return printed; 15059 } 15060 15061 public boolean getTitlePrinted() { 15062 return mTitlePrinted; 15063 } 15064 15065 public void setTitlePrinted(boolean enabled) { 15066 mTitlePrinted = enabled; 15067 } 15068 15069 public SharedUserSetting getSharedUser() { 15070 return mSharedUser; 15071 } 15072 15073 public void setSharedUser(SharedUserSetting user) { 15074 mSharedUser = user; 15075 } 15076 } 15077 15078 @Override 15079 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15080 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15081 (new PackageManagerShellCommand(this)).exec( 15082 this, in, out, err, args, resultReceiver); 15083 } 15084 15085 @Override 15086 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15087 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15088 != PackageManager.PERMISSION_GRANTED) { 15089 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15090 + Binder.getCallingPid() 15091 + ", uid=" + Binder.getCallingUid() 15092 + " without permission " 15093 + android.Manifest.permission.DUMP); 15094 return; 15095 } 15096 15097 DumpState dumpState = new DumpState(); 15098 boolean fullPreferred = false; 15099 boolean checkin = false; 15100 15101 String packageName = null; 15102 ArraySet<String> permissionNames = null; 15103 15104 int opti = 0; 15105 while (opti < args.length) { 15106 String opt = args[opti]; 15107 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15108 break; 15109 } 15110 opti++; 15111 15112 if ("-a".equals(opt)) { 15113 // Right now we only know how to print all. 15114 } else if ("-h".equals(opt)) { 15115 pw.println("Package manager dump options:"); 15116 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15117 pw.println(" --checkin: dump for a checkin"); 15118 pw.println(" -f: print details of intent filters"); 15119 pw.println(" -h: print this help"); 15120 pw.println(" cmd may be one of:"); 15121 pw.println(" l[ibraries]: list known shared libraries"); 15122 pw.println(" f[ibraries]: list device features"); 15123 pw.println(" k[eysets]: print known keysets"); 15124 pw.println(" r[esolvers]: dump intent resolvers"); 15125 pw.println(" perm[issions]: dump permissions"); 15126 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15127 pw.println(" pref[erred]: print preferred package settings"); 15128 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15129 pw.println(" prov[iders]: dump content providers"); 15130 pw.println(" p[ackages]: dump installed packages"); 15131 pw.println(" s[hared-users]: dump shared user IDs"); 15132 pw.println(" m[essages]: print collected runtime messages"); 15133 pw.println(" v[erifiers]: print package verifier info"); 15134 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15135 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15136 pw.println(" version: print database version info"); 15137 pw.println(" write: write current settings now"); 15138 pw.println(" installs: details about install sessions"); 15139 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15140 pw.println(" <package.name>: info about given package"); 15141 return; 15142 } else if ("--checkin".equals(opt)) { 15143 checkin = true; 15144 } else if ("-f".equals(opt)) { 15145 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15146 } else { 15147 pw.println("Unknown argument: " + opt + "; use -h for help"); 15148 } 15149 } 15150 15151 // Is the caller requesting to dump a particular piece of data? 15152 if (opti < args.length) { 15153 String cmd = args[opti]; 15154 opti++; 15155 // Is this a package name? 15156 if ("android".equals(cmd) || cmd.contains(".")) { 15157 packageName = cmd; 15158 // When dumping a single package, we always dump all of its 15159 // filter information since the amount of data will be reasonable. 15160 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15161 } else if ("check-permission".equals(cmd)) { 15162 if (opti >= args.length) { 15163 pw.println("Error: check-permission missing permission argument"); 15164 return; 15165 } 15166 String perm = args[opti]; 15167 opti++; 15168 if (opti >= args.length) { 15169 pw.println("Error: check-permission missing package argument"); 15170 return; 15171 } 15172 String pkg = args[opti]; 15173 opti++; 15174 int user = UserHandle.getUserId(Binder.getCallingUid()); 15175 if (opti < args.length) { 15176 try { 15177 user = Integer.parseInt(args[opti]); 15178 } catch (NumberFormatException e) { 15179 pw.println("Error: check-permission user argument is not a number: " 15180 + args[opti]); 15181 return; 15182 } 15183 } 15184 pw.println(checkPermission(perm, pkg, user)); 15185 return; 15186 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15187 dumpState.setDump(DumpState.DUMP_LIBS); 15188 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15189 dumpState.setDump(DumpState.DUMP_FEATURES); 15190 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15191 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15192 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15193 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15194 } else if ("permission".equals(cmd)) { 15195 if (opti >= args.length) { 15196 pw.println("Error: permission requires permission name"); 15197 return; 15198 } 15199 permissionNames = new ArraySet<>(); 15200 while (opti < args.length) { 15201 permissionNames.add(args[opti]); 15202 opti++; 15203 } 15204 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15205 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15206 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15207 dumpState.setDump(DumpState.DUMP_PREFERRED); 15208 } else if ("preferred-xml".equals(cmd)) { 15209 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15210 if (opti < args.length && "--full".equals(args[opti])) { 15211 fullPreferred = true; 15212 opti++; 15213 } 15214 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15215 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15216 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15217 dumpState.setDump(DumpState.DUMP_PACKAGES); 15218 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15219 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15220 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15221 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15222 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15223 dumpState.setDump(DumpState.DUMP_MESSAGES); 15224 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15225 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15226 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15227 || "intent-filter-verifiers".equals(cmd)) { 15228 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15229 } else if ("version".equals(cmd)) { 15230 dumpState.setDump(DumpState.DUMP_VERSION); 15231 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15232 dumpState.setDump(DumpState.DUMP_KEYSETS); 15233 } else if ("installs".equals(cmd)) { 15234 dumpState.setDump(DumpState.DUMP_INSTALLS); 15235 } else if ("write".equals(cmd)) { 15236 synchronized (mPackages) { 15237 mSettings.writeLPr(); 15238 pw.println("Settings written."); 15239 return; 15240 } 15241 } 15242 } 15243 15244 if (checkin) { 15245 pw.println("vers,1"); 15246 } 15247 15248 // reader 15249 synchronized (mPackages) { 15250 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15251 if (!checkin) { 15252 if (dumpState.onTitlePrinted()) 15253 pw.println(); 15254 pw.println("Database versions:"); 15255 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15256 } 15257 } 15258 15259 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15260 if (!checkin) { 15261 if (dumpState.onTitlePrinted()) 15262 pw.println(); 15263 pw.println("Verifiers:"); 15264 pw.print(" Required: "); 15265 pw.print(mRequiredVerifierPackage); 15266 pw.print(" (uid="); 15267 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15268 pw.println(")"); 15269 } else if (mRequiredVerifierPackage != null) { 15270 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15271 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15272 } 15273 } 15274 15275 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15276 packageName == null) { 15277 if (mIntentFilterVerifierComponent != null) { 15278 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15279 if (!checkin) { 15280 if (dumpState.onTitlePrinted()) 15281 pw.println(); 15282 pw.println("Intent Filter Verifier:"); 15283 pw.print(" Using: "); 15284 pw.print(verifierPackageName); 15285 pw.print(" (uid="); 15286 pw.print(getPackageUid(verifierPackageName, 0)); 15287 pw.println(")"); 15288 } else if (verifierPackageName != null) { 15289 pw.print("ifv,"); pw.print(verifierPackageName); 15290 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15291 } 15292 } else { 15293 pw.println(); 15294 pw.println("No Intent Filter Verifier available!"); 15295 } 15296 } 15297 15298 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15299 boolean printedHeader = false; 15300 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15301 while (it.hasNext()) { 15302 String name = it.next(); 15303 SharedLibraryEntry ent = mSharedLibraries.get(name); 15304 if (!checkin) { 15305 if (!printedHeader) { 15306 if (dumpState.onTitlePrinted()) 15307 pw.println(); 15308 pw.println("Libraries:"); 15309 printedHeader = true; 15310 } 15311 pw.print(" "); 15312 } else { 15313 pw.print("lib,"); 15314 } 15315 pw.print(name); 15316 if (!checkin) { 15317 pw.print(" -> "); 15318 } 15319 if (ent.path != null) { 15320 if (!checkin) { 15321 pw.print("(jar) "); 15322 pw.print(ent.path); 15323 } else { 15324 pw.print(",jar,"); 15325 pw.print(ent.path); 15326 } 15327 } else { 15328 if (!checkin) { 15329 pw.print("(apk) "); 15330 pw.print(ent.apk); 15331 } else { 15332 pw.print(",apk,"); 15333 pw.print(ent.apk); 15334 } 15335 } 15336 pw.println(); 15337 } 15338 } 15339 15340 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15341 if (dumpState.onTitlePrinted()) 15342 pw.println(); 15343 if (!checkin) { 15344 pw.println("Features:"); 15345 } 15346 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15347 while (it.hasNext()) { 15348 String name = it.next(); 15349 if (!checkin) { 15350 pw.print(" "); 15351 } else { 15352 pw.print("feat,"); 15353 } 15354 pw.println(name); 15355 } 15356 } 15357 15358 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15359 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15360 : "Activity Resolver Table:", " ", packageName, 15361 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15362 dumpState.setTitlePrinted(true); 15363 } 15364 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15365 : "Receiver Resolver Table:", " ", packageName, 15366 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15367 dumpState.setTitlePrinted(true); 15368 } 15369 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15370 : "Service Resolver Table:", " ", packageName, 15371 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15372 dumpState.setTitlePrinted(true); 15373 } 15374 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15375 : "Provider Resolver Table:", " ", packageName, 15376 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15377 dumpState.setTitlePrinted(true); 15378 } 15379 } 15380 15381 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15382 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15383 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15384 int user = mSettings.mPreferredActivities.keyAt(i); 15385 if (pir.dump(pw, 15386 dumpState.getTitlePrinted() 15387 ? "\nPreferred Activities User " + user + ":" 15388 : "Preferred Activities User " + user + ":", " ", 15389 packageName, true, false)) { 15390 dumpState.setTitlePrinted(true); 15391 } 15392 } 15393 } 15394 15395 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15396 pw.flush(); 15397 FileOutputStream fout = new FileOutputStream(fd); 15398 BufferedOutputStream str = new BufferedOutputStream(fout); 15399 XmlSerializer serializer = new FastXmlSerializer(); 15400 try { 15401 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15402 serializer.startDocument(null, true); 15403 serializer.setFeature( 15404 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15405 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15406 serializer.endDocument(); 15407 serializer.flush(); 15408 } catch (IllegalArgumentException e) { 15409 pw.println("Failed writing: " + e); 15410 } catch (IllegalStateException e) { 15411 pw.println("Failed writing: " + e); 15412 } catch (IOException e) { 15413 pw.println("Failed writing: " + e); 15414 } 15415 } 15416 15417 if (!checkin 15418 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15419 && packageName == null) { 15420 pw.println(); 15421 int count = mSettings.mPackages.size(); 15422 if (count == 0) { 15423 pw.println("No applications!"); 15424 pw.println(); 15425 } else { 15426 final String prefix = " "; 15427 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15428 if (allPackageSettings.size() == 0) { 15429 pw.println("No domain preferred apps!"); 15430 pw.println(); 15431 } else { 15432 pw.println("App verification status:"); 15433 pw.println(); 15434 count = 0; 15435 for (PackageSetting ps : allPackageSettings) { 15436 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15437 if (ivi == null || ivi.getPackageName() == null) continue; 15438 pw.println(prefix + "Package: " + ivi.getPackageName()); 15439 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15440 pw.println(prefix + "Status: " + ivi.getStatusString()); 15441 pw.println(); 15442 count++; 15443 } 15444 if (count == 0) { 15445 pw.println(prefix + "No app verification established."); 15446 pw.println(); 15447 } 15448 for (int userId : sUserManager.getUserIds()) { 15449 pw.println("App linkages for user " + userId + ":"); 15450 pw.println(); 15451 count = 0; 15452 for (PackageSetting ps : allPackageSettings) { 15453 final long status = ps.getDomainVerificationStatusForUser(userId); 15454 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15455 continue; 15456 } 15457 pw.println(prefix + "Package: " + ps.name); 15458 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15459 String statusStr = IntentFilterVerificationInfo. 15460 getStatusStringFromValue(status); 15461 pw.println(prefix + "Status: " + statusStr); 15462 pw.println(); 15463 count++; 15464 } 15465 if (count == 0) { 15466 pw.println(prefix + "No configured app linkages."); 15467 pw.println(); 15468 } 15469 } 15470 } 15471 } 15472 } 15473 15474 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15475 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15476 if (packageName == null && permissionNames == null) { 15477 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15478 if (iperm == 0) { 15479 if (dumpState.onTitlePrinted()) 15480 pw.println(); 15481 pw.println("AppOp Permissions:"); 15482 } 15483 pw.print(" AppOp Permission "); 15484 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15485 pw.println(":"); 15486 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15487 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15488 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15489 } 15490 } 15491 } 15492 } 15493 15494 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15495 boolean printedSomething = false; 15496 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15497 if (packageName != null && !packageName.equals(p.info.packageName)) { 15498 continue; 15499 } 15500 if (!printedSomething) { 15501 if (dumpState.onTitlePrinted()) 15502 pw.println(); 15503 pw.println("Registered ContentProviders:"); 15504 printedSomething = true; 15505 } 15506 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15507 pw.print(" "); pw.println(p.toString()); 15508 } 15509 printedSomething = false; 15510 for (Map.Entry<String, PackageParser.Provider> entry : 15511 mProvidersByAuthority.entrySet()) { 15512 PackageParser.Provider p = entry.getValue(); 15513 if (packageName != null && !packageName.equals(p.info.packageName)) { 15514 continue; 15515 } 15516 if (!printedSomething) { 15517 if (dumpState.onTitlePrinted()) 15518 pw.println(); 15519 pw.println("ContentProvider Authorities:"); 15520 printedSomething = true; 15521 } 15522 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15523 pw.print(" "); pw.println(p.toString()); 15524 if (p.info != null && p.info.applicationInfo != null) { 15525 final String appInfo = p.info.applicationInfo.toString(); 15526 pw.print(" applicationInfo="); pw.println(appInfo); 15527 } 15528 } 15529 } 15530 15531 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15532 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15533 } 15534 15535 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15536 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15537 } 15538 15539 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15540 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15541 } 15542 15543 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15544 // XXX should handle packageName != null by dumping only install data that 15545 // the given package is involved with. 15546 if (dumpState.onTitlePrinted()) pw.println(); 15547 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15548 } 15549 15550 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15551 if (dumpState.onTitlePrinted()) pw.println(); 15552 mSettings.dumpReadMessagesLPr(pw, dumpState); 15553 15554 pw.println(); 15555 pw.println("Package warning messages:"); 15556 BufferedReader in = null; 15557 String line = null; 15558 try { 15559 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15560 while ((line = in.readLine()) != null) { 15561 if (line.contains("ignored: updated version")) continue; 15562 pw.println(line); 15563 } 15564 } catch (IOException ignored) { 15565 } finally { 15566 IoUtils.closeQuietly(in); 15567 } 15568 } 15569 15570 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15571 BufferedReader in = null; 15572 String line = null; 15573 try { 15574 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15575 while ((line = in.readLine()) != null) { 15576 if (line.contains("ignored: updated version")) continue; 15577 pw.print("msg,"); 15578 pw.println(line); 15579 } 15580 } catch (IOException ignored) { 15581 } finally { 15582 IoUtils.closeQuietly(in); 15583 } 15584 } 15585 } 15586 } 15587 15588 private String dumpDomainString(String packageName) { 15589 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15590 List<IntentFilter> filters = getAllIntentFilters(packageName); 15591 15592 ArraySet<String> result = new ArraySet<>(); 15593 if (iviList.size() > 0) { 15594 for (IntentFilterVerificationInfo ivi : iviList) { 15595 for (String host : ivi.getDomains()) { 15596 result.add(host); 15597 } 15598 } 15599 } 15600 if (filters != null && filters.size() > 0) { 15601 for (IntentFilter filter : filters) { 15602 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15603 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15604 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15605 result.addAll(filter.getHostsList()); 15606 } 15607 } 15608 } 15609 15610 StringBuilder sb = new StringBuilder(result.size() * 16); 15611 for (String domain : result) { 15612 if (sb.length() > 0) sb.append(" "); 15613 sb.append(domain); 15614 } 15615 return sb.toString(); 15616 } 15617 15618 // ------- apps on sdcard specific code ------- 15619 static final boolean DEBUG_SD_INSTALL = false; 15620 15621 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15622 15623 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15624 15625 private boolean mMediaMounted = false; 15626 15627 static String getEncryptKey() { 15628 try { 15629 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15630 SD_ENCRYPTION_KEYSTORE_NAME); 15631 if (sdEncKey == null) { 15632 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15633 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15634 if (sdEncKey == null) { 15635 Slog.e(TAG, "Failed to create encryption keys"); 15636 return null; 15637 } 15638 } 15639 return sdEncKey; 15640 } catch (NoSuchAlgorithmException nsae) { 15641 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15642 return null; 15643 } catch (IOException ioe) { 15644 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15645 return null; 15646 } 15647 } 15648 15649 /* 15650 * Update media status on PackageManager. 15651 */ 15652 @Override 15653 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15654 int callingUid = Binder.getCallingUid(); 15655 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15656 throw new SecurityException("Media status can only be updated by the system"); 15657 } 15658 // reader; this apparently protects mMediaMounted, but should probably 15659 // be a different lock in that case. 15660 synchronized (mPackages) { 15661 Log.i(TAG, "Updating external media status from " 15662 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15663 + (mediaStatus ? "mounted" : "unmounted")); 15664 if (DEBUG_SD_INSTALL) 15665 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15666 + ", mMediaMounted=" + mMediaMounted); 15667 if (mediaStatus == mMediaMounted) { 15668 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15669 : 0, -1); 15670 mHandler.sendMessage(msg); 15671 return; 15672 } 15673 mMediaMounted = mediaStatus; 15674 } 15675 // Queue up an async operation since the package installation may take a 15676 // little while. 15677 mHandler.post(new Runnable() { 15678 public void run() { 15679 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15680 } 15681 }); 15682 } 15683 15684 /** 15685 * Called by MountService when the initial ASECs to scan are available. 15686 * Should block until all the ASEC containers are finished being scanned. 15687 */ 15688 public void scanAvailableAsecs() { 15689 updateExternalMediaStatusInner(true, false, false); 15690 if (mShouldRestoreconData) { 15691 SELinuxMMAC.setRestoreconDone(); 15692 mShouldRestoreconData = false; 15693 } 15694 } 15695 15696 /* 15697 * Collect information of applications on external media, map them against 15698 * existing containers and update information based on current mount status. 15699 * Please note that we always have to report status if reportStatus has been 15700 * set to true especially when unloading packages. 15701 */ 15702 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15703 boolean externalStorage) { 15704 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15705 int[] uidArr = EmptyArray.INT; 15706 15707 final String[] list = PackageHelper.getSecureContainerList(); 15708 if (ArrayUtils.isEmpty(list)) { 15709 Log.i(TAG, "No secure containers found"); 15710 } else { 15711 // Process list of secure containers and categorize them 15712 // as active or stale based on their package internal state. 15713 15714 // reader 15715 synchronized (mPackages) { 15716 for (String cid : list) { 15717 // Leave stages untouched for now; installer service owns them 15718 if (PackageInstallerService.isStageName(cid)) continue; 15719 15720 if (DEBUG_SD_INSTALL) 15721 Log.i(TAG, "Processing container " + cid); 15722 String pkgName = getAsecPackageName(cid); 15723 if (pkgName == null) { 15724 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15725 continue; 15726 } 15727 if (DEBUG_SD_INSTALL) 15728 Log.i(TAG, "Looking for pkg : " + pkgName); 15729 15730 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15731 if (ps == null) { 15732 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15733 continue; 15734 } 15735 15736 /* 15737 * Skip packages that are not external if we're unmounting 15738 * external storage. 15739 */ 15740 if (externalStorage && !isMounted && !isExternal(ps)) { 15741 continue; 15742 } 15743 15744 final AsecInstallArgs args = new AsecInstallArgs(cid, 15745 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15746 // The package status is changed only if the code path 15747 // matches between settings and the container id. 15748 if (ps.codePathString != null 15749 && ps.codePathString.startsWith(args.getCodePath())) { 15750 if (DEBUG_SD_INSTALL) { 15751 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15752 + " at code path: " + ps.codePathString); 15753 } 15754 15755 // We do have a valid package installed on sdcard 15756 processCids.put(args, ps.codePathString); 15757 final int uid = ps.appId; 15758 if (uid != -1) { 15759 uidArr = ArrayUtils.appendInt(uidArr, uid); 15760 } 15761 } else { 15762 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15763 + ps.codePathString); 15764 } 15765 } 15766 } 15767 15768 Arrays.sort(uidArr); 15769 } 15770 15771 // Process packages with valid entries. 15772 if (isMounted) { 15773 if (DEBUG_SD_INSTALL) 15774 Log.i(TAG, "Loading packages"); 15775 loadMediaPackages(processCids, uidArr, externalStorage); 15776 startCleaningPackages(); 15777 mInstallerService.onSecureContainersAvailable(); 15778 } else { 15779 if (DEBUG_SD_INSTALL) 15780 Log.i(TAG, "Unloading packages"); 15781 unloadMediaPackages(processCids, uidArr, reportStatus); 15782 } 15783 } 15784 15785 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15786 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15787 final int size = infos.size(); 15788 final String[] packageNames = new String[size]; 15789 final int[] packageUids = new int[size]; 15790 for (int i = 0; i < size; i++) { 15791 final ApplicationInfo info = infos.get(i); 15792 packageNames[i] = info.packageName; 15793 packageUids[i] = info.uid; 15794 } 15795 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15796 finishedReceiver); 15797 } 15798 15799 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15800 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15801 sendResourcesChangedBroadcast(mediaStatus, replacing, 15802 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15803 } 15804 15805 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15806 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15807 int size = pkgList.length; 15808 if (size > 0) { 15809 // Send broadcasts here 15810 Bundle extras = new Bundle(); 15811 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15812 if (uidArr != null) { 15813 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15814 } 15815 if (replacing) { 15816 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15817 } 15818 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15819 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15820 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15821 } 15822 } 15823 15824 /* 15825 * Look at potentially valid container ids from processCids If package 15826 * information doesn't match the one on record or package scanning fails, 15827 * the cid is added to list of removeCids. We currently don't delete stale 15828 * containers. 15829 */ 15830 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15831 boolean externalStorage) { 15832 ArrayList<String> pkgList = new ArrayList<String>(); 15833 Set<AsecInstallArgs> keys = processCids.keySet(); 15834 15835 for (AsecInstallArgs args : keys) { 15836 String codePath = processCids.get(args); 15837 if (DEBUG_SD_INSTALL) 15838 Log.i(TAG, "Loading container : " + args.cid); 15839 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15840 try { 15841 // Make sure there are no container errors first. 15842 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15843 Slog.e(TAG, "Failed to mount cid : " + args.cid 15844 + " when installing from sdcard"); 15845 continue; 15846 } 15847 // Check code path here. 15848 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15849 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15850 + " does not match one in settings " + codePath); 15851 continue; 15852 } 15853 // Parse package 15854 int parseFlags = mDefParseFlags; 15855 if (args.isExternalAsec()) { 15856 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15857 } 15858 if (args.isFwdLocked()) { 15859 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15860 } 15861 15862 synchronized (mInstallLock) { 15863 PackageParser.Package pkg = null; 15864 try { 15865 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15866 } catch (PackageManagerException e) { 15867 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15868 } 15869 // Scan the package 15870 if (pkg != null) { 15871 /* 15872 * TODO why is the lock being held? doPostInstall is 15873 * called in other places without the lock. This needs 15874 * to be straightened out. 15875 */ 15876 // writer 15877 synchronized (mPackages) { 15878 retCode = PackageManager.INSTALL_SUCCEEDED; 15879 pkgList.add(pkg.packageName); 15880 // Post process args 15881 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15882 pkg.applicationInfo.uid); 15883 } 15884 } else { 15885 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15886 } 15887 } 15888 15889 } finally { 15890 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15891 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15892 } 15893 } 15894 } 15895 // writer 15896 synchronized (mPackages) { 15897 // If the platform SDK has changed since the last time we booted, 15898 // we need to re-grant app permission to catch any new ones that 15899 // appear. This is really a hack, and means that apps can in some 15900 // cases get permissions that the user didn't initially explicitly 15901 // allow... it would be nice to have some better way to handle 15902 // this situation. 15903 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15904 : mSettings.getInternalVersion(); 15905 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15906 : StorageManager.UUID_PRIVATE_INTERNAL; 15907 15908 int updateFlags = UPDATE_PERMISSIONS_ALL; 15909 if (ver.sdkVersion != mSdkVersion) { 15910 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15911 + mSdkVersion + "; regranting permissions for external"); 15912 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15913 } 15914 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15915 15916 // Yay, everything is now upgraded 15917 ver.forceCurrent(); 15918 15919 // can downgrade to reader 15920 // Persist settings 15921 mSettings.writeLPr(); 15922 } 15923 // Send a broadcast to let everyone know we are done processing 15924 if (pkgList.size() > 0) { 15925 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15926 } 15927 } 15928 15929 /* 15930 * Utility method to unload a list of specified containers 15931 */ 15932 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15933 // Just unmount all valid containers. 15934 for (AsecInstallArgs arg : cidArgs) { 15935 synchronized (mInstallLock) { 15936 arg.doPostDeleteLI(false); 15937 } 15938 } 15939 } 15940 15941 /* 15942 * Unload packages mounted on external media. This involves deleting package 15943 * data from internal structures, sending broadcasts about diabled packages, 15944 * gc'ing to free up references, unmounting all secure containers 15945 * corresponding to packages on external media, and posting a 15946 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15947 * that we always have to post this message if status has been requested no 15948 * matter what. 15949 */ 15950 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15951 final boolean reportStatus) { 15952 if (DEBUG_SD_INSTALL) 15953 Log.i(TAG, "unloading media packages"); 15954 ArrayList<String> pkgList = new ArrayList<String>(); 15955 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15956 final Set<AsecInstallArgs> keys = processCids.keySet(); 15957 for (AsecInstallArgs args : keys) { 15958 String pkgName = args.getPackageName(); 15959 if (DEBUG_SD_INSTALL) 15960 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15961 // Delete package internally 15962 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15963 synchronized (mInstallLock) { 15964 boolean res = deletePackageLI(pkgName, null, false, null, null, 15965 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15966 if (res) { 15967 pkgList.add(pkgName); 15968 } else { 15969 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15970 failedList.add(args); 15971 } 15972 } 15973 } 15974 15975 // reader 15976 synchronized (mPackages) { 15977 // We didn't update the settings after removing each package; 15978 // write them now for all packages. 15979 mSettings.writeLPr(); 15980 } 15981 15982 // We have to absolutely send UPDATED_MEDIA_STATUS only 15983 // after confirming that all the receivers processed the ordered 15984 // broadcast when packages get disabled, force a gc to clean things up. 15985 // and unload all the containers. 15986 if (pkgList.size() > 0) { 15987 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15988 new IIntentReceiver.Stub() { 15989 public void performReceive(Intent intent, int resultCode, String data, 15990 Bundle extras, boolean ordered, boolean sticky, 15991 int sendingUser) throws RemoteException { 15992 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15993 reportStatus ? 1 : 0, 1, keys); 15994 mHandler.sendMessage(msg); 15995 } 15996 }); 15997 } else { 15998 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15999 keys); 16000 mHandler.sendMessage(msg); 16001 } 16002 } 16003 16004 private void loadPrivatePackages(final VolumeInfo vol) { 16005 mHandler.post(new Runnable() { 16006 @Override 16007 public void run() { 16008 loadPrivatePackagesInner(vol); 16009 } 16010 }); 16011 } 16012 16013 private void loadPrivatePackagesInner(VolumeInfo vol) { 16014 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16015 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16016 16017 final VersionInfo ver; 16018 final List<PackageSetting> packages; 16019 synchronized (mPackages) { 16020 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16021 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16022 } 16023 16024 for (PackageSetting ps : packages) { 16025 synchronized (mInstallLock) { 16026 final PackageParser.Package pkg; 16027 try { 16028 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16029 loaded.add(pkg.applicationInfo); 16030 } catch (PackageManagerException e) { 16031 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16032 } 16033 16034 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16035 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16036 } 16037 } 16038 } 16039 16040 synchronized (mPackages) { 16041 int updateFlags = UPDATE_PERMISSIONS_ALL; 16042 if (ver.sdkVersion != mSdkVersion) { 16043 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16044 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16045 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16046 } 16047 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16048 16049 // Yay, everything is now upgraded 16050 ver.forceCurrent(); 16051 16052 mSettings.writeLPr(); 16053 } 16054 16055 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16056 sendResourcesChangedBroadcast(true, false, loaded, null); 16057 } 16058 16059 private void unloadPrivatePackages(final VolumeInfo vol) { 16060 mHandler.post(new Runnable() { 16061 @Override 16062 public void run() { 16063 unloadPrivatePackagesInner(vol); 16064 } 16065 }); 16066 } 16067 16068 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16069 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16070 synchronized (mInstallLock) { 16071 synchronized (mPackages) { 16072 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16073 for (PackageSetting ps : packages) { 16074 if (ps.pkg == null) continue; 16075 16076 final ApplicationInfo info = ps.pkg.applicationInfo; 16077 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16078 if (deletePackageLI(ps.name, null, false, null, null, 16079 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16080 unloaded.add(info); 16081 } else { 16082 Slog.w(TAG, "Failed to unload " + ps.codePath); 16083 } 16084 } 16085 16086 mSettings.writeLPr(); 16087 } 16088 } 16089 16090 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16091 sendResourcesChangedBroadcast(false, false, unloaded, null); 16092 } 16093 16094 /** 16095 * Examine all users present on given mounted volume, and destroy data 16096 * belonging to users that are no longer valid, or whose user ID has been 16097 * recycled. 16098 */ 16099 private void reconcileUsers(String volumeUuid) { 16100 final File[] files = FileUtils 16101 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16102 for (File file : files) { 16103 if (!file.isDirectory()) continue; 16104 16105 final int userId; 16106 final UserInfo info; 16107 try { 16108 userId = Integer.parseInt(file.getName()); 16109 info = sUserManager.getUserInfo(userId); 16110 } catch (NumberFormatException e) { 16111 Slog.w(TAG, "Invalid user directory " + file); 16112 continue; 16113 } 16114 16115 boolean destroyUser = false; 16116 if (info == null) { 16117 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16118 + " because no matching user was found"); 16119 destroyUser = true; 16120 } else { 16121 try { 16122 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16123 } catch (IOException e) { 16124 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16125 + " because we failed to enforce serial number: " + e); 16126 destroyUser = true; 16127 } 16128 } 16129 16130 if (destroyUser) { 16131 synchronized (mInstallLock) { 16132 mInstaller.removeUserDataDirs(volumeUuid, userId); 16133 } 16134 } 16135 } 16136 16137 final UserManager um = mContext.getSystemService(UserManager.class); 16138 for (UserInfo user : um.getUsers()) { 16139 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16140 if (userDir.exists()) continue; 16141 16142 try { 16143 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16144 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16145 } catch (IOException e) { 16146 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16147 } 16148 } 16149 } 16150 16151 /** 16152 * Examine all apps present on given mounted volume, and destroy apps that 16153 * aren't expected, either due to uninstallation or reinstallation on 16154 * another volume. 16155 */ 16156 private void reconcileApps(String volumeUuid) { 16157 final File[] files = FileUtils 16158 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16159 for (File file : files) { 16160 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16161 && !PackageInstallerService.isStageName(file.getName()); 16162 if (!isPackage) { 16163 // Ignore entries which are not packages 16164 continue; 16165 } 16166 16167 boolean destroyApp = false; 16168 String packageName = null; 16169 try { 16170 final PackageLite pkg = PackageParser.parsePackageLite(file, 16171 PackageParser.PARSE_MUST_BE_APK); 16172 packageName = pkg.packageName; 16173 16174 synchronized (mPackages) { 16175 final PackageSetting ps = mSettings.mPackages.get(packageName); 16176 if (ps == null) { 16177 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16178 + volumeUuid + " because we found no install record"); 16179 destroyApp = true; 16180 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16181 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16182 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16183 destroyApp = true; 16184 } 16185 } 16186 16187 } catch (PackageParserException e) { 16188 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16189 destroyApp = true; 16190 } 16191 16192 if (destroyApp) { 16193 synchronized (mInstallLock) { 16194 if (packageName != null) { 16195 removeDataDirsLI(volumeUuid, packageName); 16196 } 16197 if (file.isDirectory()) { 16198 mInstaller.rmPackageDir(file.getAbsolutePath()); 16199 } else { 16200 file.delete(); 16201 } 16202 } 16203 } 16204 } 16205 } 16206 16207 private void unfreezePackage(String packageName) { 16208 synchronized (mPackages) { 16209 final PackageSetting ps = mSettings.mPackages.get(packageName); 16210 if (ps != null) { 16211 ps.frozen = false; 16212 } 16213 } 16214 } 16215 16216 @Override 16217 public int movePackage(final String packageName, final String volumeUuid) { 16218 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16219 16220 final int moveId = mNextMoveId.getAndIncrement(); 16221 mHandler.post(new Runnable() { 16222 @Override 16223 public void run() { 16224 try { 16225 movePackageInternal(packageName, volumeUuid, moveId); 16226 } catch (PackageManagerException e) { 16227 Slog.w(TAG, "Failed to move " + packageName, e); 16228 mMoveCallbacks.notifyStatusChanged(moveId, 16229 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16230 } 16231 } 16232 }); 16233 return moveId; 16234 } 16235 16236 private void movePackageInternal(final String packageName, final String volumeUuid, 16237 final int moveId) throws PackageManagerException { 16238 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16239 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16240 final PackageManager pm = mContext.getPackageManager(); 16241 16242 final boolean currentAsec; 16243 final String currentVolumeUuid; 16244 final File codeFile; 16245 final String installerPackageName; 16246 final String packageAbiOverride; 16247 final int appId; 16248 final String seinfo; 16249 final String label; 16250 16251 // reader 16252 synchronized (mPackages) { 16253 final PackageParser.Package pkg = mPackages.get(packageName); 16254 final PackageSetting ps = mSettings.mPackages.get(packageName); 16255 if (pkg == null || ps == null) { 16256 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16257 } 16258 16259 if (pkg.applicationInfo.isSystemApp()) { 16260 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16261 "Cannot move system application"); 16262 } 16263 16264 if (pkg.applicationInfo.isExternalAsec()) { 16265 currentAsec = true; 16266 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16267 } else if (pkg.applicationInfo.isForwardLocked()) { 16268 currentAsec = true; 16269 currentVolumeUuid = "forward_locked"; 16270 } else { 16271 currentAsec = false; 16272 currentVolumeUuid = ps.volumeUuid; 16273 16274 final File probe = new File(pkg.codePath); 16275 final File probeOat = new File(probe, "oat"); 16276 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16277 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16278 "Move only supported for modern cluster style installs"); 16279 } 16280 } 16281 16282 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16283 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16284 "Package already moved to " + volumeUuid); 16285 } 16286 16287 if (ps.frozen) { 16288 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16289 "Failed to move already frozen package"); 16290 } 16291 ps.frozen = true; 16292 16293 codeFile = new File(pkg.codePath); 16294 installerPackageName = ps.installerPackageName; 16295 packageAbiOverride = ps.cpuAbiOverrideString; 16296 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16297 seinfo = pkg.applicationInfo.seinfo; 16298 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16299 } 16300 16301 // Now that we're guarded by frozen state, kill app during move 16302 final long token = Binder.clearCallingIdentity(); 16303 try { 16304 killApplication(packageName, appId, "move pkg"); 16305 } finally { 16306 Binder.restoreCallingIdentity(token); 16307 } 16308 16309 final Bundle extras = new Bundle(); 16310 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16311 extras.putString(Intent.EXTRA_TITLE, label); 16312 mMoveCallbacks.notifyCreated(moveId, extras); 16313 16314 int installFlags; 16315 final boolean moveCompleteApp; 16316 final File measurePath; 16317 16318 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16319 installFlags = INSTALL_INTERNAL; 16320 moveCompleteApp = !currentAsec; 16321 measurePath = Environment.getDataAppDirectory(volumeUuid); 16322 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16323 installFlags = INSTALL_EXTERNAL; 16324 moveCompleteApp = false; 16325 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16326 } else { 16327 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16328 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16329 || !volume.isMountedWritable()) { 16330 unfreezePackage(packageName); 16331 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16332 "Move location not mounted private volume"); 16333 } 16334 16335 Preconditions.checkState(!currentAsec); 16336 16337 installFlags = INSTALL_INTERNAL; 16338 moveCompleteApp = true; 16339 measurePath = Environment.getDataAppDirectory(volumeUuid); 16340 } 16341 16342 final PackageStats stats = new PackageStats(null, -1); 16343 synchronized (mInstaller) { 16344 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16345 unfreezePackage(packageName); 16346 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16347 "Failed to measure package size"); 16348 } 16349 } 16350 16351 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16352 + stats.dataSize); 16353 16354 final long startFreeBytes = measurePath.getFreeSpace(); 16355 final long sizeBytes; 16356 if (moveCompleteApp) { 16357 sizeBytes = stats.codeSize + stats.dataSize; 16358 } else { 16359 sizeBytes = stats.codeSize; 16360 } 16361 16362 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16363 unfreezePackage(packageName); 16364 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16365 "Not enough free space to move"); 16366 } 16367 16368 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16369 16370 final CountDownLatch installedLatch = new CountDownLatch(1); 16371 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16372 @Override 16373 public void onUserActionRequired(Intent intent) throws RemoteException { 16374 throw new IllegalStateException(); 16375 } 16376 16377 @Override 16378 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16379 Bundle extras) throws RemoteException { 16380 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16381 + PackageManager.installStatusToString(returnCode, msg)); 16382 16383 installedLatch.countDown(); 16384 16385 // Regardless of success or failure of the move operation, 16386 // always unfreeze the package 16387 unfreezePackage(packageName); 16388 16389 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16390 switch (status) { 16391 case PackageInstaller.STATUS_SUCCESS: 16392 mMoveCallbacks.notifyStatusChanged(moveId, 16393 PackageManager.MOVE_SUCCEEDED); 16394 break; 16395 case PackageInstaller.STATUS_FAILURE_STORAGE: 16396 mMoveCallbacks.notifyStatusChanged(moveId, 16397 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16398 break; 16399 default: 16400 mMoveCallbacks.notifyStatusChanged(moveId, 16401 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16402 break; 16403 } 16404 } 16405 }; 16406 16407 final MoveInfo move; 16408 if (moveCompleteApp) { 16409 // Kick off a thread to report progress estimates 16410 new Thread() { 16411 @Override 16412 public void run() { 16413 while (true) { 16414 try { 16415 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16416 break; 16417 } 16418 } catch (InterruptedException ignored) { 16419 } 16420 16421 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16422 final int progress = 10 + (int) MathUtils.constrain( 16423 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16424 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16425 } 16426 } 16427 }.start(); 16428 16429 final String dataAppName = codeFile.getName(); 16430 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16431 dataAppName, appId, seinfo); 16432 } else { 16433 move = null; 16434 } 16435 16436 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16437 16438 final Message msg = mHandler.obtainMessage(INIT_COPY); 16439 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16440 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16441 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16442 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16443 msg.obj = params; 16444 16445 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16446 System.identityHashCode(msg.obj)); 16447 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16448 System.identityHashCode(msg.obj)); 16449 16450 mHandler.sendMessage(msg); 16451 } 16452 16453 @Override 16454 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16455 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16456 16457 final int realMoveId = mNextMoveId.getAndIncrement(); 16458 final Bundle extras = new Bundle(); 16459 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16460 mMoveCallbacks.notifyCreated(realMoveId, extras); 16461 16462 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16463 @Override 16464 public void onCreated(int moveId, Bundle extras) { 16465 // Ignored 16466 } 16467 16468 @Override 16469 public void onStatusChanged(int moveId, int status, long estMillis) { 16470 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16471 } 16472 }; 16473 16474 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16475 storage.setPrimaryStorageUuid(volumeUuid, callback); 16476 return realMoveId; 16477 } 16478 16479 @Override 16480 public int getMoveStatus(int moveId) { 16481 mContext.enforceCallingOrSelfPermission( 16482 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16483 return mMoveCallbacks.mLastStatus.get(moveId); 16484 } 16485 16486 @Override 16487 public void registerMoveCallback(IPackageMoveObserver callback) { 16488 mContext.enforceCallingOrSelfPermission( 16489 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16490 mMoveCallbacks.register(callback); 16491 } 16492 16493 @Override 16494 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16495 mContext.enforceCallingOrSelfPermission( 16496 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16497 mMoveCallbacks.unregister(callback); 16498 } 16499 16500 @Override 16501 public boolean setInstallLocation(int loc) { 16502 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16503 null); 16504 if (getInstallLocation() == loc) { 16505 return true; 16506 } 16507 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16508 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16509 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16510 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16511 return true; 16512 } 16513 return false; 16514 } 16515 16516 @Override 16517 public int getInstallLocation() { 16518 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16519 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16520 PackageHelper.APP_INSTALL_AUTO); 16521 } 16522 16523 /** Called by UserManagerService */ 16524 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16525 mDirtyUsers.remove(userHandle); 16526 mSettings.removeUserLPw(userHandle); 16527 mPendingBroadcasts.remove(userHandle); 16528 if (mInstaller != null) { 16529 // Technically, we shouldn't be doing this with the package lock 16530 // held. However, this is very rare, and there is already so much 16531 // other disk I/O going on, that we'll let it slide for now. 16532 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16533 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16534 final String volumeUuid = vol.getFsUuid(); 16535 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16536 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16537 } 16538 } 16539 mUserNeedsBadging.delete(userHandle); 16540 removeUnusedPackagesLILPw(userManager, userHandle); 16541 } 16542 16543 /** 16544 * We're removing userHandle and would like to remove any downloaded packages 16545 * that are no longer in use by any other user. 16546 * @param userHandle the user being removed 16547 */ 16548 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16549 final boolean DEBUG_CLEAN_APKS = false; 16550 int [] users = userManager.getUserIds(); 16551 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16552 while (psit.hasNext()) { 16553 PackageSetting ps = psit.next(); 16554 if (ps.pkg == null) { 16555 continue; 16556 } 16557 final String packageName = ps.pkg.packageName; 16558 // Skip over if system app 16559 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16560 continue; 16561 } 16562 if (DEBUG_CLEAN_APKS) { 16563 Slog.i(TAG, "Checking package " + packageName); 16564 } 16565 boolean keep = false; 16566 for (int i = 0; i < users.length; i++) { 16567 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16568 keep = true; 16569 if (DEBUG_CLEAN_APKS) { 16570 Slog.i(TAG, " Keeping package " + packageName + " for user " 16571 + users[i]); 16572 } 16573 break; 16574 } 16575 } 16576 if (!keep) { 16577 if (DEBUG_CLEAN_APKS) { 16578 Slog.i(TAG, " Removing package " + packageName); 16579 } 16580 mHandler.post(new Runnable() { 16581 public void run() { 16582 deletePackageX(packageName, userHandle, 0); 16583 } //end run 16584 }); 16585 } 16586 } 16587 } 16588 16589 /** Called by UserManagerService */ 16590 void createNewUserLILPw(int userHandle) { 16591 if (mInstaller != null) { 16592 mInstaller.createUserConfig(userHandle); 16593 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16594 applyFactoryDefaultBrowserLPw(userHandle); 16595 primeDomainVerificationsLPw(userHandle); 16596 } 16597 } 16598 16599 void newUserCreated(final int userHandle) { 16600 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16601 } 16602 16603 @Override 16604 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16605 mContext.enforceCallingOrSelfPermission( 16606 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16607 "Only package verification agents can read the verifier device identity"); 16608 16609 synchronized (mPackages) { 16610 return mSettings.getVerifierDeviceIdentityLPw(); 16611 } 16612 } 16613 16614 @Override 16615 public void setPermissionEnforced(String permission, boolean enforced) { 16616 // TODO: Now that we no longer change GID for storage, this should to away. 16617 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16618 "setPermissionEnforced"); 16619 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16620 synchronized (mPackages) { 16621 if (mSettings.mReadExternalStorageEnforced == null 16622 || mSettings.mReadExternalStorageEnforced != enforced) { 16623 mSettings.mReadExternalStorageEnforced = enforced; 16624 mSettings.writeLPr(); 16625 } 16626 } 16627 // kill any non-foreground processes so we restart them and 16628 // grant/revoke the GID. 16629 final IActivityManager am = ActivityManagerNative.getDefault(); 16630 if (am != null) { 16631 final long token = Binder.clearCallingIdentity(); 16632 try { 16633 am.killProcessesBelowForeground("setPermissionEnforcement"); 16634 } catch (RemoteException e) { 16635 } finally { 16636 Binder.restoreCallingIdentity(token); 16637 } 16638 } 16639 } else { 16640 throw new IllegalArgumentException("No selective enforcement for " + permission); 16641 } 16642 } 16643 16644 @Override 16645 @Deprecated 16646 public boolean isPermissionEnforced(String permission) { 16647 return true; 16648 } 16649 16650 @Override 16651 public boolean isStorageLow() { 16652 final long token = Binder.clearCallingIdentity(); 16653 try { 16654 final DeviceStorageMonitorInternal 16655 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16656 if (dsm != null) { 16657 return dsm.isMemoryLow(); 16658 } else { 16659 return false; 16660 } 16661 } finally { 16662 Binder.restoreCallingIdentity(token); 16663 } 16664 } 16665 16666 @Override 16667 public IPackageInstaller getPackageInstaller() { 16668 return mInstallerService; 16669 } 16670 16671 private boolean userNeedsBadging(int userId) { 16672 int index = mUserNeedsBadging.indexOfKey(userId); 16673 if (index < 0) { 16674 final UserInfo userInfo; 16675 final long token = Binder.clearCallingIdentity(); 16676 try { 16677 userInfo = sUserManager.getUserInfo(userId); 16678 } finally { 16679 Binder.restoreCallingIdentity(token); 16680 } 16681 final boolean b; 16682 if (userInfo != null && userInfo.isManagedProfile()) { 16683 b = true; 16684 } else { 16685 b = false; 16686 } 16687 mUserNeedsBadging.put(userId, b); 16688 return b; 16689 } 16690 return mUserNeedsBadging.valueAt(index); 16691 } 16692 16693 @Override 16694 public KeySet getKeySetByAlias(String packageName, String alias) { 16695 if (packageName == null || alias == null) { 16696 return null; 16697 } 16698 synchronized(mPackages) { 16699 final PackageParser.Package pkg = mPackages.get(packageName); 16700 if (pkg == null) { 16701 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16702 throw new IllegalArgumentException("Unknown package: " + packageName); 16703 } 16704 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16705 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16706 } 16707 } 16708 16709 @Override 16710 public KeySet getSigningKeySet(String packageName) { 16711 if (packageName == null) { 16712 return null; 16713 } 16714 synchronized(mPackages) { 16715 final PackageParser.Package pkg = mPackages.get(packageName); 16716 if (pkg == null) { 16717 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16718 throw new IllegalArgumentException("Unknown package: " + packageName); 16719 } 16720 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16721 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16722 throw new SecurityException("May not access signing KeySet of other apps."); 16723 } 16724 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16725 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16726 } 16727 } 16728 16729 @Override 16730 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16731 if (packageName == null || ks == null) { 16732 return false; 16733 } 16734 synchronized(mPackages) { 16735 final PackageParser.Package pkg = mPackages.get(packageName); 16736 if (pkg == null) { 16737 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16738 throw new IllegalArgumentException("Unknown package: " + packageName); 16739 } 16740 IBinder ksh = ks.getToken(); 16741 if (ksh instanceof KeySetHandle) { 16742 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16743 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16744 } 16745 return false; 16746 } 16747 } 16748 16749 @Override 16750 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16751 if (packageName == null || ks == null) { 16752 return false; 16753 } 16754 synchronized(mPackages) { 16755 final PackageParser.Package pkg = mPackages.get(packageName); 16756 if (pkg == null) { 16757 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16758 throw new IllegalArgumentException("Unknown package: " + packageName); 16759 } 16760 IBinder ksh = ks.getToken(); 16761 if (ksh instanceof KeySetHandle) { 16762 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16763 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16764 } 16765 return false; 16766 } 16767 } 16768 16769 public void getUsageStatsIfNoPackageUsageInfo() { 16770 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16771 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16772 if (usm == null) { 16773 throw new IllegalStateException("UsageStatsManager must be initialized"); 16774 } 16775 long now = System.currentTimeMillis(); 16776 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16777 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16778 String packageName = entry.getKey(); 16779 PackageParser.Package pkg = mPackages.get(packageName); 16780 if (pkg == null) { 16781 continue; 16782 } 16783 UsageStats usage = entry.getValue(); 16784 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16785 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16786 } 16787 } 16788 } 16789 16790 /** 16791 * Check and throw if the given before/after packages would be considered a 16792 * downgrade. 16793 */ 16794 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16795 throws PackageManagerException { 16796 if (after.versionCode < before.mVersionCode) { 16797 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16798 "Update version code " + after.versionCode + " is older than current " 16799 + before.mVersionCode); 16800 } else if (after.versionCode == before.mVersionCode) { 16801 if (after.baseRevisionCode < before.baseRevisionCode) { 16802 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16803 "Update base revision code " + after.baseRevisionCode 16804 + " is older than current " + before.baseRevisionCode); 16805 } 16806 16807 if (!ArrayUtils.isEmpty(after.splitNames)) { 16808 for (int i = 0; i < after.splitNames.length; i++) { 16809 final String splitName = after.splitNames[i]; 16810 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16811 if (j != -1) { 16812 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16813 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16814 "Update split " + splitName + " revision code " 16815 + after.splitRevisionCodes[i] + " is older than current " 16816 + before.splitRevisionCodes[j]); 16817 } 16818 } 16819 } 16820 } 16821 } 16822 } 16823 16824 private static class MoveCallbacks extends Handler { 16825 private static final int MSG_CREATED = 1; 16826 private static final int MSG_STATUS_CHANGED = 2; 16827 16828 private final RemoteCallbackList<IPackageMoveObserver> 16829 mCallbacks = new RemoteCallbackList<>(); 16830 16831 private final SparseIntArray mLastStatus = new SparseIntArray(); 16832 16833 public MoveCallbacks(Looper looper) { 16834 super(looper); 16835 } 16836 16837 public void register(IPackageMoveObserver callback) { 16838 mCallbacks.register(callback); 16839 } 16840 16841 public void unregister(IPackageMoveObserver callback) { 16842 mCallbacks.unregister(callback); 16843 } 16844 16845 @Override 16846 public void handleMessage(Message msg) { 16847 final SomeArgs args = (SomeArgs) msg.obj; 16848 final int n = mCallbacks.beginBroadcast(); 16849 for (int i = 0; i < n; i++) { 16850 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16851 try { 16852 invokeCallback(callback, msg.what, args); 16853 } catch (RemoteException ignored) { 16854 } 16855 } 16856 mCallbacks.finishBroadcast(); 16857 args.recycle(); 16858 } 16859 16860 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16861 throws RemoteException { 16862 switch (what) { 16863 case MSG_CREATED: { 16864 callback.onCreated(args.argi1, (Bundle) args.arg2); 16865 break; 16866 } 16867 case MSG_STATUS_CHANGED: { 16868 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16869 break; 16870 } 16871 } 16872 } 16873 16874 private void notifyCreated(int moveId, Bundle extras) { 16875 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16876 16877 final SomeArgs args = SomeArgs.obtain(); 16878 args.argi1 = moveId; 16879 args.arg2 = extras; 16880 obtainMessage(MSG_CREATED, args).sendToTarget(); 16881 } 16882 16883 private void notifyStatusChanged(int moveId, int status) { 16884 notifyStatusChanged(moveId, status, -1); 16885 } 16886 16887 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16888 Slog.v(TAG, "Move " + moveId + " status " + status); 16889 16890 final SomeArgs args = SomeArgs.obtain(); 16891 args.argi1 = moveId; 16892 args.argi2 = status; 16893 args.arg3 = estMillis; 16894 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16895 16896 synchronized (mLastStatus) { 16897 mLastStatus.put(moveId, status); 16898 } 16899 } 16900 } 16901 16902 private final class OnPermissionChangeListeners extends Handler { 16903 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16904 16905 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16906 new RemoteCallbackList<>(); 16907 16908 public OnPermissionChangeListeners(Looper looper) { 16909 super(looper); 16910 } 16911 16912 @Override 16913 public void handleMessage(Message msg) { 16914 switch (msg.what) { 16915 case MSG_ON_PERMISSIONS_CHANGED: { 16916 final int uid = msg.arg1; 16917 handleOnPermissionsChanged(uid); 16918 } break; 16919 } 16920 } 16921 16922 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16923 mPermissionListeners.register(listener); 16924 16925 } 16926 16927 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16928 mPermissionListeners.unregister(listener); 16929 } 16930 16931 public void onPermissionsChanged(int uid) { 16932 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16933 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16934 } 16935 } 16936 16937 private void handleOnPermissionsChanged(int uid) { 16938 final int count = mPermissionListeners.beginBroadcast(); 16939 try { 16940 for (int i = 0; i < count; i++) { 16941 IOnPermissionsChangeListener callback = mPermissionListeners 16942 .getBroadcastItem(i); 16943 try { 16944 callback.onPermissionsChanged(uid); 16945 } catch (RemoteException e) { 16946 Log.e(TAG, "Permission listener is dead", e); 16947 } 16948 } 16949 } finally { 16950 mPermissionListeners.finishBroadcast(); 16951 } 16952 } 16953 } 16954 16955 private class PackageManagerInternalImpl extends PackageManagerInternal { 16956 @Override 16957 public void setLocationPackagesProvider(PackagesProvider provider) { 16958 synchronized (mPackages) { 16959 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16960 } 16961 } 16962 16963 @Override 16964 public void setImePackagesProvider(PackagesProvider provider) { 16965 synchronized (mPackages) { 16966 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16967 } 16968 } 16969 16970 @Override 16971 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16972 synchronized (mPackages) { 16973 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16974 } 16975 } 16976 16977 @Override 16978 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16979 synchronized (mPackages) { 16980 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16981 } 16982 } 16983 16984 @Override 16985 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16986 synchronized (mPackages) { 16987 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16988 } 16989 } 16990 16991 @Override 16992 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16993 synchronized (mPackages) { 16994 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16995 } 16996 } 16997 16998 @Override 16999 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17000 synchronized (mPackages) { 17001 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17002 } 17003 } 17004 17005 @Override 17006 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17007 synchronized (mPackages) { 17008 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17009 packageName, userId); 17010 } 17011 } 17012 17013 @Override 17014 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17015 synchronized (mPackages) { 17016 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17017 packageName, userId); 17018 } 17019 } 17020 @Override 17021 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17022 synchronized (mPackages) { 17023 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17024 packageName, userId); 17025 } 17026 } 17027 } 17028 17029 @Override 17030 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17031 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17032 synchronized (mPackages) { 17033 final long identity = Binder.clearCallingIdentity(); 17034 try { 17035 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17036 packageNames, userId); 17037 } finally { 17038 Binder.restoreCallingIdentity(identity); 17039 } 17040 } 17041 } 17042 17043 private static void enforceSystemOrPhoneCaller(String tag) { 17044 int callingUid = Binder.getCallingUid(); 17045 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17046 throw new SecurityException( 17047 "Cannot call " + tag + " from UID " + callingUid); 17048 } 17049 } 17050} 17051