PackageManagerService.java revision 0f4bc2b8002b927290dc84403bb0255e4c4a9079
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.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.FIRST_APPLICATION_UID; 80import static android.os.Process.PACKAGE_INFO_GID; 81import static android.os.Process.SYSTEM_UID; 82import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 83import static android.system.OsConstants.O_CREAT; 84import static android.system.OsConstants.O_RDWR; 85 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 88import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 89import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 90import static com.android.internal.util.ArrayUtils.appendInt; 91import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 92import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 95import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 96import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 102 103import android.Manifest; 104import android.annotation.NonNull; 105import android.annotation.Nullable; 106import android.app.ActivityManager; 107import android.app.ActivityManagerNative; 108import android.app.IActivityManager; 109import android.app.admin.DevicePolicyManagerInternal; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentFilter.AuthorityEntry; 120import android.content.IntentSender; 121import android.content.IntentSender.SendIntentException; 122import android.content.ServiceConnection; 123import android.content.pm.ActivityInfo; 124import android.content.pm.ApplicationInfo; 125import android.content.pm.AppsQueryHelper; 126import android.content.pm.ComponentInfo; 127import android.content.pm.EphemeralApplicationInfo; 128import android.content.pm.EphemeralResolveInfo; 129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 130import android.content.pm.FeatureInfo; 131import android.content.pm.IOnPermissionsChangeListener; 132import android.content.pm.IPackageDataObserver; 133import android.content.pm.IPackageDeleteObserver; 134import android.content.pm.IPackageDeleteObserver2; 135import android.content.pm.IPackageInstallObserver2; 136import android.content.pm.IPackageInstaller; 137import android.content.pm.IPackageManager; 138import android.content.pm.IPackageMoveObserver; 139import android.content.pm.IPackageStatsObserver; 140import android.content.pm.InstrumentationInfo; 141import android.content.pm.IntentFilterVerificationInfo; 142import android.content.pm.KeySet; 143import android.content.pm.PackageCleanItem; 144import android.content.pm.PackageInfo; 145import android.content.pm.PackageInfoLite; 146import android.content.pm.PackageInstaller; 147import android.content.pm.PackageManager; 148import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 149import android.content.pm.PackageManagerInternal; 150import android.content.pm.PackageParser; 151import android.content.pm.PackageParser.ActivityIntentInfo; 152import android.content.pm.PackageParser.IntentInfo; 153import android.content.pm.PackageParser.PackageLite; 154import android.content.pm.PackageParser.PackageParserException; 155import android.content.pm.PackageStats; 156import android.content.pm.PackageUserState; 157import android.content.pm.ParceledListSlice; 158import android.content.pm.PermissionGroupInfo; 159import android.content.pm.PermissionInfo; 160import android.content.pm.ProviderInfo; 161import android.content.pm.ResolveInfo; 162import android.content.pm.ServiceInfo; 163import android.content.pm.Signature; 164import android.content.pm.UserInfo; 165import android.content.pm.VerifierDeviceIdentity; 166import android.content.pm.VerifierInfo; 167import android.content.res.Resources; 168import android.graphics.Bitmap; 169import android.hardware.display.DisplayManager; 170import android.net.Uri; 171import android.os.Binder; 172import android.os.Build; 173import android.os.Bundle; 174import android.os.Debug; 175import android.os.Environment; 176import android.os.Environment.UserEnvironment; 177import android.os.FileUtils; 178import android.os.Handler; 179import android.os.IBinder; 180import android.os.Looper; 181import android.os.Message; 182import android.os.Parcel; 183import android.os.ParcelFileDescriptor; 184import android.os.Process; 185import android.os.RemoteCallbackList; 186import android.os.RemoteException; 187import android.os.ResultReceiver; 188import android.os.SELinux; 189import android.os.ServiceManager; 190import android.os.SystemClock; 191import android.os.SystemProperties; 192import android.os.Trace; 193import android.os.UserHandle; 194import android.os.UserManager; 195import android.os.storage.IMountService; 196import android.os.storage.MountServiceInternal; 197import android.os.storage.StorageEventListener; 198import android.os.storage.StorageManager; 199import android.os.storage.VolumeInfo; 200import android.os.storage.VolumeRecord; 201import android.security.KeyStore; 202import android.security.SystemKeyStore; 203import android.system.ErrnoException; 204import android.system.Os; 205import android.text.TextUtils; 206import android.text.format.DateUtils; 207import android.util.ArrayMap; 208import android.util.ArraySet; 209import android.util.AtomicFile; 210import android.util.DisplayMetrics; 211import android.util.EventLog; 212import android.util.ExceptionUtils; 213import android.util.Log; 214import android.util.LogPrinter; 215import android.util.MathUtils; 216import android.util.PrintStreamPrinter; 217import android.util.Slog; 218import android.util.SparseArray; 219import android.util.SparseBooleanArray; 220import android.util.SparseIntArray; 221import android.util.Xml; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.os.IParcelFileDescriptorFactory; 231import com.android.internal.os.InstallerConnection.InstallerException; 232import com.android.internal.os.SomeArgs; 233import com.android.internal.os.Zygote; 234import com.android.internal.util.ArrayUtils; 235import com.android.internal.util.FastPrintWriter; 236import com.android.internal.util.FastXmlSerializer; 237import com.android.internal.util.IndentingPrintWriter; 238import com.android.internal.util.Preconditions; 239import com.android.internal.util.XmlUtils; 240import com.android.server.EventLogTags; 241import com.android.server.FgThread; 242import com.android.server.IntentResolver; 243import com.android.server.LocalServices; 244import com.android.server.ServiceThread; 245import com.android.server.SystemConfig; 246import com.android.server.Watchdog; 247import com.android.server.pm.PermissionsState.PermissionState; 248import com.android.server.pm.Settings.DatabaseVersion; 249import com.android.server.pm.Settings.VersionInfo; 250import com.android.server.storage.DeviceStorageMonitorInternal; 251 252import dalvik.system.DexFile; 253import dalvik.system.VMRuntime; 254 255import libcore.io.IoUtils; 256import libcore.util.EmptyArray; 257 258import org.xmlpull.v1.XmlPullParser; 259import org.xmlpull.v1.XmlPullParserException; 260import org.xmlpull.v1.XmlSerializer; 261 262import java.io.BufferedInputStream; 263import java.io.BufferedOutputStream; 264import java.io.BufferedReader; 265import java.io.ByteArrayInputStream; 266import java.io.ByteArrayOutputStream; 267import java.io.File; 268import java.io.FileDescriptor; 269import java.io.FileNotFoundException; 270import java.io.FileOutputStream; 271import java.io.FileReader; 272import java.io.FilenameFilter; 273import java.io.IOException; 274import java.io.InputStream; 275import java.io.PrintWriter; 276import java.nio.charset.StandardCharsets; 277import java.security.MessageDigest; 278import java.security.NoSuchAlgorithmException; 279import java.security.PublicKey; 280import java.security.cert.CertificateEncodingException; 281import java.security.cert.CertificateException; 282import java.text.SimpleDateFormat; 283import java.util.ArrayList; 284import java.util.Arrays; 285import java.util.Collection; 286import java.util.Collections; 287import java.util.Comparator; 288import java.util.Date; 289import java.util.HashSet; 290import java.util.Iterator; 291import java.util.List; 292import java.util.Map; 293import java.util.Objects; 294import java.util.Set; 295import java.util.concurrent.CountDownLatch; 296import java.util.concurrent.TimeUnit; 297import java.util.concurrent.atomic.AtomicBoolean; 298import java.util.concurrent.atomic.AtomicInteger; 299import java.util.concurrent.atomic.AtomicLong; 300 301/** 302 * Keep track of all those .apks everywhere. 303 * 304 * This is very central to the platform's security; please run the unit 305 * tests whenever making modifications here: 306 * 307runtest -c android.content.pm.PackageManagerTests frameworks-core 308 * 309 * {@hide} 310 */ 311public class PackageManagerService extends IPackageManager.Stub { 312 static final String TAG = "PackageManager"; 313 static final boolean DEBUG_SETTINGS = false; 314 static final boolean DEBUG_PREFERRED = false; 315 static final boolean DEBUG_UPGRADE = false; 316 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 317 private static final boolean DEBUG_BACKUP = false; 318 private static final boolean DEBUG_INSTALL = false; 319 private static final boolean DEBUG_REMOVE = false; 320 private static final boolean DEBUG_BROADCASTS = false; 321 private static final boolean DEBUG_SHOW_INFO = false; 322 private static final boolean DEBUG_PACKAGE_INFO = false; 323 private static final boolean DEBUG_INTENT_MATCHING = false; 324 private static final boolean DEBUG_PACKAGE_SCANNING = false; 325 private static final boolean DEBUG_VERIFY = false; 326 private static final boolean DEBUG_FILTERS = false; 327 328 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 329 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 330 // user, but by default initialize to this. 331 static final boolean DEBUG_DEXOPT = false; 332 333 private static final boolean DEBUG_ABI_SELECTION = false; 334 private static final boolean DEBUG_EPHEMERAL = false; 335 private static final boolean DEBUG_TRIAGED_MISSING = false; 336 private static final boolean DEBUG_APP_DATA = false; 337 338 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 339 340 private static final boolean DISABLE_EPHEMERAL_APPS = true; 341 342 private static final int RADIO_UID = Process.PHONE_UID; 343 private static final int LOG_UID = Process.LOG_UID; 344 private static final int NFC_UID = Process.NFC_UID; 345 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 346 private static final int SHELL_UID = Process.SHELL_UID; 347 348 // Cap the size of permission trees that 3rd party apps can define 349 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 350 351 // Suffix used during package installation when copying/moving 352 // package apks to install directory. 353 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 354 355 static final int SCAN_NO_DEX = 1<<1; 356 static final int SCAN_FORCE_DEX = 1<<2; 357 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 358 static final int SCAN_NEW_INSTALL = 1<<4; 359 static final int SCAN_NO_PATHS = 1<<5; 360 static final int SCAN_UPDATE_TIME = 1<<6; 361 static final int SCAN_DEFER_DEX = 1<<7; 362 static final int SCAN_BOOTING = 1<<8; 363 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 364 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 365 static final int SCAN_REPLACING = 1<<11; 366 static final int SCAN_REQUIRE_KNOWN = 1<<12; 367 static final int SCAN_MOVE = 1<<13; 368 static final int SCAN_INITIAL = 1<<14; 369 static final int SCAN_CHECK_ONLY = 1<<15; 370 static final int SCAN_DONT_KILL_APP = 1<<17; 371 372 static final int REMOVE_CHATTY = 1<<16; 373 374 private static final int[] EMPTY_INT_ARRAY = new int[0]; 375 376 /** 377 * Timeout (in milliseconds) after which the watchdog should declare that 378 * our handler thread is wedged. The usual default for such things is one 379 * minute but we sometimes do very lengthy I/O operations on this thread, 380 * such as installing multi-gigabyte applications, so ours needs to be longer. 381 */ 382 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 383 384 /** 385 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 386 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 387 * settings entry if available, otherwise we use the hardcoded default. If it's been 388 * more than this long since the last fstrim, we force one during the boot sequence. 389 * 390 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 391 * one gets run at the next available charging+idle time. This final mandatory 392 * no-fstrim check kicks in only of the other scheduling criteria is never met. 393 */ 394 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 395 396 /** 397 * Whether verification is enabled by default. 398 */ 399 private static final boolean DEFAULT_VERIFY_ENABLE = true; 400 401 /** 402 * The default maximum time to wait for the verification agent to return in 403 * milliseconds. 404 */ 405 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 406 407 /** 408 * The default response for package verification timeout. 409 * 410 * This can be either PackageManager.VERIFICATION_ALLOW or 411 * PackageManager.VERIFICATION_REJECT. 412 */ 413 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 414 415 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 416 417 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 418 DEFAULT_CONTAINER_PACKAGE, 419 "com.android.defcontainer.DefaultContainerService"); 420 421 private static final String KILL_APP_REASON_GIDS_CHANGED = 422 "permission grant or revoke changed gids"; 423 424 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 425 "permissions revoked"; 426 427 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 428 429 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 430 431 /** Permission grant: not grant the permission. */ 432 private static final int GRANT_DENIED = 1; 433 434 /** Permission grant: grant the permission as an install permission. */ 435 private static final int GRANT_INSTALL = 2; 436 437 /** Permission grant: grant the permission as a runtime one. */ 438 private static final int GRANT_RUNTIME = 3; 439 440 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 441 private static final int GRANT_UPGRADE = 4; 442 443 /** Canonical intent used to identify what counts as a "web browser" app */ 444 private static final Intent sBrowserIntent; 445 static { 446 sBrowserIntent = new Intent(); 447 sBrowserIntent.setAction(Intent.ACTION_VIEW); 448 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 449 sBrowserIntent.setData(Uri.parse("http:")); 450 } 451 452 /** 453 * The set of all protected actions [i.e. those actions for which a high priority 454 * intent filter is disallowed]. 455 */ 456 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 457 static { 458 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 459 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 460 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 461 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 462 } 463 464 // Compilation reasons. 465 public static final int REASON_FIRST_BOOT = 0; 466 public static final int REASON_BOOT = 1; 467 public static final int REASON_INSTALL = 2; 468 public static final int REASON_BACKGROUND_DEXOPT = 3; 469 public static final int REASON_AB_OTA = 4; 470 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 471 public static final int REASON_SHARED_APK = 6; 472 public static final int REASON_FORCED_DEXOPT = 7; 473 474 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 475 476 final ServiceThread mHandlerThread; 477 478 final PackageHandler mHandler; 479 480 private final ProcessLoggingHandler mProcessLoggingHandler; 481 482 /** 483 * Messages for {@link #mHandler} that need to wait for system ready before 484 * being dispatched. 485 */ 486 private ArrayList<Message> mPostSystemReadyMessages; 487 488 final int mSdkVersion = Build.VERSION.SDK_INT; 489 490 final Context mContext; 491 final boolean mFactoryTest; 492 final boolean mOnlyCore; 493 final DisplayMetrics mMetrics; 494 final int mDefParseFlags; 495 final String[] mSeparateProcesses; 496 final boolean mIsUpgrade; 497 final boolean mIsPreNUpgrade; 498 499 /** The location for ASEC container files on internal storage. */ 500 final String mAsecInternalPath; 501 502 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 503 // LOCK HELD. Can be called with mInstallLock held. 504 @GuardedBy("mInstallLock") 505 final Installer mInstaller; 506 507 /** Directory where installed third-party apps stored */ 508 final File mAppInstallDir; 509 final File mEphemeralInstallDir; 510 511 /** 512 * Directory to which applications installed internally have their 513 * 32 bit native libraries copied. 514 */ 515 private File mAppLib32InstallDir; 516 517 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 518 // apps. 519 final File mDrmAppPrivateInstallDir; 520 521 // ---------------------------------------------------------------- 522 523 // Lock for state used when installing and doing other long running 524 // operations. Methods that must be called with this lock held have 525 // the suffix "LI". 526 final Object mInstallLock = new Object(); 527 528 // ---------------------------------------------------------------- 529 530 // Keys are String (package name), values are Package. This also serves 531 // as the lock for the global state. Methods that must be called with 532 // this lock held have the prefix "LP". 533 @GuardedBy("mPackages") 534 final ArrayMap<String, PackageParser.Package> mPackages = 535 new ArrayMap<String, PackageParser.Package>(); 536 537 final ArrayMap<String, Set<String>> mKnownCodebase = 538 new ArrayMap<String, Set<String>>(); 539 540 // Tracks available target package names -> overlay package paths. 541 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 542 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 543 544 /** 545 * Tracks new system packages [received in an OTA] that we expect to 546 * find updated user-installed versions. Keys are package name, values 547 * are package location. 548 */ 549 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 550 /** 551 * Tracks high priority intent filters for protected actions. During boot, certain 552 * filter actions are protected and should never be allowed to have a high priority 553 * intent filter for them. However, there is one, and only one exception -- the 554 * setup wizard. It must be able to define a high priority intent filter for these 555 * actions to ensure there are no escapes from the wizard. We need to delay processing 556 * of these during boot as we need to look at all of the system packages in order 557 * to know which component is the setup wizard. 558 */ 559 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 560 /** 561 * Whether or not processing protected filters should be deferred. 562 */ 563 private boolean mDeferProtectedFilters = true; 564 565 /** 566 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 567 */ 568 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 569 /** 570 * Whether or not system app permissions should be promoted from install to runtime. 571 */ 572 boolean mPromoteSystemApps; 573 574 final Settings mSettings; 575 boolean mRestoredSettings; 576 577 // System configuration read by SystemConfig. 578 final int[] mGlobalGids; 579 final SparseArray<ArraySet<String>> mSystemPermissions; 580 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 581 582 // If mac_permissions.xml was found for seinfo labeling. 583 boolean mFoundPolicyFile; 584 585 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 586 587 public static final class SharedLibraryEntry { 588 public final String path; 589 public final String apk; 590 591 SharedLibraryEntry(String _path, String _apk) { 592 path = _path; 593 apk = _apk; 594 } 595 } 596 597 // Currently known shared libraries. 598 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 599 new ArrayMap<String, SharedLibraryEntry>(); 600 601 // All available activities, for your resolving pleasure. 602 final ActivityIntentResolver mActivities = 603 new ActivityIntentResolver(); 604 605 // All available receivers, for your resolving pleasure. 606 final ActivityIntentResolver mReceivers = 607 new ActivityIntentResolver(); 608 609 // All available services, for your resolving pleasure. 610 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 611 612 // All available providers, for your resolving pleasure. 613 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 614 615 // Mapping from provider base names (first directory in content URI codePath) 616 // to the provider information. 617 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 618 new ArrayMap<String, PackageParser.Provider>(); 619 620 // Mapping from instrumentation class names to info about them. 621 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 622 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 623 624 // Mapping from permission names to info about them. 625 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 626 new ArrayMap<String, PackageParser.PermissionGroup>(); 627 628 // Packages whose data we have transfered into another package, thus 629 // should no longer exist. 630 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 631 632 // Broadcast actions that are only available to the system. 633 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 634 635 /** List of packages waiting for verification. */ 636 final SparseArray<PackageVerificationState> mPendingVerification 637 = new SparseArray<PackageVerificationState>(); 638 639 /** Set of packages associated with each app op permission. */ 640 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 641 642 final PackageInstallerService mInstallerService; 643 644 private final PackageDexOptimizer mPackageDexOptimizer; 645 646 private AtomicInteger mNextMoveId = new AtomicInteger(); 647 private final MoveCallbacks mMoveCallbacks; 648 649 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 650 651 // Cache of users who need badging. 652 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 653 654 /** Token for keys in mPendingVerification. */ 655 private int mPendingVerificationToken = 0; 656 657 volatile boolean mSystemReady; 658 volatile boolean mSafeMode; 659 volatile boolean mHasSystemUidErrors; 660 661 ApplicationInfo mAndroidApplication; 662 final ActivityInfo mResolveActivity = new ActivityInfo(); 663 final ResolveInfo mResolveInfo = new ResolveInfo(); 664 ComponentName mResolveComponentName; 665 PackageParser.Package mPlatformPackage; 666 ComponentName mCustomResolverComponentName; 667 668 boolean mResolverReplaced = false; 669 670 private final @Nullable ComponentName mIntentFilterVerifierComponent; 671 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 672 673 private int mIntentFilterVerificationToken = 0; 674 675 /** Component that knows whether or not an ephemeral application exists */ 676 final ComponentName mEphemeralResolverComponent; 677 /** The service connection to the ephemeral resolver */ 678 final EphemeralResolverConnection mEphemeralResolverConnection; 679 680 /** Component used to install ephemeral applications */ 681 final ComponentName mEphemeralInstallerComponent; 682 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 683 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 684 685 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 686 = new SparseArray<IntentFilterVerificationState>(); 687 688 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 689 new DefaultPermissionGrantPolicy(this); 690 691 // List of packages names to keep cached, even if they are uninstalled for all users 692 private List<String> mKeepUninstalledPackages; 693 694 private static class IFVerificationParams { 695 PackageParser.Package pkg; 696 boolean replacing; 697 int userId; 698 int verifierUid; 699 700 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 701 int _userId, int _verifierUid) { 702 pkg = _pkg; 703 replacing = _replacing; 704 userId = _userId; 705 replacing = _replacing; 706 verifierUid = _verifierUid; 707 } 708 } 709 710 private interface IntentFilterVerifier<T extends IntentFilter> { 711 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 712 T filter, String packageName); 713 void startVerifications(int userId); 714 void receiveVerificationResponse(int verificationId); 715 } 716 717 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 718 private Context mContext; 719 private ComponentName mIntentFilterVerifierComponent; 720 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 721 722 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 723 mContext = context; 724 mIntentFilterVerifierComponent = verifierComponent; 725 } 726 727 private String getDefaultScheme() { 728 return IntentFilter.SCHEME_HTTPS; 729 } 730 731 @Override 732 public void startVerifications(int userId) { 733 // Launch verifications requests 734 int count = mCurrentIntentFilterVerifications.size(); 735 for (int n=0; n<count; n++) { 736 int verificationId = mCurrentIntentFilterVerifications.get(n); 737 final IntentFilterVerificationState ivs = 738 mIntentFilterVerificationStates.get(verificationId); 739 740 String packageName = ivs.getPackageName(); 741 742 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 743 final int filterCount = filters.size(); 744 ArraySet<String> domainsSet = new ArraySet<>(); 745 for (int m=0; m<filterCount; m++) { 746 PackageParser.ActivityIntentInfo filter = filters.get(m); 747 domainsSet.addAll(filter.getHostsList()); 748 } 749 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 750 synchronized (mPackages) { 751 if (mSettings.createIntentFilterVerificationIfNeededLPw( 752 packageName, domainsList) != null) { 753 scheduleWriteSettingsLocked(); 754 } 755 } 756 sendVerificationRequest(userId, verificationId, ivs); 757 } 758 mCurrentIntentFilterVerifications.clear(); 759 } 760 761 private void sendVerificationRequest(int userId, int verificationId, 762 IntentFilterVerificationState ivs) { 763 764 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 765 verificationIntent.putExtra( 766 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 767 verificationId); 768 verificationIntent.putExtra( 769 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 770 getDefaultScheme()); 771 verificationIntent.putExtra( 772 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 773 ivs.getHostsString()); 774 verificationIntent.putExtra( 775 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 776 ivs.getPackageName()); 777 verificationIntent.setComponent(mIntentFilterVerifierComponent); 778 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 779 780 UserHandle user = new UserHandle(userId); 781 mContext.sendBroadcastAsUser(verificationIntent, user); 782 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 783 "Sending IntentFilter verification broadcast"); 784 } 785 786 public void receiveVerificationResponse(int verificationId) { 787 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 788 789 final boolean verified = ivs.isVerified(); 790 791 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 792 final int count = filters.size(); 793 if (DEBUG_DOMAIN_VERIFICATION) { 794 Slog.i(TAG, "Received verification response " + verificationId 795 + " for " + count + " filters, verified=" + verified); 796 } 797 for (int n=0; n<count; n++) { 798 PackageParser.ActivityIntentInfo filter = filters.get(n); 799 filter.setVerified(verified); 800 801 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 802 + " verified with result:" + verified + " and hosts:" 803 + ivs.getHostsString()); 804 } 805 806 mIntentFilterVerificationStates.remove(verificationId); 807 808 final String packageName = ivs.getPackageName(); 809 IntentFilterVerificationInfo ivi = null; 810 811 synchronized (mPackages) { 812 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 813 } 814 if (ivi == null) { 815 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 816 + verificationId + " packageName:" + packageName); 817 return; 818 } 819 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 820 "Updating IntentFilterVerificationInfo for package " + packageName 821 +" verificationId:" + verificationId); 822 823 synchronized (mPackages) { 824 if (verified) { 825 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 826 } else { 827 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 828 } 829 scheduleWriteSettingsLocked(); 830 831 final int userId = ivs.getUserId(); 832 if (userId != UserHandle.USER_ALL) { 833 final int userStatus = 834 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 835 836 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 837 boolean needUpdate = false; 838 839 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 840 // already been set by the User thru the Disambiguation dialog 841 switch (userStatus) { 842 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 843 if (verified) { 844 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 845 } else { 846 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 847 } 848 needUpdate = true; 849 break; 850 851 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 852 if (verified) { 853 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 854 needUpdate = true; 855 } 856 break; 857 858 default: 859 // Nothing to do 860 } 861 862 if (needUpdate) { 863 mSettings.updateIntentFilterVerificationStatusLPw( 864 packageName, updatedStatus, userId); 865 scheduleWritePackageRestrictionsLocked(userId); 866 } 867 } 868 } 869 } 870 871 @Override 872 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 873 ActivityIntentInfo filter, String packageName) { 874 if (!hasValidDomains(filter)) { 875 return false; 876 } 877 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 878 if (ivs == null) { 879 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 880 packageName); 881 } 882 if (DEBUG_DOMAIN_VERIFICATION) { 883 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 884 } 885 ivs.addFilter(filter); 886 return true; 887 } 888 889 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 890 int userId, int verificationId, String packageName) { 891 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 892 verifierUid, userId, packageName); 893 ivs.setPendingState(); 894 synchronized (mPackages) { 895 mIntentFilterVerificationStates.append(verificationId, ivs); 896 mCurrentIntentFilterVerifications.add(verificationId); 897 } 898 return ivs; 899 } 900 } 901 902 private static boolean hasValidDomains(ActivityIntentInfo filter) { 903 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 904 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 905 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 906 } 907 908 // Set of pending broadcasts for aggregating enable/disable of components. 909 static class PendingPackageBroadcasts { 910 // for each user id, a map of <package name -> components within that package> 911 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 912 913 public PendingPackageBroadcasts() { 914 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 915 } 916 917 public ArrayList<String> get(int userId, String packageName) { 918 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 919 return packages.get(packageName); 920 } 921 922 public void put(int userId, String packageName, ArrayList<String> components) { 923 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 924 packages.put(packageName, components); 925 } 926 927 public void remove(int userId, String packageName) { 928 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 929 if (packages != null) { 930 packages.remove(packageName); 931 } 932 } 933 934 public void remove(int userId) { 935 mUidMap.remove(userId); 936 } 937 938 public int userIdCount() { 939 return mUidMap.size(); 940 } 941 942 public int userIdAt(int n) { 943 return mUidMap.keyAt(n); 944 } 945 946 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 947 return mUidMap.get(userId); 948 } 949 950 public int size() { 951 // total number of pending broadcast entries across all userIds 952 int num = 0; 953 for (int i = 0; i< mUidMap.size(); i++) { 954 num += mUidMap.valueAt(i).size(); 955 } 956 return num; 957 } 958 959 public void clear() { 960 mUidMap.clear(); 961 } 962 963 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 964 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 965 if (map == null) { 966 map = new ArrayMap<String, ArrayList<String>>(); 967 mUidMap.put(userId, map); 968 } 969 return map; 970 } 971 } 972 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 973 974 // Service Connection to remote media container service to copy 975 // package uri's from external media onto secure containers 976 // or internal storage. 977 private IMediaContainerService mContainerService = null; 978 979 static final int SEND_PENDING_BROADCAST = 1; 980 static final int MCS_BOUND = 3; 981 static final int END_COPY = 4; 982 static final int INIT_COPY = 5; 983 static final int MCS_UNBIND = 6; 984 static final int START_CLEANING_PACKAGE = 7; 985 static final int FIND_INSTALL_LOC = 8; 986 static final int POST_INSTALL = 9; 987 static final int MCS_RECONNECT = 10; 988 static final int MCS_GIVE_UP = 11; 989 static final int UPDATED_MEDIA_STATUS = 12; 990 static final int WRITE_SETTINGS = 13; 991 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 992 static final int PACKAGE_VERIFIED = 15; 993 static final int CHECK_PENDING_VERIFICATION = 16; 994 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 995 static final int INTENT_FILTER_VERIFIED = 18; 996 997 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 998 999 // Delay time in millisecs 1000 static final int BROADCAST_DELAY = 10 * 1000; 1001 1002 static UserManagerService sUserManager; 1003 1004 // Stores a list of users whose package restrictions file needs to be updated 1005 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1006 1007 final private DefaultContainerConnection mDefContainerConn = 1008 new DefaultContainerConnection(); 1009 class DefaultContainerConnection implements ServiceConnection { 1010 public void onServiceConnected(ComponentName name, IBinder service) { 1011 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1012 IMediaContainerService imcs = 1013 IMediaContainerService.Stub.asInterface(service); 1014 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1015 } 1016 1017 public void onServiceDisconnected(ComponentName name) { 1018 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1019 } 1020 } 1021 1022 // Recordkeeping of restore-after-install operations that are currently in flight 1023 // between the Package Manager and the Backup Manager 1024 static class PostInstallData { 1025 public InstallArgs args; 1026 public PackageInstalledInfo res; 1027 1028 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1029 args = _a; 1030 res = _r; 1031 } 1032 } 1033 1034 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1035 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1036 1037 // XML tags for backup/restore of various bits of state 1038 private static final String TAG_PREFERRED_BACKUP = "pa"; 1039 private static final String TAG_DEFAULT_APPS = "da"; 1040 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1041 1042 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1043 private static final String TAG_ALL_GRANTS = "rt-grants"; 1044 private static final String TAG_GRANT = "grant"; 1045 private static final String ATTR_PACKAGE_NAME = "pkg"; 1046 1047 private static final String TAG_PERMISSION = "perm"; 1048 private static final String ATTR_PERMISSION_NAME = "name"; 1049 private static final String ATTR_IS_GRANTED = "g"; 1050 private static final String ATTR_USER_SET = "set"; 1051 private static final String ATTR_USER_FIXED = "fixed"; 1052 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1053 1054 // System/policy permission grants are not backed up 1055 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1056 FLAG_PERMISSION_POLICY_FIXED 1057 | FLAG_PERMISSION_SYSTEM_FIXED 1058 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1059 1060 // And we back up these user-adjusted states 1061 private static final int USER_RUNTIME_GRANT_MASK = 1062 FLAG_PERMISSION_USER_SET 1063 | FLAG_PERMISSION_USER_FIXED 1064 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1065 1066 final @Nullable String mRequiredVerifierPackage; 1067 final @Nullable String mRequiredInstallerPackage; 1068 final @Nullable String mSetupWizardPackage; 1069 1070 private final PackageUsage mPackageUsage = new PackageUsage(); 1071 1072 private class PackageUsage { 1073 private static final int WRITE_INTERVAL 1074 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1075 1076 private final Object mFileLock = new Object(); 1077 private final AtomicLong mLastWritten = new AtomicLong(0); 1078 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1079 1080 private boolean mIsHistoricalPackageUsageAvailable = true; 1081 1082 boolean isHistoricalPackageUsageAvailable() { 1083 return mIsHistoricalPackageUsageAvailable; 1084 } 1085 1086 void write(boolean force) { 1087 if (force) { 1088 writeInternal(); 1089 return; 1090 } 1091 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1092 && !DEBUG_DEXOPT) { 1093 return; 1094 } 1095 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1096 new Thread("PackageUsage_DiskWriter") { 1097 @Override 1098 public void run() { 1099 try { 1100 writeInternal(); 1101 } finally { 1102 mBackgroundWriteRunning.set(false); 1103 } 1104 } 1105 }.start(); 1106 } 1107 } 1108 1109 private void writeInternal() { 1110 synchronized (mPackages) { 1111 synchronized (mFileLock) { 1112 AtomicFile file = getFile(); 1113 FileOutputStream f = null; 1114 try { 1115 f = file.startWrite(); 1116 BufferedOutputStream out = new BufferedOutputStream(f); 1117 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1118 StringBuilder sb = new StringBuilder(); 1119 for (PackageParser.Package pkg : mPackages.values()) { 1120 if (pkg.mLastPackageUsageTimeInMills == 0) { 1121 continue; 1122 } 1123 sb.setLength(0); 1124 sb.append(pkg.packageName); 1125 sb.append(' '); 1126 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1127 sb.append('\n'); 1128 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1129 } 1130 out.flush(); 1131 file.finishWrite(f); 1132 } catch (IOException e) { 1133 if (f != null) { 1134 file.failWrite(f); 1135 } 1136 Log.e(TAG, "Failed to write package usage times", e); 1137 } 1138 } 1139 } 1140 mLastWritten.set(SystemClock.elapsedRealtime()); 1141 } 1142 1143 void readLP() { 1144 synchronized (mFileLock) { 1145 AtomicFile file = getFile(); 1146 BufferedInputStream in = null; 1147 try { 1148 in = new BufferedInputStream(file.openRead()); 1149 StringBuffer sb = new StringBuffer(); 1150 while (true) { 1151 String packageName = readToken(in, sb, ' '); 1152 if (packageName == null) { 1153 break; 1154 } 1155 String timeInMillisString = readToken(in, sb, '\n'); 1156 if (timeInMillisString == null) { 1157 throw new IOException("Failed to find last usage time for package " 1158 + packageName); 1159 } 1160 PackageParser.Package pkg = mPackages.get(packageName); 1161 if (pkg == null) { 1162 continue; 1163 } 1164 long timeInMillis; 1165 try { 1166 timeInMillis = Long.parseLong(timeInMillisString); 1167 } catch (NumberFormatException e) { 1168 throw new IOException("Failed to parse " + timeInMillisString 1169 + " as a long.", e); 1170 } 1171 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1172 } 1173 } catch (FileNotFoundException expected) { 1174 mIsHistoricalPackageUsageAvailable = false; 1175 } catch (IOException e) { 1176 Log.w(TAG, "Failed to read package usage times", e); 1177 } finally { 1178 IoUtils.closeQuietly(in); 1179 } 1180 } 1181 mLastWritten.set(SystemClock.elapsedRealtime()); 1182 } 1183 1184 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1185 throws IOException { 1186 sb.setLength(0); 1187 while (true) { 1188 int ch = in.read(); 1189 if (ch == -1) { 1190 if (sb.length() == 0) { 1191 return null; 1192 } 1193 throw new IOException("Unexpected EOF"); 1194 } 1195 if (ch == endOfToken) { 1196 return sb.toString(); 1197 } 1198 sb.append((char)ch); 1199 } 1200 } 1201 1202 private AtomicFile getFile() { 1203 File dataDir = Environment.getDataDirectory(); 1204 File systemDir = new File(dataDir, "system"); 1205 File fname = new File(systemDir, "package-usage.list"); 1206 return new AtomicFile(fname); 1207 } 1208 } 1209 1210 class PackageHandler extends Handler { 1211 private boolean mBound = false; 1212 final ArrayList<HandlerParams> mPendingInstalls = 1213 new ArrayList<HandlerParams>(); 1214 1215 private boolean connectToService() { 1216 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1217 " DefaultContainerService"); 1218 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1219 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1220 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1221 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1222 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1223 mBound = true; 1224 return true; 1225 } 1226 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1227 return false; 1228 } 1229 1230 private void disconnectService() { 1231 mContainerService = null; 1232 mBound = false; 1233 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1234 mContext.unbindService(mDefContainerConn); 1235 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1236 } 1237 1238 PackageHandler(Looper looper) { 1239 super(looper); 1240 } 1241 1242 public void handleMessage(Message msg) { 1243 try { 1244 doHandleMessage(msg); 1245 } finally { 1246 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1247 } 1248 } 1249 1250 void doHandleMessage(Message msg) { 1251 switch (msg.what) { 1252 case INIT_COPY: { 1253 HandlerParams params = (HandlerParams) msg.obj; 1254 int idx = mPendingInstalls.size(); 1255 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1256 // If a bind was already initiated we dont really 1257 // need to do anything. The pending install 1258 // will be processed later on. 1259 if (!mBound) { 1260 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1261 System.identityHashCode(mHandler)); 1262 // If this is the only one pending we might 1263 // have to bind to the service again. 1264 if (!connectToService()) { 1265 Slog.e(TAG, "Failed to bind to media container service"); 1266 params.serviceError(); 1267 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1268 System.identityHashCode(mHandler)); 1269 if (params.traceMethod != null) { 1270 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1271 params.traceCookie); 1272 } 1273 return; 1274 } else { 1275 // Once we bind to the service, the first 1276 // pending request will be processed. 1277 mPendingInstalls.add(idx, params); 1278 } 1279 } else { 1280 mPendingInstalls.add(idx, params); 1281 // Already bound to the service. Just make 1282 // sure we trigger off processing the first request. 1283 if (idx == 0) { 1284 mHandler.sendEmptyMessage(MCS_BOUND); 1285 } 1286 } 1287 break; 1288 } 1289 case MCS_BOUND: { 1290 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1291 if (msg.obj != null) { 1292 mContainerService = (IMediaContainerService) msg.obj; 1293 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1294 System.identityHashCode(mHandler)); 1295 } 1296 if (mContainerService == null) { 1297 if (!mBound) { 1298 // Something seriously wrong since we are not bound and we are not 1299 // waiting for connection. Bail out. 1300 Slog.e(TAG, "Cannot bind to media container service"); 1301 for (HandlerParams params : mPendingInstalls) { 1302 // Indicate service bind error 1303 params.serviceError(); 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1305 System.identityHashCode(params)); 1306 if (params.traceMethod != null) { 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1308 params.traceMethod, params.traceCookie); 1309 } 1310 return; 1311 } 1312 mPendingInstalls.clear(); 1313 } else { 1314 Slog.w(TAG, "Waiting to connect to media container service"); 1315 } 1316 } else if (mPendingInstalls.size() > 0) { 1317 HandlerParams params = mPendingInstalls.get(0); 1318 if (params != null) { 1319 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1320 System.identityHashCode(params)); 1321 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1322 if (params.startCopy()) { 1323 // We are done... look for more work or to 1324 // go idle. 1325 if (DEBUG_SD_INSTALL) Log.i(TAG, 1326 "Checking for more work or unbind..."); 1327 // Delete pending install 1328 if (mPendingInstalls.size() > 0) { 1329 mPendingInstalls.remove(0); 1330 } 1331 if (mPendingInstalls.size() == 0) { 1332 if (mBound) { 1333 if (DEBUG_SD_INSTALL) Log.i(TAG, 1334 "Posting delayed MCS_UNBIND"); 1335 removeMessages(MCS_UNBIND); 1336 Message ubmsg = obtainMessage(MCS_UNBIND); 1337 // Unbind after a little delay, to avoid 1338 // continual thrashing. 1339 sendMessageDelayed(ubmsg, 10000); 1340 } 1341 } else { 1342 // There are more pending requests in queue. 1343 // Just post MCS_BOUND message to trigger processing 1344 // of next pending install. 1345 if (DEBUG_SD_INSTALL) Log.i(TAG, 1346 "Posting MCS_BOUND for next work"); 1347 mHandler.sendEmptyMessage(MCS_BOUND); 1348 } 1349 } 1350 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1351 } 1352 } else { 1353 // Should never happen ideally. 1354 Slog.w(TAG, "Empty queue"); 1355 } 1356 break; 1357 } 1358 case MCS_RECONNECT: { 1359 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1360 if (mPendingInstalls.size() > 0) { 1361 if (mBound) { 1362 disconnectService(); 1363 } 1364 if (!connectToService()) { 1365 Slog.e(TAG, "Failed to bind to media container service"); 1366 for (HandlerParams params : mPendingInstalls) { 1367 // Indicate service bind error 1368 params.serviceError(); 1369 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1370 System.identityHashCode(params)); 1371 } 1372 mPendingInstalls.clear(); 1373 } 1374 } 1375 break; 1376 } 1377 case MCS_UNBIND: { 1378 // If there is no actual work left, then time to unbind. 1379 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1380 1381 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1382 if (mBound) { 1383 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1384 1385 disconnectService(); 1386 } 1387 } else if (mPendingInstalls.size() > 0) { 1388 // There are more pending requests in queue. 1389 // Just post MCS_BOUND message to trigger processing 1390 // of next pending install. 1391 mHandler.sendEmptyMessage(MCS_BOUND); 1392 } 1393 1394 break; 1395 } 1396 case MCS_GIVE_UP: { 1397 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1398 HandlerParams params = mPendingInstalls.remove(0); 1399 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1400 System.identityHashCode(params)); 1401 break; 1402 } 1403 case SEND_PENDING_BROADCAST: { 1404 String packages[]; 1405 ArrayList<String> components[]; 1406 int size = 0; 1407 int uids[]; 1408 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1409 synchronized (mPackages) { 1410 if (mPendingBroadcasts == null) { 1411 return; 1412 } 1413 size = mPendingBroadcasts.size(); 1414 if (size <= 0) { 1415 // Nothing to be done. Just return 1416 return; 1417 } 1418 packages = new String[size]; 1419 components = new ArrayList[size]; 1420 uids = new int[size]; 1421 int i = 0; // filling out the above arrays 1422 1423 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1424 int packageUserId = mPendingBroadcasts.userIdAt(n); 1425 Iterator<Map.Entry<String, ArrayList<String>>> it 1426 = mPendingBroadcasts.packagesForUserId(packageUserId) 1427 .entrySet().iterator(); 1428 while (it.hasNext() && i < size) { 1429 Map.Entry<String, ArrayList<String>> ent = it.next(); 1430 packages[i] = ent.getKey(); 1431 components[i] = ent.getValue(); 1432 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1433 uids[i] = (ps != null) 1434 ? UserHandle.getUid(packageUserId, ps.appId) 1435 : -1; 1436 i++; 1437 } 1438 } 1439 size = i; 1440 mPendingBroadcasts.clear(); 1441 } 1442 // Send broadcasts 1443 for (int i = 0; i < size; i++) { 1444 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1445 } 1446 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1447 break; 1448 } 1449 case START_CLEANING_PACKAGE: { 1450 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1451 final String packageName = (String)msg.obj; 1452 final int userId = msg.arg1; 1453 final boolean andCode = msg.arg2 != 0; 1454 synchronized (mPackages) { 1455 if (userId == UserHandle.USER_ALL) { 1456 int[] users = sUserManager.getUserIds(); 1457 for (int user : users) { 1458 mSettings.addPackageToCleanLPw( 1459 new PackageCleanItem(user, packageName, andCode)); 1460 } 1461 } else { 1462 mSettings.addPackageToCleanLPw( 1463 new PackageCleanItem(userId, packageName, andCode)); 1464 } 1465 } 1466 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1467 startCleaningPackages(); 1468 } break; 1469 case POST_INSTALL: { 1470 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1471 1472 PostInstallData data = mRunningInstalls.get(msg.arg1); 1473 mRunningInstalls.delete(msg.arg1); 1474 1475 if (data != null) { 1476 InstallArgs args = data.args; 1477 PackageInstalledInfo parentRes = data.res; 1478 1479 final boolean grantPermissions = (args.installFlags 1480 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1481 final boolean killApp = (args.installFlags 1482 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1483 final String[] grantedPermissions = args.installGrantPermissions; 1484 1485 // Handle the parent package 1486 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1487 grantedPermissions, args.observer); 1488 1489 // Handle the child packages 1490 final int childCount = (parentRes.addedChildPackages != null) 1491 ? parentRes.addedChildPackages.size() : 0; 1492 for (int i = 0; i < childCount; i++) { 1493 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1494 handlePackagePostInstall(childRes, grantPermissions, killApp, 1495 grantedPermissions, args.observer); 1496 } 1497 1498 // Log tracing if needed 1499 if (args.traceMethod != null) { 1500 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1501 args.traceCookie); 1502 } 1503 } else { 1504 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1505 } 1506 1507 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1508 } break; 1509 case UPDATED_MEDIA_STATUS: { 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1511 boolean reportStatus = msg.arg1 == 1; 1512 boolean doGc = msg.arg2 == 1; 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1514 if (doGc) { 1515 // Force a gc to clear up stale containers. 1516 Runtime.getRuntime().gc(); 1517 } 1518 if (msg.obj != null) { 1519 @SuppressWarnings("unchecked") 1520 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1521 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1522 // Unload containers 1523 unloadAllContainers(args); 1524 } 1525 if (reportStatus) { 1526 try { 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1528 PackageHelper.getMountService().finishMediaUpdate(); 1529 } catch (RemoteException e) { 1530 Log.e(TAG, "MountService not running?"); 1531 } 1532 } 1533 } break; 1534 case WRITE_SETTINGS: { 1535 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1536 synchronized (mPackages) { 1537 removeMessages(WRITE_SETTINGS); 1538 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1539 mSettings.writeLPr(); 1540 mDirtyUsers.clear(); 1541 } 1542 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1543 } break; 1544 case WRITE_PACKAGE_RESTRICTIONS: { 1545 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1546 synchronized (mPackages) { 1547 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1548 for (int userId : mDirtyUsers) { 1549 mSettings.writePackageRestrictionsLPr(userId); 1550 } 1551 mDirtyUsers.clear(); 1552 } 1553 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1554 } break; 1555 case CHECK_PENDING_VERIFICATION: { 1556 final int verificationId = msg.arg1; 1557 final PackageVerificationState state = mPendingVerification.get(verificationId); 1558 1559 if ((state != null) && !state.timeoutExtended()) { 1560 final InstallArgs args = state.getInstallArgs(); 1561 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1562 1563 Slog.i(TAG, "Verification timed out for " + originUri); 1564 mPendingVerification.remove(verificationId); 1565 1566 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1567 1568 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1569 Slog.i(TAG, "Continuing with installation of " + originUri); 1570 state.setVerifierResponse(Binder.getCallingUid(), 1571 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1572 broadcastPackageVerified(verificationId, originUri, 1573 PackageManager.VERIFICATION_ALLOW, 1574 state.getInstallArgs().getUser()); 1575 try { 1576 ret = args.copyApk(mContainerService, true); 1577 } catch (RemoteException e) { 1578 Slog.e(TAG, "Could not contact the ContainerService"); 1579 } 1580 } else { 1581 broadcastPackageVerified(verificationId, originUri, 1582 PackageManager.VERIFICATION_REJECT, 1583 state.getInstallArgs().getUser()); 1584 } 1585 1586 Trace.asyncTraceEnd( 1587 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1588 1589 processPendingInstall(args, ret); 1590 mHandler.sendEmptyMessage(MCS_UNBIND); 1591 } 1592 break; 1593 } 1594 case PACKAGE_VERIFIED: { 1595 final int verificationId = msg.arg1; 1596 1597 final PackageVerificationState state = mPendingVerification.get(verificationId); 1598 if (state == null) { 1599 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1600 break; 1601 } 1602 1603 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1604 1605 state.setVerifierResponse(response.callerUid, response.code); 1606 1607 if (state.isVerificationComplete()) { 1608 mPendingVerification.remove(verificationId); 1609 1610 final InstallArgs args = state.getInstallArgs(); 1611 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1612 1613 int ret; 1614 if (state.isInstallAllowed()) { 1615 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1616 broadcastPackageVerified(verificationId, originUri, 1617 response.code, state.getInstallArgs().getUser()); 1618 try { 1619 ret = args.copyApk(mContainerService, true); 1620 } catch (RemoteException e) { 1621 Slog.e(TAG, "Could not contact the ContainerService"); 1622 } 1623 } else { 1624 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1625 } 1626 1627 Trace.asyncTraceEnd( 1628 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1629 1630 processPendingInstall(args, ret); 1631 mHandler.sendEmptyMessage(MCS_UNBIND); 1632 } 1633 1634 break; 1635 } 1636 case START_INTENT_FILTER_VERIFICATIONS: { 1637 IFVerificationParams params = (IFVerificationParams) msg.obj; 1638 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1639 params.replacing, params.pkg); 1640 break; 1641 } 1642 case INTENT_FILTER_VERIFIED: { 1643 final int verificationId = msg.arg1; 1644 1645 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1646 verificationId); 1647 if (state == null) { 1648 Slog.w(TAG, "Invalid IntentFilter verification token " 1649 + verificationId + " received"); 1650 break; 1651 } 1652 1653 final int userId = state.getUserId(); 1654 1655 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1656 "Processing IntentFilter verification with token:" 1657 + verificationId + " and userId:" + userId); 1658 1659 final IntentFilterVerificationResponse response = 1660 (IntentFilterVerificationResponse) msg.obj; 1661 1662 state.setVerifierResponse(response.callerUid, response.code); 1663 1664 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1665 "IntentFilter verification with token:" + verificationId 1666 + " and userId:" + userId 1667 + " is settings verifier response with response code:" 1668 + response.code); 1669 1670 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1671 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1672 + response.getFailedDomainsString()); 1673 } 1674 1675 if (state.isVerificationComplete()) { 1676 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1677 } else { 1678 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1679 "IntentFilter verification with token:" + verificationId 1680 + " was not said to be complete"); 1681 } 1682 1683 break; 1684 } 1685 } 1686 } 1687 } 1688 1689 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1690 boolean killApp, String[] grantedPermissions, 1691 IPackageInstallObserver2 installObserver) { 1692 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1693 // Send the removed broadcasts 1694 if (res.removedInfo != null) { 1695 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1696 } 1697 1698 // Now that we successfully installed the package, grant runtime 1699 // permissions if requested before broadcasting the install. 1700 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1701 >= Build.VERSION_CODES.M) { 1702 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1703 } 1704 1705 final boolean update = res.removedInfo != null 1706 && res.removedInfo.removedPackage != null; 1707 1708 // If this is the first time we have child packages for a disabled privileged 1709 // app that had no children, we grant requested runtime permissions to the new 1710 // children if the parent on the system image had them already granted. 1711 if (res.pkg.parentPackage != null) { 1712 synchronized (mPackages) { 1713 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1714 } 1715 } 1716 1717 synchronized (mPackages) { 1718 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1719 } 1720 1721 final String packageName = res.pkg.applicationInfo.packageName; 1722 Bundle extras = new Bundle(1); 1723 extras.putInt(Intent.EXTRA_UID, res.uid); 1724 1725 // Determine the set of users who are adding this package for 1726 // the first time vs. those who are seeing an update. 1727 int[] firstUsers = EMPTY_INT_ARRAY; 1728 int[] updateUsers = EMPTY_INT_ARRAY; 1729 if (res.origUsers == null || res.origUsers.length == 0) { 1730 firstUsers = res.newUsers; 1731 } else { 1732 for (int newUser : res.newUsers) { 1733 boolean isNew = true; 1734 for (int origUser : res.origUsers) { 1735 if (origUser == newUser) { 1736 isNew = false; 1737 break; 1738 } 1739 } 1740 if (isNew) { 1741 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1742 } else { 1743 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1744 } 1745 } 1746 } 1747 1748 // Send installed broadcasts if the install/update is not ephemeral 1749 if (!isEphemeral(res.pkg)) { 1750 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1751 1752 // Send added for users that see the package for the first time 1753 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1754 extras, 0 /*flags*/, null /*targetPackage*/, 1755 null /*finishedReceiver*/, firstUsers); 1756 1757 // Send added for users that don't see the package for the first time 1758 if (update) { 1759 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1760 } 1761 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1762 extras, 0 /*flags*/, null /*targetPackage*/, 1763 null /*finishedReceiver*/, updateUsers); 1764 1765 // Send replaced for users that don't see the package for the first time 1766 if (update) { 1767 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1768 packageName, extras, 0 /*flags*/, 1769 null /*targetPackage*/, null /*finishedReceiver*/, 1770 updateUsers); 1771 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1772 null /*package*/, null /*extras*/, 0 /*flags*/, 1773 packageName /*targetPackage*/, 1774 null /*finishedReceiver*/, updateUsers); 1775 } 1776 1777 // Send broadcast package appeared if forward locked/external for all users 1778 // treat asec-hosted packages like removable media on upgrade 1779 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1780 if (DEBUG_INSTALL) { 1781 Slog.i(TAG, "upgrading pkg " + res.pkg 1782 + " is ASEC-hosted -> AVAILABLE"); 1783 } 1784 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1785 ArrayList<String> pkgList = new ArrayList<>(1); 1786 pkgList.add(packageName); 1787 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1788 } 1789 } 1790 1791 // Work that needs to happen on first install within each user 1792 if (firstUsers != null && firstUsers.length > 0) { 1793 synchronized (mPackages) { 1794 for (int userId : firstUsers) { 1795 // If this app is a browser and it's newly-installed for some 1796 // users, clear any default-browser state in those users. The 1797 // app's nature doesn't depend on the user, so we can just check 1798 // its browser nature in any user and generalize. 1799 if (packageIsBrowser(packageName, userId)) { 1800 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1801 } 1802 1803 // We may also need to apply pending (restored) runtime 1804 // permission grants within these users. 1805 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1806 } 1807 } 1808 } 1809 1810 // Log current value of "unknown sources" setting 1811 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1812 getUnknownSourcesSettings()); 1813 1814 // Force a gc to clear up things 1815 Runtime.getRuntime().gc(); 1816 1817 // Remove the replaced package's older resources safely now 1818 // We delete after a gc for applications on sdcard. 1819 if (res.removedInfo != null && res.removedInfo.args != null) { 1820 synchronized (mInstallLock) { 1821 res.removedInfo.args.doPostDeleteLI(true); 1822 } 1823 } 1824 } 1825 1826 // If someone is watching installs - notify them 1827 if (installObserver != null) { 1828 try { 1829 Bundle extras = extrasForInstallResult(res); 1830 installObserver.onPackageInstalled(res.name, res.returnCode, 1831 res.returnMsg, extras); 1832 } catch (RemoteException e) { 1833 Slog.i(TAG, "Observer no longer exists."); 1834 } 1835 } 1836 } 1837 1838 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1839 PackageParser.Package pkg) { 1840 if (pkg.parentPackage == null) { 1841 return; 1842 } 1843 if (pkg.requestedPermissions == null) { 1844 return; 1845 } 1846 final PackageSetting disabledSysParentPs = mSettings 1847 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1848 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1849 || !disabledSysParentPs.isPrivileged() 1850 || (disabledSysParentPs.childPackageNames != null 1851 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1852 return; 1853 } 1854 final int[] allUserIds = sUserManager.getUserIds(); 1855 final int permCount = pkg.requestedPermissions.size(); 1856 for (int i = 0; i < permCount; i++) { 1857 String permission = pkg.requestedPermissions.get(i); 1858 BasePermission bp = mSettings.mPermissions.get(permission); 1859 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1860 continue; 1861 } 1862 for (int userId : allUserIds) { 1863 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1864 permission, userId)) { 1865 grantRuntimePermission(pkg.packageName, permission, userId); 1866 } 1867 } 1868 } 1869 } 1870 1871 private StorageEventListener mStorageListener = new StorageEventListener() { 1872 @Override 1873 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1874 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1875 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1876 final String volumeUuid = vol.getFsUuid(); 1877 1878 // Clean up any users or apps that were removed or recreated 1879 // while this volume was missing 1880 reconcileUsers(volumeUuid); 1881 reconcileApps(volumeUuid); 1882 1883 // Clean up any install sessions that expired or were 1884 // cancelled while this volume was missing 1885 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1886 1887 loadPrivatePackages(vol); 1888 1889 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1890 unloadPrivatePackages(vol); 1891 } 1892 } 1893 1894 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1895 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1896 updateExternalMediaStatus(true, false); 1897 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1898 updateExternalMediaStatus(false, false); 1899 } 1900 } 1901 } 1902 1903 @Override 1904 public void onVolumeForgotten(String fsUuid) { 1905 if (TextUtils.isEmpty(fsUuid)) { 1906 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1907 return; 1908 } 1909 1910 // Remove any apps installed on the forgotten volume 1911 synchronized (mPackages) { 1912 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1913 for (PackageSetting ps : packages) { 1914 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1915 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1916 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1917 } 1918 1919 mSettings.onVolumeForgotten(fsUuid); 1920 mSettings.writeLPr(); 1921 } 1922 } 1923 }; 1924 1925 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1926 String[] grantedPermissions) { 1927 for (int userId : userIds) { 1928 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1929 } 1930 1931 // We could have touched GID membership, so flush out packages.list 1932 synchronized (mPackages) { 1933 mSettings.writePackageListLPr(); 1934 } 1935 } 1936 1937 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1938 String[] grantedPermissions) { 1939 SettingBase sb = (SettingBase) pkg.mExtras; 1940 if (sb == null) { 1941 return; 1942 } 1943 1944 PermissionsState permissionsState = sb.getPermissionsState(); 1945 1946 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1947 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1948 1949 synchronized (mPackages) { 1950 for (String permission : pkg.requestedPermissions) { 1951 BasePermission bp = mSettings.mPermissions.get(permission); 1952 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1953 && (grantedPermissions == null 1954 || ArrayUtils.contains(grantedPermissions, permission))) { 1955 final int flags = permissionsState.getPermissionFlags(permission, userId); 1956 // Installer cannot change immutable permissions. 1957 if ((flags & immutableFlags) == 0) { 1958 grantRuntimePermission(pkg.packageName, permission, userId); 1959 } 1960 } 1961 } 1962 } 1963 } 1964 1965 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1966 Bundle extras = null; 1967 switch (res.returnCode) { 1968 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1969 extras = new Bundle(); 1970 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1971 res.origPermission); 1972 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1973 res.origPackage); 1974 break; 1975 } 1976 case PackageManager.INSTALL_SUCCEEDED: { 1977 extras = new Bundle(); 1978 extras.putBoolean(Intent.EXTRA_REPLACING, 1979 res.removedInfo != null && res.removedInfo.removedPackage != null); 1980 break; 1981 } 1982 } 1983 return extras; 1984 } 1985 1986 void scheduleWriteSettingsLocked() { 1987 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1988 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1989 } 1990 } 1991 1992 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1993 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1994 scheduleWritePackageRestrictionsLocked(userId); 1995 } 1996 1997 void scheduleWritePackageRestrictionsLocked(int userId) { 1998 final int[] userIds = (userId == UserHandle.USER_ALL) 1999 ? sUserManager.getUserIds() : new int[]{userId}; 2000 for (int nextUserId : userIds) { 2001 if (!sUserManager.exists(nextUserId)) return; 2002 mDirtyUsers.add(nextUserId); 2003 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2004 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2005 } 2006 } 2007 } 2008 2009 public static PackageManagerService main(Context context, Installer installer, 2010 boolean factoryTest, boolean onlyCore) { 2011 // Self-check for initial settings. 2012 PackageManagerServiceCompilerMapping.checkProperties(); 2013 2014 PackageManagerService m = new PackageManagerService(context, installer, 2015 factoryTest, onlyCore); 2016 m.enableSystemUserPackages(); 2017 ServiceManager.addService("package", m); 2018 return m; 2019 } 2020 2021 private void enableSystemUserPackages() { 2022 if (!UserManager.isSplitSystemUser()) { 2023 return; 2024 } 2025 // For system user, enable apps based on the following conditions: 2026 // - app is whitelisted or belong to one of these groups: 2027 // -- system app which has no launcher icons 2028 // -- system app which has INTERACT_ACROSS_USERS permission 2029 // -- system IME app 2030 // - app is not in the blacklist 2031 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2032 Set<String> enableApps = new ArraySet<>(); 2033 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2034 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2035 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2036 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2037 enableApps.addAll(wlApps); 2038 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2039 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2040 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2041 enableApps.removeAll(blApps); 2042 Log.i(TAG, "Applications installed for system user: " + enableApps); 2043 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2044 UserHandle.SYSTEM); 2045 final int allAppsSize = allAps.size(); 2046 synchronized (mPackages) { 2047 for (int i = 0; i < allAppsSize; i++) { 2048 String pName = allAps.get(i); 2049 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2050 // Should not happen, but we shouldn't be failing if it does 2051 if (pkgSetting == null) { 2052 continue; 2053 } 2054 boolean install = enableApps.contains(pName); 2055 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2056 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2057 + " for system user"); 2058 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2059 } 2060 } 2061 } 2062 } 2063 2064 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2065 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2066 Context.DISPLAY_SERVICE); 2067 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2068 } 2069 2070 public PackageManagerService(Context context, Installer installer, 2071 boolean factoryTest, boolean onlyCore) { 2072 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2073 SystemClock.uptimeMillis()); 2074 2075 if (mSdkVersion <= 0) { 2076 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2077 } 2078 2079 mContext = context; 2080 mFactoryTest = factoryTest; 2081 mOnlyCore = onlyCore; 2082 mMetrics = new DisplayMetrics(); 2083 mSettings = new Settings(mPackages); 2084 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2085 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2086 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2087 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2088 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2089 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2090 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2091 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2092 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2093 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2094 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2095 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2096 2097 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2098 if (separateProcesses != null && separateProcesses.length() > 0) { 2099 if ("*".equals(separateProcesses)) { 2100 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2101 mSeparateProcesses = null; 2102 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2103 } else { 2104 mDefParseFlags = 0; 2105 mSeparateProcesses = separateProcesses.split(","); 2106 Slog.w(TAG, "Running with debug.separate_processes: " 2107 + separateProcesses); 2108 } 2109 } else { 2110 mDefParseFlags = 0; 2111 mSeparateProcesses = null; 2112 } 2113 2114 mInstaller = installer; 2115 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2116 "*dexopt*"); 2117 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2118 2119 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2120 FgThread.get().getLooper()); 2121 2122 getDefaultDisplayMetrics(context, mMetrics); 2123 2124 SystemConfig systemConfig = SystemConfig.getInstance(); 2125 mGlobalGids = systemConfig.getGlobalGids(); 2126 mSystemPermissions = systemConfig.getSystemPermissions(); 2127 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2128 2129 synchronized (mInstallLock) { 2130 // writer 2131 synchronized (mPackages) { 2132 mHandlerThread = new ServiceThread(TAG, 2133 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2134 mHandlerThread.start(); 2135 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2136 mProcessLoggingHandler = new ProcessLoggingHandler(); 2137 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2138 2139 File dataDir = Environment.getDataDirectory(); 2140 mAppInstallDir = new File(dataDir, "app"); 2141 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2142 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2143 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2144 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2145 2146 sUserManager = new UserManagerService(context, this, mPackages); 2147 2148 // Propagate permission configuration in to package manager. 2149 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2150 = systemConfig.getPermissions(); 2151 for (int i=0; i<permConfig.size(); i++) { 2152 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2153 BasePermission bp = mSettings.mPermissions.get(perm.name); 2154 if (bp == null) { 2155 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2156 mSettings.mPermissions.put(perm.name, bp); 2157 } 2158 if (perm.gids != null) { 2159 bp.setGids(perm.gids, perm.perUser); 2160 } 2161 } 2162 2163 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2164 for (int i=0; i<libConfig.size(); i++) { 2165 mSharedLibraries.put(libConfig.keyAt(i), 2166 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2167 } 2168 2169 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2170 2171 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2172 2173 String customResolverActivity = Resources.getSystem().getString( 2174 R.string.config_customResolverActivity); 2175 if (TextUtils.isEmpty(customResolverActivity)) { 2176 customResolverActivity = null; 2177 } else { 2178 mCustomResolverComponentName = ComponentName.unflattenFromString( 2179 customResolverActivity); 2180 } 2181 2182 long startTime = SystemClock.uptimeMillis(); 2183 2184 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2185 startTime); 2186 2187 // Set flag to monitor and not change apk file paths when 2188 // scanning install directories. 2189 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2190 2191 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2192 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2193 2194 if (bootClassPath == null) { 2195 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2196 } 2197 2198 if (systemServerClassPath == null) { 2199 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2200 } 2201 2202 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2203 final String[] dexCodeInstructionSets = 2204 getDexCodeInstructionSets( 2205 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2206 2207 /** 2208 * Ensure all external libraries have had dexopt run on them. 2209 */ 2210 if (mSharedLibraries.size() > 0) { 2211 // NOTE: For now, we're compiling these system "shared libraries" 2212 // (and framework jars) into all available architectures. It's possible 2213 // to compile them only when we come across an app that uses them (there's 2214 // already logic for that in scanPackageLI) but that adds some complexity. 2215 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2216 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2217 final String lib = libEntry.path; 2218 if (lib == null) { 2219 continue; 2220 } 2221 2222 try { 2223 // Shared libraries do not have profiles so we perform a full 2224 // AOT compilation (if needed). 2225 int dexoptNeeded = DexFile.getDexOptNeeded( 2226 lib, dexCodeInstructionSet, 2227 getCompilerFilterForReason(REASON_SHARED_APK), 2228 false /* newProfile */); 2229 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2230 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2231 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2232 getCompilerFilterForReason(REASON_SHARED_APK), 2233 StorageManager.UUID_PRIVATE_INTERNAL); 2234 } 2235 } catch (FileNotFoundException e) { 2236 Slog.w(TAG, "Library not found: " + lib); 2237 } catch (IOException | InstallerException e) { 2238 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2239 + e.getMessage()); 2240 } 2241 } 2242 } 2243 } 2244 2245 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2246 2247 final VersionInfo ver = mSettings.getInternalVersion(); 2248 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2249 2250 // when upgrading from pre-M, promote system app permissions from install to runtime 2251 mPromoteSystemApps = 2252 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2253 2254 // save off the names of pre-existing system packages prior to scanning; we don't 2255 // want to automatically grant runtime permissions for new system apps 2256 if (mPromoteSystemApps) { 2257 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2258 while (pkgSettingIter.hasNext()) { 2259 PackageSetting ps = pkgSettingIter.next(); 2260 if (isSystemApp(ps)) { 2261 mExistingSystemPackages.add(ps.name); 2262 } 2263 } 2264 } 2265 2266 // When upgrading from pre-N, we need to handle package extraction like first boot, 2267 // as there is no profiling data available. 2268 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2269 mSettings.setNWorkDone(); 2270 2271 // Collect vendor overlay packages. 2272 // (Do this before scanning any apps.) 2273 // For security and version matching reason, only consider 2274 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2275 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2276 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2278 2279 // Find base frameworks (resource packages without code). 2280 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2281 | PackageParser.PARSE_IS_SYSTEM_DIR 2282 | PackageParser.PARSE_IS_PRIVILEGED, 2283 scanFlags | SCAN_NO_DEX, 0); 2284 2285 // Collected privileged system packages. 2286 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2287 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2288 | PackageParser.PARSE_IS_SYSTEM_DIR 2289 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2290 2291 // Collect ordinary system packages. 2292 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2293 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2294 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2295 2296 // Collect all vendor packages. 2297 File vendorAppDir = new File("/vendor/app"); 2298 try { 2299 vendorAppDir = vendorAppDir.getCanonicalFile(); 2300 } catch (IOException e) { 2301 // failed to look up canonical path, continue with original one 2302 } 2303 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2304 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2305 2306 // Collect all OEM packages. 2307 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2308 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2309 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2310 2311 // Prune any system packages that no longer exist. 2312 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2313 if (!mOnlyCore) { 2314 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2315 while (psit.hasNext()) { 2316 PackageSetting ps = psit.next(); 2317 2318 /* 2319 * If this is not a system app, it can't be a 2320 * disable system app. 2321 */ 2322 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2323 continue; 2324 } 2325 2326 /* 2327 * If the package is scanned, it's not erased. 2328 */ 2329 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2330 if (scannedPkg != null) { 2331 /* 2332 * If the system app is both scanned and in the 2333 * disabled packages list, then it must have been 2334 * added via OTA. Remove it from the currently 2335 * scanned package so the previously user-installed 2336 * application can be scanned. 2337 */ 2338 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2339 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2340 + ps.name + "; removing system app. Last known codePath=" 2341 + ps.codePathString + ", installStatus=" + ps.installStatus 2342 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2343 + scannedPkg.mVersionCode); 2344 removePackageLI(scannedPkg, true); 2345 mExpectingBetter.put(ps.name, ps.codePath); 2346 } 2347 2348 continue; 2349 } 2350 2351 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2352 psit.remove(); 2353 logCriticalInfo(Log.WARN, "System package " + ps.name 2354 + " no longer exists; wiping its data"); 2355 removeDataDirsLI(null, ps.name); 2356 } else { 2357 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2358 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2359 possiblyDeletedUpdatedSystemApps.add(ps.name); 2360 } 2361 } 2362 } 2363 } 2364 2365 //look for any incomplete package installations 2366 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2367 //clean up list 2368 for(int i = 0; i < deletePkgsList.size(); i++) { 2369 //clean up here 2370 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2371 } 2372 //delete tmp files 2373 deleteTempPackageFiles(); 2374 2375 // Remove any shared userIDs that have no associated packages 2376 mSettings.pruneSharedUsersLPw(); 2377 2378 if (!mOnlyCore) { 2379 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2380 SystemClock.uptimeMillis()); 2381 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2382 2383 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2384 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2385 2386 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2387 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2388 2389 /** 2390 * Remove disable package settings for any updated system 2391 * apps that were removed via an OTA. If they're not a 2392 * previously-updated app, remove them completely. 2393 * Otherwise, just revoke their system-level permissions. 2394 */ 2395 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2396 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2397 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2398 2399 String msg; 2400 if (deletedPkg == null) { 2401 msg = "Updated system package " + deletedAppName 2402 + " no longer exists; wiping its data"; 2403 removeDataDirsLI(null, deletedAppName); 2404 } else { 2405 msg = "Updated system app + " + deletedAppName 2406 + " no longer present; removing system privileges for " 2407 + deletedAppName; 2408 2409 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2410 2411 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2412 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2413 } 2414 logCriticalInfo(Log.WARN, msg); 2415 } 2416 2417 /** 2418 * Make sure all system apps that we expected to appear on 2419 * the userdata partition actually showed up. If they never 2420 * appeared, crawl back and revive the system version. 2421 */ 2422 for (int i = 0; i < mExpectingBetter.size(); i++) { 2423 final String packageName = mExpectingBetter.keyAt(i); 2424 if (!mPackages.containsKey(packageName)) { 2425 final File scanFile = mExpectingBetter.valueAt(i); 2426 2427 logCriticalInfo(Log.WARN, "Expected better " + packageName 2428 + " but never showed up; reverting to system"); 2429 2430 final int reparseFlags; 2431 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2432 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2433 | PackageParser.PARSE_IS_SYSTEM_DIR 2434 | PackageParser.PARSE_IS_PRIVILEGED; 2435 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2436 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2437 | PackageParser.PARSE_IS_SYSTEM_DIR; 2438 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2439 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2440 | PackageParser.PARSE_IS_SYSTEM_DIR; 2441 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2442 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2443 | PackageParser.PARSE_IS_SYSTEM_DIR; 2444 } else { 2445 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2446 continue; 2447 } 2448 2449 mSettings.enableSystemPackageLPw(packageName); 2450 2451 try { 2452 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2453 } catch (PackageManagerException e) { 2454 Slog.e(TAG, "Failed to parse original system package: " 2455 + e.getMessage()); 2456 } 2457 } 2458 } 2459 } 2460 mExpectingBetter.clear(); 2461 2462 // Resolve protected action filters. Only the setup wizard is allowed to 2463 // have a high priority filter for these actions. 2464 mSetupWizardPackage = getSetupWizardPackageName(); 2465 if (mProtectedFilters.size() > 0) { 2466 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2467 Slog.i(TAG, "No setup wizard;" 2468 + " All protected intents capped to priority 0"); 2469 } 2470 for (ActivityIntentInfo filter : mProtectedFilters) { 2471 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2472 if (DEBUG_FILTERS) { 2473 Slog.i(TAG, "Found setup wizard;" 2474 + " allow priority " + filter.getPriority() + ";" 2475 + " package: " + filter.activity.info.packageName 2476 + " activity: " + filter.activity.className 2477 + " priority: " + filter.getPriority()); 2478 } 2479 // skip setup wizard; allow it to keep the high priority filter 2480 continue; 2481 } 2482 Slog.w(TAG, "Protected action; cap priority to 0;" 2483 + " package: " + filter.activity.info.packageName 2484 + " activity: " + filter.activity.className 2485 + " origPrio: " + filter.getPriority()); 2486 filter.setPriority(0); 2487 } 2488 } 2489 mDeferProtectedFilters = false; 2490 mProtectedFilters.clear(); 2491 2492 // Now that we know all of the shared libraries, update all clients to have 2493 // the correct library paths. 2494 updateAllSharedLibrariesLPw(); 2495 2496 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2497 // NOTE: We ignore potential failures here during a system scan (like 2498 // the rest of the commands above) because there's precious little we 2499 // can do about it. A settings error is reported, though. 2500 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2501 false /* boot complete */); 2502 } 2503 2504 // Now that we know all the packages we are keeping, 2505 // read and update their last usage times. 2506 mPackageUsage.readLP(); 2507 2508 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2509 SystemClock.uptimeMillis()); 2510 Slog.i(TAG, "Time to scan packages: " 2511 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2512 + " seconds"); 2513 2514 // If the platform SDK has changed since the last time we booted, 2515 // we need to re-grant app permission to catch any new ones that 2516 // appear. This is really a hack, and means that apps can in some 2517 // cases get permissions that the user didn't initially explicitly 2518 // allow... it would be nice to have some better way to handle 2519 // this situation. 2520 int updateFlags = UPDATE_PERMISSIONS_ALL; 2521 if (ver.sdkVersion != mSdkVersion) { 2522 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2523 + mSdkVersion + "; regranting permissions for internal storage"); 2524 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2525 } 2526 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2527 ver.sdkVersion = mSdkVersion; 2528 2529 // If this is the first boot or an update from pre-M, and it is a normal 2530 // boot, then we need to initialize the default preferred apps across 2531 // all defined users. 2532 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2533 for (UserInfo user : sUserManager.getUsers(true)) { 2534 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2535 applyFactoryDefaultBrowserLPw(user.id); 2536 primeDomainVerificationsLPw(user.id); 2537 } 2538 } 2539 2540 // Prepare storage for system user really early during boot, 2541 // since core system apps like SettingsProvider and SystemUI 2542 // can't wait for user to start 2543 final int storageFlags; 2544 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2545 storageFlags = StorageManager.FLAG_STORAGE_DE; 2546 } else { 2547 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2548 } 2549 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2550 storageFlags); 2551 2552 // If this is first boot after an OTA, and a normal boot, then 2553 // we need to clear code cache directories. 2554 if (mIsUpgrade && !onlyCore) { 2555 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2556 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2557 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2558 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2559 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2560 } 2561 } 2562 ver.fingerprint = Build.FINGERPRINT; 2563 } 2564 2565 checkDefaultBrowser(); 2566 2567 // clear only after permissions and other defaults have been updated 2568 mExistingSystemPackages.clear(); 2569 mPromoteSystemApps = false; 2570 2571 // All the changes are done during package scanning. 2572 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2573 2574 // can downgrade to reader 2575 mSettings.writeLPr(); 2576 2577 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2578 SystemClock.uptimeMillis()); 2579 2580 if (!mOnlyCore) { 2581 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2582 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2583 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2584 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2585 mIntentFilterVerifierComponent); 2586 } else { 2587 mRequiredVerifierPackage = null; 2588 mRequiredInstallerPackage = null; 2589 mIntentFilterVerifierComponent = null; 2590 mIntentFilterVerifier = null; 2591 } 2592 2593 mInstallerService = new PackageInstallerService(context, this); 2594 2595 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2596 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2597 // both the installer and resolver must be present to enable ephemeral 2598 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2599 if (DEBUG_EPHEMERAL) { 2600 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2601 + " installer:" + ephemeralInstallerComponent); 2602 } 2603 mEphemeralResolverComponent = ephemeralResolverComponent; 2604 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2605 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2606 mEphemeralResolverConnection = 2607 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2608 } else { 2609 if (DEBUG_EPHEMERAL) { 2610 final String missingComponent = 2611 (ephemeralResolverComponent == null) 2612 ? (ephemeralInstallerComponent == null) 2613 ? "resolver and installer" 2614 : "resolver" 2615 : "installer"; 2616 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2617 } 2618 mEphemeralResolverComponent = null; 2619 mEphemeralInstallerComponent = null; 2620 mEphemeralResolverConnection = null; 2621 } 2622 2623 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2624 } // synchronized (mPackages) 2625 } // synchronized (mInstallLock) 2626 2627 // Now after opening every single application zip, make sure they 2628 // are all flushed. Not really needed, but keeps things nice and 2629 // tidy. 2630 Runtime.getRuntime().gc(); 2631 2632 // The initial scanning above does many calls into installd while 2633 // holding the mPackages lock, but we're mostly interested in yelling 2634 // once we have a booted system. 2635 mInstaller.setWarnIfHeld(mPackages); 2636 2637 // Expose private service for system components to use. 2638 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2639 } 2640 2641 @Override 2642 public boolean isFirstBoot() { 2643 return !mRestoredSettings; 2644 } 2645 2646 @Override 2647 public boolean isOnlyCoreApps() { 2648 return mOnlyCore; 2649 } 2650 2651 @Override 2652 public boolean isUpgrade() { 2653 return mIsUpgrade; 2654 } 2655 2656 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2657 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2658 2659 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2660 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2661 UserHandle.USER_SYSTEM); 2662 if (matches.size() == 1) { 2663 return matches.get(0).getComponentInfo().packageName; 2664 } else { 2665 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2666 return null; 2667 } 2668 } 2669 2670 private @NonNull String getRequiredInstallerLPr() { 2671 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2672 intent.addCategory(Intent.CATEGORY_DEFAULT); 2673 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2674 2675 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2676 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2677 UserHandle.USER_SYSTEM); 2678 if (matches.size() == 1) { 2679 return matches.get(0).getComponentInfo().packageName; 2680 } else { 2681 throw new RuntimeException("There must be exactly one installer; found " + matches); 2682 } 2683 } 2684 2685 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2686 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2687 2688 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2689 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2690 UserHandle.USER_SYSTEM); 2691 ResolveInfo best = null; 2692 final int N = matches.size(); 2693 for (int i = 0; i < N; i++) { 2694 final ResolveInfo cur = matches.get(i); 2695 final String packageName = cur.getComponentInfo().packageName; 2696 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2697 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2698 continue; 2699 } 2700 2701 if (best == null || cur.priority > best.priority) { 2702 best = cur; 2703 } 2704 } 2705 2706 if (best != null) { 2707 return best.getComponentInfo().getComponentName(); 2708 } else { 2709 throw new RuntimeException("There must be at least one intent filter verifier"); 2710 } 2711 } 2712 2713 private @Nullable ComponentName getEphemeralResolverLPr() { 2714 final String[] packageArray = 2715 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2716 if (packageArray.length == 0) { 2717 if (DEBUG_EPHEMERAL) { 2718 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2719 } 2720 return null; 2721 } 2722 2723 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2724 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2725 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2726 UserHandle.USER_SYSTEM); 2727 2728 final int N = resolvers.size(); 2729 if (N == 0) { 2730 if (DEBUG_EPHEMERAL) { 2731 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2732 } 2733 return null; 2734 } 2735 2736 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2737 for (int i = 0; i < N; i++) { 2738 final ResolveInfo info = resolvers.get(i); 2739 2740 if (info.serviceInfo == null) { 2741 continue; 2742 } 2743 2744 final String packageName = info.serviceInfo.packageName; 2745 if (!possiblePackages.contains(packageName)) { 2746 if (DEBUG_EPHEMERAL) { 2747 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2748 + " pkg: " + packageName + ", info:" + info); 2749 } 2750 continue; 2751 } 2752 2753 if (DEBUG_EPHEMERAL) { 2754 Slog.v(TAG, "Ephemeral resolver found;" 2755 + " pkg: " + packageName + ", info:" + info); 2756 } 2757 return new ComponentName(packageName, info.serviceInfo.name); 2758 } 2759 if (DEBUG_EPHEMERAL) { 2760 Slog.v(TAG, "Ephemeral resolver NOT found"); 2761 } 2762 return null; 2763 } 2764 2765 private @Nullable ComponentName getEphemeralInstallerLPr() { 2766 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2767 intent.addCategory(Intent.CATEGORY_DEFAULT); 2768 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2769 2770 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2771 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2772 UserHandle.USER_SYSTEM); 2773 if (matches.size() == 0) { 2774 return null; 2775 } else if (matches.size() == 1) { 2776 return matches.get(0).getComponentInfo().getComponentName(); 2777 } else { 2778 throw new RuntimeException( 2779 "There must be at most one ephemeral installer; found " + matches); 2780 } 2781 } 2782 2783 private void primeDomainVerificationsLPw(int userId) { 2784 if (DEBUG_DOMAIN_VERIFICATION) { 2785 Slog.d(TAG, "Priming domain verifications in user " + userId); 2786 } 2787 2788 SystemConfig systemConfig = SystemConfig.getInstance(); 2789 ArraySet<String> packages = systemConfig.getLinkedApps(); 2790 ArraySet<String> domains = new ArraySet<String>(); 2791 2792 for (String packageName : packages) { 2793 PackageParser.Package pkg = mPackages.get(packageName); 2794 if (pkg != null) { 2795 if (!pkg.isSystemApp()) { 2796 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2797 continue; 2798 } 2799 2800 domains.clear(); 2801 for (PackageParser.Activity a : pkg.activities) { 2802 for (ActivityIntentInfo filter : a.intents) { 2803 if (hasValidDomains(filter)) { 2804 domains.addAll(filter.getHostsList()); 2805 } 2806 } 2807 } 2808 2809 if (domains.size() > 0) { 2810 if (DEBUG_DOMAIN_VERIFICATION) { 2811 Slog.v(TAG, " + " + packageName); 2812 } 2813 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2814 // state w.r.t. the formal app-linkage "no verification attempted" state; 2815 // and then 'always' in the per-user state actually used for intent resolution. 2816 final IntentFilterVerificationInfo ivi; 2817 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2818 new ArrayList<String>(domains)); 2819 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2820 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2821 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2822 } else { 2823 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2824 + "' does not handle web links"); 2825 } 2826 } else { 2827 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2828 } 2829 } 2830 2831 scheduleWritePackageRestrictionsLocked(userId); 2832 scheduleWriteSettingsLocked(); 2833 } 2834 2835 private void applyFactoryDefaultBrowserLPw(int userId) { 2836 // The default browser app's package name is stored in a string resource, 2837 // with a product-specific overlay used for vendor customization. 2838 String browserPkg = mContext.getResources().getString( 2839 com.android.internal.R.string.default_browser); 2840 if (!TextUtils.isEmpty(browserPkg)) { 2841 // non-empty string => required to be a known package 2842 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2843 if (ps == null) { 2844 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2845 browserPkg = null; 2846 } else { 2847 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2848 } 2849 } 2850 2851 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2852 // default. If there's more than one, just leave everything alone. 2853 if (browserPkg == null) { 2854 calculateDefaultBrowserLPw(userId); 2855 } 2856 } 2857 2858 private void calculateDefaultBrowserLPw(int userId) { 2859 List<String> allBrowsers = resolveAllBrowserApps(userId); 2860 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2861 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2862 } 2863 2864 private List<String> resolveAllBrowserApps(int userId) { 2865 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2866 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2867 PackageManager.MATCH_ALL, userId); 2868 2869 final int count = list.size(); 2870 List<String> result = new ArrayList<String>(count); 2871 for (int i=0; i<count; i++) { 2872 ResolveInfo info = list.get(i); 2873 if (info.activityInfo == null 2874 || !info.handleAllWebDataURI 2875 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2876 || result.contains(info.activityInfo.packageName)) { 2877 continue; 2878 } 2879 result.add(info.activityInfo.packageName); 2880 } 2881 2882 return result; 2883 } 2884 2885 private boolean packageIsBrowser(String packageName, int userId) { 2886 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2887 PackageManager.MATCH_ALL, userId); 2888 final int N = list.size(); 2889 for (int i = 0; i < N; i++) { 2890 ResolveInfo info = list.get(i); 2891 if (packageName.equals(info.activityInfo.packageName)) { 2892 return true; 2893 } 2894 } 2895 return false; 2896 } 2897 2898 private void checkDefaultBrowser() { 2899 final int myUserId = UserHandle.myUserId(); 2900 final String packageName = getDefaultBrowserPackageName(myUserId); 2901 if (packageName != null) { 2902 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2903 if (info == null) { 2904 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2905 synchronized (mPackages) { 2906 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2907 } 2908 } 2909 } 2910 } 2911 2912 @Override 2913 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2914 throws RemoteException { 2915 try { 2916 return super.onTransact(code, data, reply, flags); 2917 } catch (RuntimeException e) { 2918 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2919 Slog.wtf(TAG, "Package Manager Crash", e); 2920 } 2921 throw e; 2922 } 2923 } 2924 2925 void cleanupInstallFailedPackage(PackageSetting ps) { 2926 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2927 2928 removeDataDirsLI(ps.volumeUuid, ps.name); 2929 if (ps.codePath != null) { 2930 removeCodePathLI(ps.codePath); 2931 } 2932 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2933 if (ps.resourcePath.isDirectory()) { 2934 FileUtils.deleteContents(ps.resourcePath); 2935 } 2936 ps.resourcePath.delete(); 2937 } 2938 mSettings.removePackageLPw(ps.name); 2939 } 2940 2941 static int[] appendInts(int[] cur, int[] add) { 2942 if (add == null) return cur; 2943 if (cur == null) return add; 2944 final int N = add.length; 2945 for (int i=0; i<N; i++) { 2946 cur = appendInt(cur, add[i]); 2947 } 2948 return cur; 2949 } 2950 2951 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 2952 if (!sUserManager.exists(userId)) return null; 2953 if (ps == null) { 2954 return null; 2955 } 2956 final PackageParser.Package p = ps.pkg; 2957 if (p == null) { 2958 return null; 2959 } 2960 2961 final PermissionsState permissionsState = ps.getPermissionsState(); 2962 2963 final int[] gids = permissionsState.computeGids(userId); 2964 final Set<String> permissions = permissionsState.getPermissions(userId); 2965 final PackageUserState state = ps.readUserState(userId); 2966 2967 return PackageParser.generatePackageInfo(p, gids, flags, 2968 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2969 } 2970 2971 @Override 2972 public void checkPackageStartable(String packageName, int userId) { 2973 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2974 2975 synchronized (mPackages) { 2976 final PackageSetting ps = mSettings.mPackages.get(packageName); 2977 if (ps == null) { 2978 throw new SecurityException("Package " + packageName + " was not found!"); 2979 } 2980 2981 if (!ps.getInstalled(userId)) { 2982 throw new SecurityException( 2983 "Package " + packageName + " was not installed for user " + userId + "!"); 2984 } 2985 2986 if (mSafeMode && !ps.isSystem()) { 2987 throw new SecurityException("Package " + packageName + " not a system app!"); 2988 } 2989 2990 if (ps.frozen) { 2991 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2992 } 2993 2994 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 2995 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 2996 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2997 } 2998 } 2999 } 3000 3001 @Override 3002 public boolean isPackageAvailable(String packageName, int userId) { 3003 if (!sUserManager.exists(userId)) return false; 3004 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3005 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3006 synchronized (mPackages) { 3007 PackageParser.Package p = mPackages.get(packageName); 3008 if (p != null) { 3009 final PackageSetting ps = (PackageSetting) p.mExtras; 3010 if (ps != null) { 3011 final PackageUserState state = ps.readUserState(userId); 3012 if (state != null) { 3013 return PackageParser.isAvailable(state); 3014 } 3015 } 3016 } 3017 } 3018 return false; 3019 } 3020 3021 @Override 3022 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3023 if (!sUserManager.exists(userId)) return null; 3024 flags = updateFlagsForPackage(flags, userId, packageName); 3025 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3026 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3027 // reader 3028 synchronized (mPackages) { 3029 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3030 PackageParser.Package p = null; 3031 if (matchFactoryOnly) { 3032 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3033 if (ps != null) { 3034 return generatePackageInfo(ps, flags, userId); 3035 } 3036 } 3037 if (p == null) { 3038 p = mPackages.get(packageName); 3039 if (matchFactoryOnly && !isSystemApp(p)) { 3040 return null; 3041 } 3042 } 3043 if (DEBUG_PACKAGE_INFO) 3044 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3045 if (p != null) { 3046 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3047 } 3048 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3049 final PackageSetting ps = mSettings.mPackages.get(packageName); 3050 return generatePackageInfo(ps, flags, userId); 3051 } 3052 } 3053 return null; 3054 } 3055 3056 @Override 3057 public String[] currentToCanonicalPackageNames(String[] names) { 3058 String[] out = new String[names.length]; 3059 // reader 3060 synchronized (mPackages) { 3061 for (int i=names.length-1; i>=0; i--) { 3062 PackageSetting ps = mSettings.mPackages.get(names[i]); 3063 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3064 } 3065 } 3066 return out; 3067 } 3068 3069 @Override 3070 public String[] canonicalToCurrentPackageNames(String[] names) { 3071 String[] out = new String[names.length]; 3072 // reader 3073 synchronized (mPackages) { 3074 for (int i=names.length-1; i>=0; i--) { 3075 String cur = mSettings.mRenamedPackages.get(names[i]); 3076 out[i] = cur != null ? cur : names[i]; 3077 } 3078 } 3079 return out; 3080 } 3081 3082 @Override 3083 public int getPackageUid(String packageName, int flags, int userId) { 3084 if (!sUserManager.exists(userId)) return -1; 3085 flags = updateFlagsForPackage(flags, userId, packageName); 3086 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3087 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3088 3089 // reader 3090 synchronized (mPackages) { 3091 final PackageParser.Package p = mPackages.get(packageName); 3092 if (p != null && p.isMatch(flags)) { 3093 return UserHandle.getUid(userId, p.applicationInfo.uid); 3094 } 3095 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3096 final PackageSetting ps = mSettings.mPackages.get(packageName); 3097 if (ps != null && ps.isMatch(flags)) { 3098 return UserHandle.getUid(userId, ps.appId); 3099 } 3100 } 3101 } 3102 3103 return -1; 3104 } 3105 3106 @Override 3107 public int[] getPackageGids(String packageName, int flags, int userId) { 3108 if (!sUserManager.exists(userId)) return null; 3109 flags = updateFlagsForPackage(flags, userId, packageName); 3110 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3111 false /* requireFullPermission */, false /* checkShell */, 3112 "getPackageGids"); 3113 3114 // reader 3115 synchronized (mPackages) { 3116 final PackageParser.Package p = mPackages.get(packageName); 3117 if (p != null && p.isMatch(flags)) { 3118 PackageSetting ps = (PackageSetting) p.mExtras; 3119 return ps.getPermissionsState().computeGids(userId); 3120 } 3121 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3122 final PackageSetting ps = mSettings.mPackages.get(packageName); 3123 if (ps != null && ps.isMatch(flags)) { 3124 return ps.getPermissionsState().computeGids(userId); 3125 } 3126 } 3127 } 3128 3129 return null; 3130 } 3131 3132 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3133 if (bp.perm != null) { 3134 return PackageParser.generatePermissionInfo(bp.perm, flags); 3135 } 3136 PermissionInfo pi = new PermissionInfo(); 3137 pi.name = bp.name; 3138 pi.packageName = bp.sourcePackage; 3139 pi.nonLocalizedLabel = bp.name; 3140 pi.protectionLevel = bp.protectionLevel; 3141 return pi; 3142 } 3143 3144 @Override 3145 public PermissionInfo getPermissionInfo(String name, int flags) { 3146 // reader 3147 synchronized (mPackages) { 3148 final BasePermission p = mSettings.mPermissions.get(name); 3149 if (p != null) { 3150 return generatePermissionInfo(p, flags); 3151 } 3152 return null; 3153 } 3154 } 3155 3156 @Override 3157 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3158 int flags) { 3159 // reader 3160 synchronized (mPackages) { 3161 if (group != null && !mPermissionGroups.containsKey(group)) { 3162 // This is thrown as NameNotFoundException 3163 return null; 3164 } 3165 3166 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3167 for (BasePermission p : mSettings.mPermissions.values()) { 3168 if (group == null) { 3169 if (p.perm == null || p.perm.info.group == null) { 3170 out.add(generatePermissionInfo(p, flags)); 3171 } 3172 } else { 3173 if (p.perm != null && group.equals(p.perm.info.group)) { 3174 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3175 } 3176 } 3177 } 3178 return new ParceledListSlice<>(out); 3179 } 3180 } 3181 3182 @Override 3183 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3184 // reader 3185 synchronized (mPackages) { 3186 return PackageParser.generatePermissionGroupInfo( 3187 mPermissionGroups.get(name), flags); 3188 } 3189 } 3190 3191 @Override 3192 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3193 // reader 3194 synchronized (mPackages) { 3195 final int N = mPermissionGroups.size(); 3196 ArrayList<PermissionGroupInfo> out 3197 = new ArrayList<PermissionGroupInfo>(N); 3198 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3199 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3200 } 3201 return new ParceledListSlice<>(out); 3202 } 3203 } 3204 3205 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3206 int userId) { 3207 if (!sUserManager.exists(userId)) return null; 3208 PackageSetting ps = mSettings.mPackages.get(packageName); 3209 if (ps != null) { 3210 if (ps.pkg == null) { 3211 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3212 if (pInfo != null) { 3213 return pInfo.applicationInfo; 3214 } 3215 return null; 3216 } 3217 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3218 ps.readUserState(userId), userId); 3219 } 3220 return null; 3221 } 3222 3223 @Override 3224 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3225 if (!sUserManager.exists(userId)) return null; 3226 flags = updateFlagsForApplication(flags, userId, packageName); 3227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3228 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3229 // writer 3230 synchronized (mPackages) { 3231 PackageParser.Package p = mPackages.get(packageName); 3232 if (DEBUG_PACKAGE_INFO) Log.v( 3233 TAG, "getApplicationInfo " + packageName 3234 + ": " + p); 3235 if (p != null) { 3236 PackageSetting ps = mSettings.mPackages.get(packageName); 3237 if (ps == null) return null; 3238 // Note: isEnabledLP() does not apply here - always return info 3239 return PackageParser.generateApplicationInfo( 3240 p, flags, ps.readUserState(userId), userId); 3241 } 3242 if ("android".equals(packageName)||"system".equals(packageName)) { 3243 return mAndroidApplication; 3244 } 3245 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3246 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3247 } 3248 } 3249 return null; 3250 } 3251 3252 @Override 3253 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3254 final IPackageDataObserver observer) { 3255 mContext.enforceCallingOrSelfPermission( 3256 android.Manifest.permission.CLEAR_APP_CACHE, null); 3257 // Queue up an async operation since clearing cache may take a little while. 3258 mHandler.post(new Runnable() { 3259 public void run() { 3260 mHandler.removeCallbacks(this); 3261 boolean success = true; 3262 synchronized (mInstallLock) { 3263 try { 3264 mInstaller.freeCache(volumeUuid, freeStorageSize); 3265 } catch (InstallerException e) { 3266 Slog.w(TAG, "Couldn't clear application caches: " + e); 3267 success = false; 3268 } 3269 } 3270 if (observer != null) { 3271 try { 3272 observer.onRemoveCompleted(null, success); 3273 } catch (RemoteException e) { 3274 Slog.w(TAG, "RemoveException when invoking call back"); 3275 } 3276 } 3277 } 3278 }); 3279 } 3280 3281 @Override 3282 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3283 final IntentSender pi) { 3284 mContext.enforceCallingOrSelfPermission( 3285 android.Manifest.permission.CLEAR_APP_CACHE, null); 3286 // Queue up an async operation since clearing cache may take a little while. 3287 mHandler.post(new Runnable() { 3288 public void run() { 3289 mHandler.removeCallbacks(this); 3290 boolean success = true; 3291 synchronized (mInstallLock) { 3292 try { 3293 mInstaller.freeCache(volumeUuid, freeStorageSize); 3294 } catch (InstallerException e) { 3295 Slog.w(TAG, "Couldn't clear application caches: " + e); 3296 success = false; 3297 } 3298 } 3299 if(pi != null) { 3300 try { 3301 // Callback via pending intent 3302 int code = success ? 1 : 0; 3303 pi.sendIntent(null, code, null, 3304 null, null); 3305 } catch (SendIntentException e1) { 3306 Slog.i(TAG, "Failed to send pending intent"); 3307 } 3308 } 3309 } 3310 }); 3311 } 3312 3313 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3314 synchronized (mInstallLock) { 3315 try { 3316 mInstaller.freeCache(volumeUuid, freeStorageSize); 3317 } catch (InstallerException e) { 3318 throw new IOException("Failed to free enough space", e); 3319 } 3320 } 3321 } 3322 3323 /** 3324 * Return if the user key is currently unlocked. 3325 */ 3326 private boolean isUserKeyUnlocked(int userId) { 3327 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3328 final IMountService mount = IMountService.Stub 3329 .asInterface(ServiceManager.getService("mount")); 3330 if (mount == null) { 3331 Slog.w(TAG, "Early during boot, assuming locked"); 3332 return false; 3333 } 3334 final long token = Binder.clearCallingIdentity(); 3335 try { 3336 return mount.isUserKeyUnlocked(userId); 3337 } catch (RemoteException e) { 3338 throw e.rethrowAsRuntimeException(); 3339 } finally { 3340 Binder.restoreCallingIdentity(token); 3341 } 3342 } else { 3343 return true; 3344 } 3345 } 3346 3347 /** 3348 * Update given flags based on encryption status of current user. 3349 */ 3350 private int updateFlags(int flags, int userId) { 3351 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3352 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3353 // Caller expressed an explicit opinion about what encryption 3354 // aware/unaware components they want to see, so fall through and 3355 // give them what they want 3356 } else { 3357 // Caller expressed no opinion, so match based on user state 3358 if (isUserKeyUnlocked(userId)) { 3359 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3360 } else { 3361 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3362 } 3363 } 3364 return flags; 3365 } 3366 3367 /** 3368 * Update given flags when being used to request {@link PackageInfo}. 3369 */ 3370 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3371 boolean triaged = true; 3372 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3373 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3374 // Caller is asking for component details, so they'd better be 3375 // asking for specific encryption matching behavior, or be triaged 3376 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3377 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3378 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3379 triaged = false; 3380 } 3381 } 3382 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3383 | PackageManager.MATCH_SYSTEM_ONLY 3384 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3385 triaged = false; 3386 } 3387 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3388 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3389 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3390 } 3391 return updateFlags(flags, userId); 3392 } 3393 3394 /** 3395 * Update given flags when being used to request {@link ApplicationInfo}. 3396 */ 3397 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3398 return updateFlagsForPackage(flags, userId, cookie); 3399 } 3400 3401 /** 3402 * Update given flags when being used to request {@link ComponentInfo}. 3403 */ 3404 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3405 if (cookie instanceof Intent) { 3406 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3407 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3408 } 3409 } 3410 3411 boolean triaged = true; 3412 // Caller is asking for component details, so they'd better be 3413 // asking for specific encryption matching behavior, or be triaged 3414 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3415 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3416 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3417 triaged = false; 3418 } 3419 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3420 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3421 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3422 } 3423 3424 return updateFlags(flags, userId); 3425 } 3426 3427 /** 3428 * Update given flags when being used to request {@link ResolveInfo}. 3429 */ 3430 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3431 // Safe mode means we shouldn't match any third-party components 3432 if (mSafeMode) { 3433 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3434 } 3435 3436 return updateFlagsForComponent(flags, userId, cookie); 3437 } 3438 3439 @Override 3440 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3441 if (!sUserManager.exists(userId)) return null; 3442 flags = updateFlagsForComponent(flags, userId, component); 3443 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3444 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3445 synchronized (mPackages) { 3446 PackageParser.Activity a = mActivities.mActivities.get(component); 3447 3448 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3449 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3450 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3451 if (ps == null) return null; 3452 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3453 userId); 3454 } 3455 if (mResolveComponentName.equals(component)) { 3456 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3457 new PackageUserState(), userId); 3458 } 3459 } 3460 return null; 3461 } 3462 3463 @Override 3464 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3465 String resolvedType) { 3466 synchronized (mPackages) { 3467 if (component.equals(mResolveComponentName)) { 3468 // The resolver supports EVERYTHING! 3469 return true; 3470 } 3471 PackageParser.Activity a = mActivities.mActivities.get(component); 3472 if (a == null) { 3473 return false; 3474 } 3475 for (int i=0; i<a.intents.size(); i++) { 3476 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3477 intent.getData(), intent.getCategories(), TAG) >= 0) { 3478 return true; 3479 } 3480 } 3481 return false; 3482 } 3483 } 3484 3485 @Override 3486 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3487 if (!sUserManager.exists(userId)) return null; 3488 flags = updateFlagsForComponent(flags, userId, component); 3489 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3490 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3491 synchronized (mPackages) { 3492 PackageParser.Activity a = mReceivers.mActivities.get(component); 3493 if (DEBUG_PACKAGE_INFO) Log.v( 3494 TAG, "getReceiverInfo " + component + ": " + a); 3495 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3496 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3497 if (ps == null) return null; 3498 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3499 userId); 3500 } 3501 } 3502 return null; 3503 } 3504 3505 @Override 3506 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3507 if (!sUserManager.exists(userId)) return null; 3508 flags = updateFlagsForComponent(flags, userId, component); 3509 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3510 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3511 synchronized (mPackages) { 3512 PackageParser.Service s = mServices.mServices.get(component); 3513 if (DEBUG_PACKAGE_INFO) Log.v( 3514 TAG, "getServiceInfo " + component + ": " + s); 3515 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3516 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3517 if (ps == null) return null; 3518 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3519 userId); 3520 } 3521 } 3522 return null; 3523 } 3524 3525 @Override 3526 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3527 if (!sUserManager.exists(userId)) return null; 3528 flags = updateFlagsForComponent(flags, userId, component); 3529 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3530 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3531 synchronized (mPackages) { 3532 PackageParser.Provider p = mProviders.mProviders.get(component); 3533 if (DEBUG_PACKAGE_INFO) Log.v( 3534 TAG, "getProviderInfo " + component + ": " + p); 3535 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3536 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3537 if (ps == null) return null; 3538 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3539 userId); 3540 } 3541 } 3542 return null; 3543 } 3544 3545 @Override 3546 public String[] getSystemSharedLibraryNames() { 3547 Set<String> libSet; 3548 synchronized (mPackages) { 3549 libSet = mSharedLibraries.keySet(); 3550 int size = libSet.size(); 3551 if (size > 0) { 3552 String[] libs = new String[size]; 3553 libSet.toArray(libs); 3554 return libs; 3555 } 3556 } 3557 return null; 3558 } 3559 3560 @Override 3561 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3562 synchronized (mPackages) { 3563 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3564 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3565 if (libraryEntry != null) { 3566 return libraryEntry.apk; 3567 } 3568 } 3569 return null; 3570 } 3571 3572 @Override 3573 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3574 synchronized (mPackages) { 3575 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3576 3577 final FeatureInfo fi = new FeatureInfo(); 3578 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3579 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3580 res.add(fi); 3581 3582 return new ParceledListSlice<>(res); 3583 } 3584 } 3585 3586 @Override 3587 public boolean hasSystemFeature(String name, int version) { 3588 synchronized (mPackages) { 3589 final FeatureInfo feat = mAvailableFeatures.get(name); 3590 if (feat == null) { 3591 return false; 3592 } else { 3593 return feat.version >= version; 3594 } 3595 } 3596 } 3597 3598 @Override 3599 public int checkPermission(String permName, String pkgName, int userId) { 3600 if (!sUserManager.exists(userId)) { 3601 return PackageManager.PERMISSION_DENIED; 3602 } 3603 3604 synchronized (mPackages) { 3605 final PackageParser.Package p = mPackages.get(pkgName); 3606 if (p != null && p.mExtras != null) { 3607 final PackageSetting ps = (PackageSetting) p.mExtras; 3608 final PermissionsState permissionsState = ps.getPermissionsState(); 3609 if (permissionsState.hasPermission(permName, userId)) { 3610 return PackageManager.PERMISSION_GRANTED; 3611 } 3612 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3613 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3614 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3615 return PackageManager.PERMISSION_GRANTED; 3616 } 3617 } 3618 } 3619 3620 return PackageManager.PERMISSION_DENIED; 3621 } 3622 3623 @Override 3624 public int checkUidPermission(String permName, int uid) { 3625 final int userId = UserHandle.getUserId(uid); 3626 3627 if (!sUserManager.exists(userId)) { 3628 return PackageManager.PERMISSION_DENIED; 3629 } 3630 3631 synchronized (mPackages) { 3632 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3633 if (obj != null) { 3634 final SettingBase ps = (SettingBase) obj; 3635 final PermissionsState permissionsState = ps.getPermissionsState(); 3636 if (permissionsState.hasPermission(permName, userId)) { 3637 return PackageManager.PERMISSION_GRANTED; 3638 } 3639 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3640 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3641 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3642 return PackageManager.PERMISSION_GRANTED; 3643 } 3644 } else { 3645 ArraySet<String> perms = mSystemPermissions.get(uid); 3646 if (perms != null) { 3647 if (perms.contains(permName)) { 3648 return PackageManager.PERMISSION_GRANTED; 3649 } 3650 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3651 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3652 return PackageManager.PERMISSION_GRANTED; 3653 } 3654 } 3655 } 3656 } 3657 3658 return PackageManager.PERMISSION_DENIED; 3659 } 3660 3661 @Override 3662 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3663 if (UserHandle.getCallingUserId() != userId) { 3664 mContext.enforceCallingPermission( 3665 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3666 "isPermissionRevokedByPolicy for user " + userId); 3667 } 3668 3669 if (checkPermission(permission, packageName, userId) 3670 == PackageManager.PERMISSION_GRANTED) { 3671 return false; 3672 } 3673 3674 final long identity = Binder.clearCallingIdentity(); 3675 try { 3676 final int flags = getPermissionFlags(permission, packageName, userId); 3677 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3678 } finally { 3679 Binder.restoreCallingIdentity(identity); 3680 } 3681 } 3682 3683 @Override 3684 public String getPermissionControllerPackageName() { 3685 synchronized (mPackages) { 3686 return mRequiredInstallerPackage; 3687 } 3688 } 3689 3690 /** 3691 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3692 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3693 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3694 * @param message the message to log on security exception 3695 */ 3696 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3697 boolean checkShell, String message) { 3698 if (userId < 0) { 3699 throw new IllegalArgumentException("Invalid userId " + userId); 3700 } 3701 if (checkShell) { 3702 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3703 } 3704 if (userId == UserHandle.getUserId(callingUid)) return; 3705 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3706 if (requireFullPermission) { 3707 mContext.enforceCallingOrSelfPermission( 3708 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3709 } else { 3710 try { 3711 mContext.enforceCallingOrSelfPermission( 3712 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3713 } catch (SecurityException se) { 3714 mContext.enforceCallingOrSelfPermission( 3715 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3716 } 3717 } 3718 } 3719 } 3720 3721 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3722 if (callingUid == Process.SHELL_UID) { 3723 if (userHandle >= 0 3724 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3725 throw new SecurityException("Shell does not have permission to access user " 3726 + userHandle); 3727 } else if (userHandle < 0) { 3728 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3729 + Debug.getCallers(3)); 3730 } 3731 } 3732 } 3733 3734 private BasePermission findPermissionTreeLP(String permName) { 3735 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3736 if (permName.startsWith(bp.name) && 3737 permName.length() > bp.name.length() && 3738 permName.charAt(bp.name.length()) == '.') { 3739 return bp; 3740 } 3741 } 3742 return null; 3743 } 3744 3745 private BasePermission checkPermissionTreeLP(String permName) { 3746 if (permName != null) { 3747 BasePermission bp = findPermissionTreeLP(permName); 3748 if (bp != null) { 3749 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3750 return bp; 3751 } 3752 throw new SecurityException("Calling uid " 3753 + Binder.getCallingUid() 3754 + " is not allowed to add to permission tree " 3755 + bp.name + " owned by uid " + bp.uid); 3756 } 3757 } 3758 throw new SecurityException("No permission tree found for " + permName); 3759 } 3760 3761 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3762 if (s1 == null) { 3763 return s2 == null; 3764 } 3765 if (s2 == null) { 3766 return false; 3767 } 3768 if (s1.getClass() != s2.getClass()) { 3769 return false; 3770 } 3771 return s1.equals(s2); 3772 } 3773 3774 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3775 if (pi1.icon != pi2.icon) return false; 3776 if (pi1.logo != pi2.logo) return false; 3777 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3778 if (!compareStrings(pi1.name, pi2.name)) return false; 3779 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3780 // We'll take care of setting this one. 3781 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3782 // These are not currently stored in settings. 3783 //if (!compareStrings(pi1.group, pi2.group)) return false; 3784 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3785 //if (pi1.labelRes != pi2.labelRes) return false; 3786 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3787 return true; 3788 } 3789 3790 int permissionInfoFootprint(PermissionInfo info) { 3791 int size = info.name.length(); 3792 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3793 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3794 return size; 3795 } 3796 3797 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3798 int size = 0; 3799 for (BasePermission perm : mSettings.mPermissions.values()) { 3800 if (perm.uid == tree.uid) { 3801 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3802 } 3803 } 3804 return size; 3805 } 3806 3807 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3808 // We calculate the max size of permissions defined by this uid and throw 3809 // if that plus the size of 'info' would exceed our stated maximum. 3810 if (tree.uid != Process.SYSTEM_UID) { 3811 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3812 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3813 throw new SecurityException("Permission tree size cap exceeded"); 3814 } 3815 } 3816 } 3817 3818 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3819 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3820 throw new SecurityException("Label must be specified in permission"); 3821 } 3822 BasePermission tree = checkPermissionTreeLP(info.name); 3823 BasePermission bp = mSettings.mPermissions.get(info.name); 3824 boolean added = bp == null; 3825 boolean changed = true; 3826 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3827 if (added) { 3828 enforcePermissionCapLocked(info, tree); 3829 bp = new BasePermission(info.name, tree.sourcePackage, 3830 BasePermission.TYPE_DYNAMIC); 3831 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3832 throw new SecurityException( 3833 "Not allowed to modify non-dynamic permission " 3834 + info.name); 3835 } else { 3836 if (bp.protectionLevel == fixedLevel 3837 && bp.perm.owner.equals(tree.perm.owner) 3838 && bp.uid == tree.uid 3839 && comparePermissionInfos(bp.perm.info, info)) { 3840 changed = false; 3841 } 3842 } 3843 bp.protectionLevel = fixedLevel; 3844 info = new PermissionInfo(info); 3845 info.protectionLevel = fixedLevel; 3846 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3847 bp.perm.info.packageName = tree.perm.info.packageName; 3848 bp.uid = tree.uid; 3849 if (added) { 3850 mSettings.mPermissions.put(info.name, bp); 3851 } 3852 if (changed) { 3853 if (!async) { 3854 mSettings.writeLPr(); 3855 } else { 3856 scheduleWriteSettingsLocked(); 3857 } 3858 } 3859 return added; 3860 } 3861 3862 @Override 3863 public boolean addPermission(PermissionInfo info) { 3864 synchronized (mPackages) { 3865 return addPermissionLocked(info, false); 3866 } 3867 } 3868 3869 @Override 3870 public boolean addPermissionAsync(PermissionInfo info) { 3871 synchronized (mPackages) { 3872 return addPermissionLocked(info, true); 3873 } 3874 } 3875 3876 @Override 3877 public void removePermission(String name) { 3878 synchronized (mPackages) { 3879 checkPermissionTreeLP(name); 3880 BasePermission bp = mSettings.mPermissions.get(name); 3881 if (bp != null) { 3882 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3883 throw new SecurityException( 3884 "Not allowed to modify non-dynamic permission " 3885 + name); 3886 } 3887 mSettings.mPermissions.remove(name); 3888 mSettings.writeLPr(); 3889 } 3890 } 3891 } 3892 3893 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3894 BasePermission bp) { 3895 int index = pkg.requestedPermissions.indexOf(bp.name); 3896 if (index == -1) { 3897 throw new SecurityException("Package " + pkg.packageName 3898 + " has not requested permission " + bp.name); 3899 } 3900 if (!bp.isRuntime() && !bp.isDevelopment()) { 3901 throw new SecurityException("Permission " + bp.name 3902 + " is not a changeable permission type"); 3903 } 3904 } 3905 3906 @Override 3907 public void grantRuntimePermission(String packageName, String name, final int userId) { 3908 if (!sUserManager.exists(userId)) { 3909 Log.e(TAG, "No such user:" + userId); 3910 return; 3911 } 3912 3913 mContext.enforceCallingOrSelfPermission( 3914 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3915 "grantRuntimePermission"); 3916 3917 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3918 true /* requireFullPermission */, true /* checkShell */, 3919 "grantRuntimePermission"); 3920 3921 final int uid; 3922 final SettingBase sb; 3923 3924 synchronized (mPackages) { 3925 final PackageParser.Package pkg = mPackages.get(packageName); 3926 if (pkg == null) { 3927 throw new IllegalArgumentException("Unknown package: " + packageName); 3928 } 3929 3930 final BasePermission bp = mSettings.mPermissions.get(name); 3931 if (bp == null) { 3932 throw new IllegalArgumentException("Unknown permission: " + name); 3933 } 3934 3935 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3936 3937 // If a permission review is required for legacy apps we represent 3938 // their permissions as always granted runtime ones since we need 3939 // to keep the review required permission flag per user while an 3940 // install permission's state is shared across all users. 3941 if (Build.PERMISSIONS_REVIEW_REQUIRED 3942 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3943 && bp.isRuntime()) { 3944 return; 3945 } 3946 3947 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3948 sb = (SettingBase) pkg.mExtras; 3949 if (sb == null) { 3950 throw new IllegalArgumentException("Unknown package: " + packageName); 3951 } 3952 3953 final PermissionsState permissionsState = sb.getPermissionsState(); 3954 3955 final int flags = permissionsState.getPermissionFlags(name, userId); 3956 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3957 throw new SecurityException("Cannot grant system fixed permission " 3958 + name + " for package " + packageName); 3959 } 3960 3961 if (bp.isDevelopment()) { 3962 // Development permissions must be handled specially, since they are not 3963 // normal runtime permissions. For now they apply to all users. 3964 if (permissionsState.grantInstallPermission(bp) != 3965 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3966 scheduleWriteSettingsLocked(); 3967 } 3968 return; 3969 } 3970 3971 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3972 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3973 return; 3974 } 3975 3976 final int result = permissionsState.grantRuntimePermission(bp, userId); 3977 switch (result) { 3978 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3979 return; 3980 } 3981 3982 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3983 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3984 mHandler.post(new Runnable() { 3985 @Override 3986 public void run() { 3987 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3988 } 3989 }); 3990 } 3991 break; 3992 } 3993 3994 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3995 3996 // Not critical if that is lost - app has to request again. 3997 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3998 } 3999 4000 // Only need to do this if user is initialized. Otherwise it's a new user 4001 // and there are no processes running as the user yet and there's no need 4002 // to make an expensive call to remount processes for the changed permissions. 4003 if (READ_EXTERNAL_STORAGE.equals(name) 4004 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4005 final long token = Binder.clearCallingIdentity(); 4006 try { 4007 if (sUserManager.isInitialized(userId)) { 4008 MountServiceInternal mountServiceInternal = LocalServices.getService( 4009 MountServiceInternal.class); 4010 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4011 } 4012 } finally { 4013 Binder.restoreCallingIdentity(token); 4014 } 4015 } 4016 } 4017 4018 @Override 4019 public void revokeRuntimePermission(String packageName, String name, int userId) { 4020 if (!sUserManager.exists(userId)) { 4021 Log.e(TAG, "No such user:" + userId); 4022 return; 4023 } 4024 4025 mContext.enforceCallingOrSelfPermission( 4026 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4027 "revokeRuntimePermission"); 4028 4029 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4030 true /* requireFullPermission */, true /* checkShell */, 4031 "revokeRuntimePermission"); 4032 4033 final int appId; 4034 4035 synchronized (mPackages) { 4036 final PackageParser.Package pkg = mPackages.get(packageName); 4037 if (pkg == null) { 4038 throw new IllegalArgumentException("Unknown package: " + packageName); 4039 } 4040 4041 final BasePermission bp = mSettings.mPermissions.get(name); 4042 if (bp == null) { 4043 throw new IllegalArgumentException("Unknown permission: " + name); 4044 } 4045 4046 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4047 4048 // If a permission review is required for legacy apps we represent 4049 // their permissions as always granted runtime ones since we need 4050 // to keep the review required permission flag per user while an 4051 // install permission's state is shared across all users. 4052 if (Build.PERMISSIONS_REVIEW_REQUIRED 4053 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4054 && bp.isRuntime()) { 4055 return; 4056 } 4057 4058 SettingBase sb = (SettingBase) pkg.mExtras; 4059 if (sb == null) { 4060 throw new IllegalArgumentException("Unknown package: " + packageName); 4061 } 4062 4063 final PermissionsState permissionsState = sb.getPermissionsState(); 4064 4065 final int flags = permissionsState.getPermissionFlags(name, userId); 4066 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4067 throw new SecurityException("Cannot revoke system fixed permission " 4068 + name + " for package " + packageName); 4069 } 4070 4071 if (bp.isDevelopment()) { 4072 // Development permissions must be handled specially, since they are not 4073 // normal runtime permissions. For now they apply to all users. 4074 if (permissionsState.revokeInstallPermission(bp) != 4075 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4076 scheduleWriteSettingsLocked(); 4077 } 4078 return; 4079 } 4080 4081 if (permissionsState.revokeRuntimePermission(bp, userId) == 4082 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4083 return; 4084 } 4085 4086 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4087 4088 // Critical, after this call app should never have the permission. 4089 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4090 4091 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4092 } 4093 4094 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4095 } 4096 4097 @Override 4098 public void resetRuntimePermissions() { 4099 mContext.enforceCallingOrSelfPermission( 4100 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4101 "revokeRuntimePermission"); 4102 4103 int callingUid = Binder.getCallingUid(); 4104 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4105 mContext.enforceCallingOrSelfPermission( 4106 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4107 "resetRuntimePermissions"); 4108 } 4109 4110 synchronized (mPackages) { 4111 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4112 for (int userId : UserManagerService.getInstance().getUserIds()) { 4113 final int packageCount = mPackages.size(); 4114 for (int i = 0; i < packageCount; i++) { 4115 PackageParser.Package pkg = mPackages.valueAt(i); 4116 if (!(pkg.mExtras instanceof PackageSetting)) { 4117 continue; 4118 } 4119 PackageSetting ps = (PackageSetting) pkg.mExtras; 4120 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4121 } 4122 } 4123 } 4124 } 4125 4126 @Override 4127 public int getPermissionFlags(String name, String packageName, int userId) { 4128 if (!sUserManager.exists(userId)) { 4129 return 0; 4130 } 4131 4132 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4133 4134 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4135 true /* requireFullPermission */, false /* checkShell */, 4136 "getPermissionFlags"); 4137 4138 synchronized (mPackages) { 4139 final PackageParser.Package pkg = mPackages.get(packageName); 4140 if (pkg == null) { 4141 throw new IllegalArgumentException("Unknown package: " + packageName); 4142 } 4143 4144 final BasePermission bp = mSettings.mPermissions.get(name); 4145 if (bp == null) { 4146 throw new IllegalArgumentException("Unknown permission: " + name); 4147 } 4148 4149 SettingBase sb = (SettingBase) pkg.mExtras; 4150 if (sb == null) { 4151 throw new IllegalArgumentException("Unknown package: " + packageName); 4152 } 4153 4154 PermissionsState permissionsState = sb.getPermissionsState(); 4155 return permissionsState.getPermissionFlags(name, userId); 4156 } 4157 } 4158 4159 @Override 4160 public void updatePermissionFlags(String name, String packageName, int flagMask, 4161 int flagValues, int userId) { 4162 if (!sUserManager.exists(userId)) { 4163 return; 4164 } 4165 4166 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4167 4168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4169 true /* requireFullPermission */, true /* checkShell */, 4170 "updatePermissionFlags"); 4171 4172 // Only the system can change these flags and nothing else. 4173 if (getCallingUid() != Process.SYSTEM_UID) { 4174 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4175 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4176 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4177 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4178 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4179 } 4180 4181 synchronized (mPackages) { 4182 final PackageParser.Package pkg = mPackages.get(packageName); 4183 if (pkg == null) { 4184 throw new IllegalArgumentException("Unknown package: " + packageName); 4185 } 4186 4187 final BasePermission bp = mSettings.mPermissions.get(name); 4188 if (bp == null) { 4189 throw new IllegalArgumentException("Unknown permission: " + name); 4190 } 4191 4192 SettingBase sb = (SettingBase) pkg.mExtras; 4193 if (sb == null) { 4194 throw new IllegalArgumentException("Unknown package: " + packageName); 4195 } 4196 4197 PermissionsState permissionsState = sb.getPermissionsState(); 4198 4199 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4200 4201 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4202 // Install and runtime permissions are stored in different places, 4203 // so figure out what permission changed and persist the change. 4204 if (permissionsState.getInstallPermissionState(name) != null) { 4205 scheduleWriteSettingsLocked(); 4206 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4207 || hadState) { 4208 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4209 } 4210 } 4211 } 4212 } 4213 4214 /** 4215 * Update the permission flags for all packages and runtime permissions of a user in order 4216 * to allow device or profile owner to remove POLICY_FIXED. 4217 */ 4218 @Override 4219 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4220 if (!sUserManager.exists(userId)) { 4221 return; 4222 } 4223 4224 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4225 4226 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4227 true /* requireFullPermission */, true /* checkShell */, 4228 "updatePermissionFlagsForAllApps"); 4229 4230 // Only the system can change system fixed flags. 4231 if (getCallingUid() != Process.SYSTEM_UID) { 4232 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4233 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4234 } 4235 4236 synchronized (mPackages) { 4237 boolean changed = false; 4238 final int packageCount = mPackages.size(); 4239 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4240 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4241 SettingBase sb = (SettingBase) pkg.mExtras; 4242 if (sb == null) { 4243 continue; 4244 } 4245 PermissionsState permissionsState = sb.getPermissionsState(); 4246 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4247 userId, flagMask, flagValues); 4248 } 4249 if (changed) { 4250 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4251 } 4252 } 4253 } 4254 4255 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4256 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4257 != PackageManager.PERMISSION_GRANTED 4258 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4259 != PackageManager.PERMISSION_GRANTED) { 4260 throw new SecurityException(message + " requires " 4261 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4262 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4263 } 4264 } 4265 4266 @Override 4267 public boolean shouldShowRequestPermissionRationale(String permissionName, 4268 String packageName, int userId) { 4269 if (UserHandle.getCallingUserId() != userId) { 4270 mContext.enforceCallingPermission( 4271 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4272 "canShowRequestPermissionRationale for user " + userId); 4273 } 4274 4275 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4276 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4277 return false; 4278 } 4279 4280 if (checkPermission(permissionName, packageName, userId) 4281 == PackageManager.PERMISSION_GRANTED) { 4282 return false; 4283 } 4284 4285 final int flags; 4286 4287 final long identity = Binder.clearCallingIdentity(); 4288 try { 4289 flags = getPermissionFlags(permissionName, 4290 packageName, userId); 4291 } finally { 4292 Binder.restoreCallingIdentity(identity); 4293 } 4294 4295 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4296 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4297 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4298 4299 if ((flags & fixedFlags) != 0) { 4300 return false; 4301 } 4302 4303 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4304 } 4305 4306 @Override 4307 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4308 mContext.enforceCallingOrSelfPermission( 4309 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4310 "addOnPermissionsChangeListener"); 4311 4312 synchronized (mPackages) { 4313 mOnPermissionChangeListeners.addListenerLocked(listener); 4314 } 4315 } 4316 4317 @Override 4318 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4319 synchronized (mPackages) { 4320 mOnPermissionChangeListeners.removeListenerLocked(listener); 4321 } 4322 } 4323 4324 @Override 4325 public boolean isProtectedBroadcast(String actionName) { 4326 synchronized (mPackages) { 4327 if (mProtectedBroadcasts.contains(actionName)) { 4328 return true; 4329 } else if (actionName != null) { 4330 // TODO: remove these terrible hacks 4331 if (actionName.startsWith("android.net.netmon.lingerExpired") 4332 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4333 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4334 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4335 return true; 4336 } 4337 } 4338 } 4339 return false; 4340 } 4341 4342 @Override 4343 public int checkSignatures(String pkg1, String pkg2) { 4344 synchronized (mPackages) { 4345 final PackageParser.Package p1 = mPackages.get(pkg1); 4346 final PackageParser.Package p2 = mPackages.get(pkg2); 4347 if (p1 == null || p1.mExtras == null 4348 || p2 == null || p2.mExtras == null) { 4349 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4350 } 4351 return compareSignatures(p1.mSignatures, p2.mSignatures); 4352 } 4353 } 4354 4355 @Override 4356 public int checkUidSignatures(int uid1, int uid2) { 4357 // Map to base uids. 4358 uid1 = UserHandle.getAppId(uid1); 4359 uid2 = UserHandle.getAppId(uid2); 4360 // reader 4361 synchronized (mPackages) { 4362 Signature[] s1; 4363 Signature[] s2; 4364 Object obj = mSettings.getUserIdLPr(uid1); 4365 if (obj != null) { 4366 if (obj instanceof SharedUserSetting) { 4367 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4368 } else if (obj instanceof PackageSetting) { 4369 s1 = ((PackageSetting)obj).signatures.mSignatures; 4370 } else { 4371 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4372 } 4373 } else { 4374 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4375 } 4376 obj = mSettings.getUserIdLPr(uid2); 4377 if (obj != null) { 4378 if (obj instanceof SharedUserSetting) { 4379 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4380 } else if (obj instanceof PackageSetting) { 4381 s2 = ((PackageSetting)obj).signatures.mSignatures; 4382 } else { 4383 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4384 } 4385 } else { 4386 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4387 } 4388 return compareSignatures(s1, s2); 4389 } 4390 } 4391 4392 private void killUid(int appId, int userId, String reason) { 4393 final long identity = Binder.clearCallingIdentity(); 4394 try { 4395 IActivityManager am = ActivityManagerNative.getDefault(); 4396 if (am != null) { 4397 try { 4398 am.killUid(appId, userId, reason); 4399 } catch (RemoteException e) { 4400 /* ignore - same process */ 4401 } 4402 } 4403 } finally { 4404 Binder.restoreCallingIdentity(identity); 4405 } 4406 } 4407 4408 /** 4409 * Compares two sets of signatures. Returns: 4410 * <br /> 4411 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4412 * <br /> 4413 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4414 * <br /> 4415 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4416 * <br /> 4417 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4418 * <br /> 4419 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4420 */ 4421 static int compareSignatures(Signature[] s1, Signature[] s2) { 4422 if (s1 == null) { 4423 return s2 == null 4424 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4425 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4426 } 4427 4428 if (s2 == null) { 4429 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4430 } 4431 4432 if (s1.length != s2.length) { 4433 return PackageManager.SIGNATURE_NO_MATCH; 4434 } 4435 4436 // Since both signature sets are of size 1, we can compare without HashSets. 4437 if (s1.length == 1) { 4438 return s1[0].equals(s2[0]) ? 4439 PackageManager.SIGNATURE_MATCH : 4440 PackageManager.SIGNATURE_NO_MATCH; 4441 } 4442 4443 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4444 for (Signature sig : s1) { 4445 set1.add(sig); 4446 } 4447 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4448 for (Signature sig : s2) { 4449 set2.add(sig); 4450 } 4451 // Make sure s2 contains all signatures in s1. 4452 if (set1.equals(set2)) { 4453 return PackageManager.SIGNATURE_MATCH; 4454 } 4455 return PackageManager.SIGNATURE_NO_MATCH; 4456 } 4457 4458 /** 4459 * If the database version for this type of package (internal storage or 4460 * external storage) is less than the version where package signatures 4461 * were updated, return true. 4462 */ 4463 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4464 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4465 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4466 } 4467 4468 /** 4469 * Used for backward compatibility to make sure any packages with 4470 * certificate chains get upgraded to the new style. {@code existingSigs} 4471 * will be in the old format (since they were stored on disk from before the 4472 * system upgrade) and {@code scannedSigs} will be in the newer format. 4473 */ 4474 private int compareSignaturesCompat(PackageSignatures existingSigs, 4475 PackageParser.Package scannedPkg) { 4476 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4477 return PackageManager.SIGNATURE_NO_MATCH; 4478 } 4479 4480 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4481 for (Signature sig : existingSigs.mSignatures) { 4482 existingSet.add(sig); 4483 } 4484 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4485 for (Signature sig : scannedPkg.mSignatures) { 4486 try { 4487 Signature[] chainSignatures = sig.getChainSignatures(); 4488 for (Signature chainSig : chainSignatures) { 4489 scannedCompatSet.add(chainSig); 4490 } 4491 } catch (CertificateEncodingException e) { 4492 scannedCompatSet.add(sig); 4493 } 4494 } 4495 /* 4496 * Make sure the expanded scanned set contains all signatures in the 4497 * existing one. 4498 */ 4499 if (scannedCompatSet.equals(existingSet)) { 4500 // Migrate the old signatures to the new scheme. 4501 existingSigs.assignSignatures(scannedPkg.mSignatures); 4502 // The new KeySets will be re-added later in the scanning process. 4503 synchronized (mPackages) { 4504 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4505 } 4506 return PackageManager.SIGNATURE_MATCH; 4507 } 4508 return PackageManager.SIGNATURE_NO_MATCH; 4509 } 4510 4511 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4512 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4513 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4514 } 4515 4516 private int compareSignaturesRecover(PackageSignatures existingSigs, 4517 PackageParser.Package scannedPkg) { 4518 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4519 return PackageManager.SIGNATURE_NO_MATCH; 4520 } 4521 4522 String msg = null; 4523 try { 4524 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4525 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4526 + scannedPkg.packageName); 4527 return PackageManager.SIGNATURE_MATCH; 4528 } 4529 } catch (CertificateException e) { 4530 msg = e.getMessage(); 4531 } 4532 4533 logCriticalInfo(Log.INFO, 4534 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4535 return PackageManager.SIGNATURE_NO_MATCH; 4536 } 4537 4538 @Override 4539 public List<String> getAllPackages() { 4540 synchronized (mPackages) { 4541 return new ArrayList<String>(mPackages.keySet()); 4542 } 4543 } 4544 4545 @Override 4546 public String[] getPackagesForUid(int uid) { 4547 uid = UserHandle.getAppId(uid); 4548 // reader 4549 synchronized (mPackages) { 4550 Object obj = mSettings.getUserIdLPr(uid); 4551 if (obj instanceof SharedUserSetting) { 4552 final SharedUserSetting sus = (SharedUserSetting) obj; 4553 final int N = sus.packages.size(); 4554 final String[] res = new String[N]; 4555 final Iterator<PackageSetting> it = sus.packages.iterator(); 4556 int i = 0; 4557 while (it.hasNext()) { 4558 res[i++] = it.next().name; 4559 } 4560 return res; 4561 } else if (obj instanceof PackageSetting) { 4562 final PackageSetting ps = (PackageSetting) obj; 4563 return new String[] { ps.name }; 4564 } 4565 } 4566 return null; 4567 } 4568 4569 @Override 4570 public String getNameForUid(int uid) { 4571 // reader 4572 synchronized (mPackages) { 4573 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4574 if (obj instanceof SharedUserSetting) { 4575 final SharedUserSetting sus = (SharedUserSetting) obj; 4576 return sus.name + ":" + sus.userId; 4577 } else if (obj instanceof PackageSetting) { 4578 final PackageSetting ps = (PackageSetting) obj; 4579 return ps.name; 4580 } 4581 } 4582 return null; 4583 } 4584 4585 @Override 4586 public int getUidForSharedUser(String sharedUserName) { 4587 if(sharedUserName == null) { 4588 return -1; 4589 } 4590 // reader 4591 synchronized (mPackages) { 4592 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4593 if (suid == null) { 4594 return -1; 4595 } 4596 return suid.userId; 4597 } 4598 } 4599 4600 @Override 4601 public int getFlagsForUid(int uid) { 4602 synchronized (mPackages) { 4603 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4604 if (obj instanceof SharedUserSetting) { 4605 final SharedUserSetting sus = (SharedUserSetting) obj; 4606 return sus.pkgFlags; 4607 } else if (obj instanceof PackageSetting) { 4608 final PackageSetting ps = (PackageSetting) obj; 4609 return ps.pkgFlags; 4610 } 4611 } 4612 return 0; 4613 } 4614 4615 @Override 4616 public int getPrivateFlagsForUid(int uid) { 4617 synchronized (mPackages) { 4618 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4619 if (obj instanceof SharedUserSetting) { 4620 final SharedUserSetting sus = (SharedUserSetting) obj; 4621 return sus.pkgPrivateFlags; 4622 } else if (obj instanceof PackageSetting) { 4623 final PackageSetting ps = (PackageSetting) obj; 4624 return ps.pkgPrivateFlags; 4625 } 4626 } 4627 return 0; 4628 } 4629 4630 @Override 4631 public boolean isUidPrivileged(int uid) { 4632 uid = UserHandle.getAppId(uid); 4633 // reader 4634 synchronized (mPackages) { 4635 Object obj = mSettings.getUserIdLPr(uid); 4636 if (obj instanceof SharedUserSetting) { 4637 final SharedUserSetting sus = (SharedUserSetting) obj; 4638 final Iterator<PackageSetting> it = sus.packages.iterator(); 4639 while (it.hasNext()) { 4640 if (it.next().isPrivileged()) { 4641 return true; 4642 } 4643 } 4644 } else if (obj instanceof PackageSetting) { 4645 final PackageSetting ps = (PackageSetting) obj; 4646 return ps.isPrivileged(); 4647 } 4648 } 4649 return false; 4650 } 4651 4652 @Override 4653 public String[] getAppOpPermissionPackages(String permissionName) { 4654 synchronized (mPackages) { 4655 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4656 if (pkgs == null) { 4657 return null; 4658 } 4659 return pkgs.toArray(new String[pkgs.size()]); 4660 } 4661 } 4662 4663 @Override 4664 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4665 int flags, int userId) { 4666 if (!sUserManager.exists(userId)) return null; 4667 flags = updateFlagsForResolve(flags, userId, intent); 4668 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4669 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4670 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4671 userId); 4672 final ResolveInfo bestChoice = 4673 chooseBestActivity(intent, resolvedType, flags, query, userId); 4674 4675 if (isEphemeralAllowed(intent, query, userId)) { 4676 final EphemeralResolveInfo ai = 4677 getEphemeralResolveInfo(intent, resolvedType, userId); 4678 if (ai != null) { 4679 if (DEBUG_EPHEMERAL) { 4680 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4681 } 4682 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4683 bestChoice.ephemeralResolveInfo = ai; 4684 } 4685 } 4686 return bestChoice; 4687 } 4688 4689 @Override 4690 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4691 IntentFilter filter, int match, ComponentName activity) { 4692 final int userId = UserHandle.getCallingUserId(); 4693 if (DEBUG_PREFERRED) { 4694 Log.v(TAG, "setLastChosenActivity intent=" + intent 4695 + " resolvedType=" + resolvedType 4696 + " flags=" + flags 4697 + " filter=" + filter 4698 + " match=" + match 4699 + " activity=" + activity); 4700 filter.dump(new PrintStreamPrinter(System.out), " "); 4701 } 4702 intent.setComponent(null); 4703 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4704 userId); 4705 // Find any earlier preferred or last chosen entries and nuke them 4706 findPreferredActivity(intent, resolvedType, 4707 flags, query, 0, false, true, false, userId); 4708 // Add the new activity as the last chosen for this filter 4709 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4710 "Setting last chosen"); 4711 } 4712 4713 @Override 4714 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4715 final int userId = UserHandle.getCallingUserId(); 4716 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4717 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4718 userId); 4719 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4720 false, false, false, userId); 4721 } 4722 4723 4724 private boolean isEphemeralAllowed( 4725 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4726 // Short circuit and return early if possible. 4727 if (DISABLE_EPHEMERAL_APPS) { 4728 return false; 4729 } 4730 final int callingUser = UserHandle.getCallingUserId(); 4731 if (callingUser != UserHandle.USER_SYSTEM) { 4732 return false; 4733 } 4734 if (mEphemeralResolverConnection == null) { 4735 return false; 4736 } 4737 if (intent.getComponent() != null) { 4738 return false; 4739 } 4740 if (intent.getPackage() != null) { 4741 return false; 4742 } 4743 final boolean isWebUri = hasWebURI(intent); 4744 if (!isWebUri) { 4745 return false; 4746 } 4747 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4748 synchronized (mPackages) { 4749 final int count = resolvedActivites.size(); 4750 for (int n = 0; n < count; n++) { 4751 ResolveInfo info = resolvedActivites.get(n); 4752 String packageName = info.activityInfo.packageName; 4753 PackageSetting ps = mSettings.mPackages.get(packageName); 4754 if (ps != null) { 4755 // Try to get the status from User settings first 4756 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4757 int status = (int) (packedStatus >> 32); 4758 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4759 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4760 if (DEBUG_EPHEMERAL) { 4761 Slog.v(TAG, "DENY ephemeral apps;" 4762 + " pkg: " + packageName + ", status: " + status); 4763 } 4764 return false; 4765 } 4766 } 4767 } 4768 } 4769 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4770 return true; 4771 } 4772 4773 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4774 int userId) { 4775 MessageDigest digest = null; 4776 try { 4777 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4778 } catch (NoSuchAlgorithmException e) { 4779 // If we can't create a digest, ignore ephemeral apps. 4780 return null; 4781 } 4782 4783 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4784 final byte[] digestBytes = digest.digest(hostBytes); 4785 int shaPrefix = 4786 digestBytes[0] << 24 4787 | digestBytes[1] << 16 4788 | digestBytes[2] << 8 4789 | digestBytes[3] << 0; 4790 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4791 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4792 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4793 // No hash prefix match; there are no ephemeral apps for this domain. 4794 return null; 4795 } 4796 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4797 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4798 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4799 continue; 4800 } 4801 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4802 // No filters; this should never happen. 4803 if (filters.isEmpty()) { 4804 continue; 4805 } 4806 // We have a domain match; resolve the filters to see if anything matches. 4807 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4808 for (int j = filters.size() - 1; j >= 0; --j) { 4809 final EphemeralResolveIntentInfo intentInfo = 4810 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4811 ephemeralResolver.addFilter(intentInfo); 4812 } 4813 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4814 intent, resolvedType, false /*defaultOnly*/, userId); 4815 if (!matchedResolveInfoList.isEmpty()) { 4816 return matchedResolveInfoList.get(0); 4817 } 4818 } 4819 // Hash or filter mis-match; no ephemeral apps for this domain. 4820 return null; 4821 } 4822 4823 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4824 int flags, List<ResolveInfo> query, int userId) { 4825 if (query != null) { 4826 final int N = query.size(); 4827 if (N == 1) { 4828 return query.get(0); 4829 } else if (N > 1) { 4830 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4831 // If there is more than one activity with the same priority, 4832 // then let the user decide between them. 4833 ResolveInfo r0 = query.get(0); 4834 ResolveInfo r1 = query.get(1); 4835 if (DEBUG_INTENT_MATCHING || debug) { 4836 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4837 + r1.activityInfo.name + "=" + r1.priority); 4838 } 4839 // If the first activity has a higher priority, or a different 4840 // default, then it is always desirable to pick it. 4841 if (r0.priority != r1.priority 4842 || r0.preferredOrder != r1.preferredOrder 4843 || r0.isDefault != r1.isDefault) { 4844 return query.get(0); 4845 } 4846 // If we have saved a preference for a preferred activity for 4847 // this Intent, use that. 4848 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4849 flags, query, r0.priority, true, false, debug, userId); 4850 if (ri != null) { 4851 return ri; 4852 } 4853 ri = new ResolveInfo(mResolveInfo); 4854 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4855 ri.activityInfo.applicationInfo = new ApplicationInfo( 4856 ri.activityInfo.applicationInfo); 4857 if (userId != 0) { 4858 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4859 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4860 } 4861 // Make sure that the resolver is displayable in car mode 4862 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4863 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4864 return ri; 4865 } 4866 } 4867 return null; 4868 } 4869 4870 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4871 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4872 final int N = query.size(); 4873 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4874 .get(userId); 4875 // Get the list of persistent preferred activities that handle the intent 4876 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4877 List<PersistentPreferredActivity> pprefs = ppir != null 4878 ? ppir.queryIntent(intent, resolvedType, 4879 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4880 : null; 4881 if (pprefs != null && pprefs.size() > 0) { 4882 final int M = pprefs.size(); 4883 for (int i=0; i<M; i++) { 4884 final PersistentPreferredActivity ppa = pprefs.get(i); 4885 if (DEBUG_PREFERRED || debug) { 4886 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4887 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4888 + "\n component=" + ppa.mComponent); 4889 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4890 } 4891 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4892 flags | MATCH_DISABLED_COMPONENTS, userId); 4893 if (DEBUG_PREFERRED || debug) { 4894 Slog.v(TAG, "Found persistent preferred activity:"); 4895 if (ai != null) { 4896 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4897 } else { 4898 Slog.v(TAG, " null"); 4899 } 4900 } 4901 if (ai == null) { 4902 // This previously registered persistent preferred activity 4903 // component is no longer known. Ignore it and do NOT remove it. 4904 continue; 4905 } 4906 for (int j=0; j<N; j++) { 4907 final ResolveInfo ri = query.get(j); 4908 if (!ri.activityInfo.applicationInfo.packageName 4909 .equals(ai.applicationInfo.packageName)) { 4910 continue; 4911 } 4912 if (!ri.activityInfo.name.equals(ai.name)) { 4913 continue; 4914 } 4915 // Found a persistent preference that can handle the intent. 4916 if (DEBUG_PREFERRED || debug) { 4917 Slog.v(TAG, "Returning persistent preferred activity: " + 4918 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4919 } 4920 return ri; 4921 } 4922 } 4923 } 4924 return null; 4925 } 4926 4927 // TODO: handle preferred activities missing while user has amnesia 4928 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4929 List<ResolveInfo> query, int priority, boolean always, 4930 boolean removeMatches, boolean debug, int userId) { 4931 if (!sUserManager.exists(userId)) return null; 4932 flags = updateFlagsForResolve(flags, userId, intent); 4933 // writer 4934 synchronized (mPackages) { 4935 if (intent.getSelector() != null) { 4936 intent = intent.getSelector(); 4937 } 4938 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4939 4940 // Try to find a matching persistent preferred activity. 4941 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4942 debug, userId); 4943 4944 // If a persistent preferred activity matched, use it. 4945 if (pri != null) { 4946 return pri; 4947 } 4948 4949 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4950 // Get the list of preferred activities that handle the intent 4951 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4952 List<PreferredActivity> prefs = pir != null 4953 ? pir.queryIntent(intent, resolvedType, 4954 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4955 : null; 4956 if (prefs != null && prefs.size() > 0) { 4957 boolean changed = false; 4958 try { 4959 // First figure out how good the original match set is. 4960 // We will only allow preferred activities that came 4961 // from the same match quality. 4962 int match = 0; 4963 4964 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4965 4966 final int N = query.size(); 4967 for (int j=0; j<N; j++) { 4968 final ResolveInfo ri = query.get(j); 4969 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4970 + ": 0x" + Integer.toHexString(match)); 4971 if (ri.match > match) { 4972 match = ri.match; 4973 } 4974 } 4975 4976 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4977 + Integer.toHexString(match)); 4978 4979 match &= IntentFilter.MATCH_CATEGORY_MASK; 4980 final int M = prefs.size(); 4981 for (int i=0; i<M; i++) { 4982 final PreferredActivity pa = prefs.get(i); 4983 if (DEBUG_PREFERRED || debug) { 4984 Slog.v(TAG, "Checking PreferredActivity ds=" 4985 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4986 + "\n component=" + pa.mPref.mComponent); 4987 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4988 } 4989 if (pa.mPref.mMatch != match) { 4990 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4991 + Integer.toHexString(pa.mPref.mMatch)); 4992 continue; 4993 } 4994 // If it's not an "always" type preferred activity and that's what we're 4995 // looking for, skip it. 4996 if (always && !pa.mPref.mAlways) { 4997 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4998 continue; 4999 } 5000 final ActivityInfo ai = getActivityInfo( 5001 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5002 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5003 userId); 5004 if (DEBUG_PREFERRED || debug) { 5005 Slog.v(TAG, "Found preferred activity:"); 5006 if (ai != null) { 5007 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5008 } else { 5009 Slog.v(TAG, " null"); 5010 } 5011 } 5012 if (ai == null) { 5013 // This previously registered preferred activity 5014 // component is no longer known. Most likely an update 5015 // to the app was installed and in the new version this 5016 // component no longer exists. Clean it up by removing 5017 // it from the preferred activities list, and skip it. 5018 Slog.w(TAG, "Removing dangling preferred activity: " 5019 + pa.mPref.mComponent); 5020 pir.removeFilter(pa); 5021 changed = true; 5022 continue; 5023 } 5024 for (int j=0; j<N; j++) { 5025 final ResolveInfo ri = query.get(j); 5026 if (!ri.activityInfo.applicationInfo.packageName 5027 .equals(ai.applicationInfo.packageName)) { 5028 continue; 5029 } 5030 if (!ri.activityInfo.name.equals(ai.name)) { 5031 continue; 5032 } 5033 5034 if (removeMatches) { 5035 pir.removeFilter(pa); 5036 changed = true; 5037 if (DEBUG_PREFERRED) { 5038 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5039 } 5040 break; 5041 } 5042 5043 // Okay we found a previously set preferred or last chosen app. 5044 // If the result set is different from when this 5045 // was created, we need to clear it and re-ask the 5046 // user their preference, if we're looking for an "always" type entry. 5047 if (always && !pa.mPref.sameSet(query)) { 5048 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5049 + intent + " type " + resolvedType); 5050 if (DEBUG_PREFERRED) { 5051 Slog.v(TAG, "Removing preferred activity since set changed " 5052 + pa.mPref.mComponent); 5053 } 5054 pir.removeFilter(pa); 5055 // Re-add the filter as a "last chosen" entry (!always) 5056 PreferredActivity lastChosen = new PreferredActivity( 5057 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5058 pir.addFilter(lastChosen); 5059 changed = true; 5060 return null; 5061 } 5062 5063 // Yay! Either the set matched or we're looking for the last chosen 5064 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5065 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5066 return ri; 5067 } 5068 } 5069 } finally { 5070 if (changed) { 5071 if (DEBUG_PREFERRED) { 5072 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5073 } 5074 scheduleWritePackageRestrictionsLocked(userId); 5075 } 5076 } 5077 } 5078 } 5079 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5080 return null; 5081 } 5082 5083 /* 5084 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5085 */ 5086 @Override 5087 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5088 int targetUserId) { 5089 mContext.enforceCallingOrSelfPermission( 5090 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5091 List<CrossProfileIntentFilter> matches = 5092 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5093 if (matches != null) { 5094 int size = matches.size(); 5095 for (int i = 0; i < size; i++) { 5096 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5097 } 5098 } 5099 if (hasWebURI(intent)) { 5100 // cross-profile app linking works only towards the parent. 5101 final UserInfo parent = getProfileParent(sourceUserId); 5102 synchronized(mPackages) { 5103 int flags = updateFlagsForResolve(0, parent.id, intent); 5104 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5105 intent, resolvedType, flags, sourceUserId, parent.id); 5106 return xpDomainInfo != null; 5107 } 5108 } 5109 return false; 5110 } 5111 5112 private UserInfo getProfileParent(int userId) { 5113 final long identity = Binder.clearCallingIdentity(); 5114 try { 5115 return sUserManager.getProfileParent(userId); 5116 } finally { 5117 Binder.restoreCallingIdentity(identity); 5118 } 5119 } 5120 5121 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5122 String resolvedType, int userId) { 5123 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5124 if (resolver != null) { 5125 return resolver.queryIntent(intent, resolvedType, false, userId); 5126 } 5127 return null; 5128 } 5129 5130 @Override 5131 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5132 String resolvedType, int flags, int userId) { 5133 return new ParceledListSlice<>( 5134 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5135 } 5136 5137 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5138 String resolvedType, int flags, int userId) { 5139 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5140 flags = updateFlagsForResolve(flags, userId, intent); 5141 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5142 false /* requireFullPermission */, false /* checkShell */, 5143 "query intent activities"); 5144 ComponentName comp = intent.getComponent(); 5145 if (comp == null) { 5146 if (intent.getSelector() != null) { 5147 intent = intent.getSelector(); 5148 comp = intent.getComponent(); 5149 } 5150 } 5151 5152 if (comp != null) { 5153 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5154 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5155 if (ai != null) { 5156 final ResolveInfo ri = new ResolveInfo(); 5157 ri.activityInfo = ai; 5158 list.add(ri); 5159 } 5160 return list; 5161 } 5162 5163 // reader 5164 synchronized (mPackages) { 5165 final String pkgName = intent.getPackage(); 5166 if (pkgName == null) { 5167 List<CrossProfileIntentFilter> matchingFilters = 5168 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5169 // Check for results that need to skip the current profile. 5170 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5171 resolvedType, flags, userId); 5172 if (xpResolveInfo != null) { 5173 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5174 result.add(xpResolveInfo); 5175 return filterIfNotSystemUser(result, userId); 5176 } 5177 5178 // Check for results in the current profile. 5179 List<ResolveInfo> result = mActivities.queryIntent( 5180 intent, resolvedType, flags, userId); 5181 result = filterIfNotSystemUser(result, userId); 5182 5183 // Check for cross profile results. 5184 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5185 xpResolveInfo = queryCrossProfileIntents( 5186 matchingFilters, intent, resolvedType, flags, userId, 5187 hasNonNegativePriorityResult); 5188 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5189 boolean isVisibleToUser = filterIfNotSystemUser( 5190 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5191 if (isVisibleToUser) { 5192 result.add(xpResolveInfo); 5193 Collections.sort(result, mResolvePrioritySorter); 5194 } 5195 } 5196 if (hasWebURI(intent)) { 5197 CrossProfileDomainInfo xpDomainInfo = null; 5198 final UserInfo parent = getProfileParent(userId); 5199 if (parent != null) { 5200 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5201 flags, userId, parent.id); 5202 } 5203 if (xpDomainInfo != null) { 5204 if (xpResolveInfo != null) { 5205 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5206 // in the result. 5207 result.remove(xpResolveInfo); 5208 } 5209 if (result.size() == 0) { 5210 result.add(xpDomainInfo.resolveInfo); 5211 return result; 5212 } 5213 } else if (result.size() <= 1) { 5214 return result; 5215 } 5216 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5217 xpDomainInfo, userId); 5218 Collections.sort(result, mResolvePrioritySorter); 5219 } 5220 return result; 5221 } 5222 final PackageParser.Package pkg = mPackages.get(pkgName); 5223 if (pkg != null) { 5224 return filterIfNotSystemUser( 5225 mActivities.queryIntentForPackage( 5226 intent, resolvedType, flags, pkg.activities, userId), 5227 userId); 5228 } 5229 return new ArrayList<ResolveInfo>(); 5230 } 5231 } 5232 5233 private static class CrossProfileDomainInfo { 5234 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5235 ResolveInfo resolveInfo; 5236 /* Best domain verification status of the activities found in the other profile */ 5237 int bestDomainVerificationStatus; 5238 } 5239 5240 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5241 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5242 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5243 sourceUserId)) { 5244 return null; 5245 } 5246 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5247 resolvedType, flags, parentUserId); 5248 5249 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5250 return null; 5251 } 5252 CrossProfileDomainInfo result = null; 5253 int size = resultTargetUser.size(); 5254 for (int i = 0; i < size; i++) { 5255 ResolveInfo riTargetUser = resultTargetUser.get(i); 5256 // Intent filter verification is only for filters that specify a host. So don't return 5257 // those that handle all web uris. 5258 if (riTargetUser.handleAllWebDataURI) { 5259 continue; 5260 } 5261 String packageName = riTargetUser.activityInfo.packageName; 5262 PackageSetting ps = mSettings.mPackages.get(packageName); 5263 if (ps == null) { 5264 continue; 5265 } 5266 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5267 int status = (int)(verificationState >> 32); 5268 if (result == null) { 5269 result = new CrossProfileDomainInfo(); 5270 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5271 sourceUserId, parentUserId); 5272 result.bestDomainVerificationStatus = status; 5273 } else { 5274 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5275 result.bestDomainVerificationStatus); 5276 } 5277 } 5278 // Don't consider matches with status NEVER across profiles. 5279 if (result != null && result.bestDomainVerificationStatus 5280 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5281 return null; 5282 } 5283 return result; 5284 } 5285 5286 /** 5287 * Verification statuses are ordered from the worse to the best, except for 5288 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5289 */ 5290 private int bestDomainVerificationStatus(int status1, int status2) { 5291 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5292 return status2; 5293 } 5294 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5295 return status1; 5296 } 5297 return (int) MathUtils.max(status1, status2); 5298 } 5299 5300 private boolean isUserEnabled(int userId) { 5301 long callingId = Binder.clearCallingIdentity(); 5302 try { 5303 UserInfo userInfo = sUserManager.getUserInfo(userId); 5304 return userInfo != null && userInfo.isEnabled(); 5305 } finally { 5306 Binder.restoreCallingIdentity(callingId); 5307 } 5308 } 5309 5310 /** 5311 * Filter out activities with systemUserOnly flag set, when current user is not System. 5312 * 5313 * @return filtered list 5314 */ 5315 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5316 if (userId == UserHandle.USER_SYSTEM) { 5317 return resolveInfos; 5318 } 5319 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5320 ResolveInfo info = resolveInfos.get(i); 5321 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5322 resolveInfos.remove(i); 5323 } 5324 } 5325 return resolveInfos; 5326 } 5327 5328 /** 5329 * @param resolveInfos list of resolve infos in descending priority order 5330 * @return if the list contains a resolve info with non-negative priority 5331 */ 5332 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5333 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5334 } 5335 5336 private static boolean hasWebURI(Intent intent) { 5337 if (intent.getData() == null) { 5338 return false; 5339 } 5340 final String scheme = intent.getScheme(); 5341 if (TextUtils.isEmpty(scheme)) { 5342 return false; 5343 } 5344 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5345 } 5346 5347 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5348 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5349 int userId) { 5350 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5351 5352 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5353 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5354 candidates.size()); 5355 } 5356 5357 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5358 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5359 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5360 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5361 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5362 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5363 5364 synchronized (mPackages) { 5365 final int count = candidates.size(); 5366 // First, try to use linked apps. Partition the candidates into four lists: 5367 // one for the final results, one for the "do not use ever", one for "undefined status" 5368 // and finally one for "browser app type". 5369 for (int n=0; n<count; n++) { 5370 ResolveInfo info = candidates.get(n); 5371 String packageName = info.activityInfo.packageName; 5372 PackageSetting ps = mSettings.mPackages.get(packageName); 5373 if (ps != null) { 5374 // Add to the special match all list (Browser use case) 5375 if (info.handleAllWebDataURI) { 5376 matchAllList.add(info); 5377 continue; 5378 } 5379 // Try to get the status from User settings first 5380 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5381 int status = (int)(packedStatus >> 32); 5382 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5383 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5384 if (DEBUG_DOMAIN_VERIFICATION) { 5385 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5386 + " : linkgen=" + linkGeneration); 5387 } 5388 // Use link-enabled generation as preferredOrder, i.e. 5389 // prefer newly-enabled over earlier-enabled. 5390 info.preferredOrder = linkGeneration; 5391 alwaysList.add(info); 5392 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5393 if (DEBUG_DOMAIN_VERIFICATION) { 5394 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5395 } 5396 neverList.add(info); 5397 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5398 if (DEBUG_DOMAIN_VERIFICATION) { 5399 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5400 } 5401 alwaysAskList.add(info); 5402 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5403 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5404 if (DEBUG_DOMAIN_VERIFICATION) { 5405 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5406 } 5407 undefinedList.add(info); 5408 } 5409 } 5410 } 5411 5412 // We'll want to include browser possibilities in a few cases 5413 boolean includeBrowser = false; 5414 5415 // First try to add the "always" resolution(s) for the current user, if any 5416 if (alwaysList.size() > 0) { 5417 result.addAll(alwaysList); 5418 } else { 5419 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5420 result.addAll(undefinedList); 5421 // Maybe add one for the other profile. 5422 if (xpDomainInfo != null && ( 5423 xpDomainInfo.bestDomainVerificationStatus 5424 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5425 result.add(xpDomainInfo.resolveInfo); 5426 } 5427 includeBrowser = true; 5428 } 5429 5430 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5431 // If there were 'always' entries their preferred order has been set, so we also 5432 // back that off to make the alternatives equivalent 5433 if (alwaysAskList.size() > 0) { 5434 for (ResolveInfo i : result) { 5435 i.preferredOrder = 0; 5436 } 5437 result.addAll(alwaysAskList); 5438 includeBrowser = true; 5439 } 5440 5441 if (includeBrowser) { 5442 // Also add browsers (all of them or only the default one) 5443 if (DEBUG_DOMAIN_VERIFICATION) { 5444 Slog.v(TAG, " ...including browsers in candidate set"); 5445 } 5446 if ((matchFlags & MATCH_ALL) != 0) { 5447 result.addAll(matchAllList); 5448 } else { 5449 // Browser/generic handling case. If there's a default browser, go straight 5450 // to that (but only if there is no other higher-priority match). 5451 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5452 int maxMatchPrio = 0; 5453 ResolveInfo defaultBrowserMatch = null; 5454 final int numCandidates = matchAllList.size(); 5455 for (int n = 0; n < numCandidates; n++) { 5456 ResolveInfo info = matchAllList.get(n); 5457 // track the highest overall match priority... 5458 if (info.priority > maxMatchPrio) { 5459 maxMatchPrio = info.priority; 5460 } 5461 // ...and the highest-priority default browser match 5462 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5463 if (defaultBrowserMatch == null 5464 || (defaultBrowserMatch.priority < info.priority)) { 5465 if (debug) { 5466 Slog.v(TAG, "Considering default browser match " + info); 5467 } 5468 defaultBrowserMatch = info; 5469 } 5470 } 5471 } 5472 if (defaultBrowserMatch != null 5473 && defaultBrowserMatch.priority >= maxMatchPrio 5474 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5475 { 5476 if (debug) { 5477 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5478 } 5479 result.add(defaultBrowserMatch); 5480 } else { 5481 result.addAll(matchAllList); 5482 } 5483 } 5484 5485 // If there is nothing selected, add all candidates and remove the ones that the user 5486 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5487 if (result.size() == 0) { 5488 result.addAll(candidates); 5489 result.removeAll(neverList); 5490 } 5491 } 5492 } 5493 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5494 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5495 result.size()); 5496 for (ResolveInfo info : result) { 5497 Slog.v(TAG, " + " + info.activityInfo); 5498 } 5499 } 5500 return result; 5501 } 5502 5503 // Returns a packed value as a long: 5504 // 5505 // high 'int'-sized word: link status: undefined/ask/never/always. 5506 // low 'int'-sized word: relative priority among 'always' results. 5507 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5508 long result = ps.getDomainVerificationStatusForUser(userId); 5509 // if none available, get the master status 5510 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5511 if (ps.getIntentFilterVerificationInfo() != null) { 5512 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5513 } 5514 } 5515 return result; 5516 } 5517 5518 private ResolveInfo querySkipCurrentProfileIntents( 5519 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5520 int flags, int sourceUserId) { 5521 if (matchingFilters != null) { 5522 int size = matchingFilters.size(); 5523 for (int i = 0; i < size; i ++) { 5524 CrossProfileIntentFilter filter = matchingFilters.get(i); 5525 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5526 // Checking if there are activities in the target user that can handle the 5527 // intent. 5528 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5529 resolvedType, flags, sourceUserId); 5530 if (resolveInfo != null) { 5531 return resolveInfo; 5532 } 5533 } 5534 } 5535 } 5536 return null; 5537 } 5538 5539 // Return matching ResolveInfo in target user if any. 5540 private ResolveInfo queryCrossProfileIntents( 5541 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5542 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5543 if (matchingFilters != null) { 5544 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5545 // match the same intent. For performance reasons, it is better not to 5546 // run queryIntent twice for the same userId 5547 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5548 int size = matchingFilters.size(); 5549 for (int i = 0; i < size; i++) { 5550 CrossProfileIntentFilter filter = matchingFilters.get(i); 5551 int targetUserId = filter.getTargetUserId(); 5552 boolean skipCurrentProfile = 5553 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5554 boolean skipCurrentProfileIfNoMatchFound = 5555 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5556 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5557 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5558 // Checking if there are activities in the target user that can handle the 5559 // intent. 5560 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5561 resolvedType, flags, sourceUserId); 5562 if (resolveInfo != null) return resolveInfo; 5563 alreadyTriedUserIds.put(targetUserId, true); 5564 } 5565 } 5566 } 5567 return null; 5568 } 5569 5570 /** 5571 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5572 * will forward the intent to the filter's target user. 5573 * Otherwise, returns null. 5574 */ 5575 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5576 String resolvedType, int flags, int sourceUserId) { 5577 int targetUserId = filter.getTargetUserId(); 5578 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5579 resolvedType, flags, targetUserId); 5580 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5581 // If all the matches in the target profile are suspended, return null. 5582 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5583 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5584 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5585 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5586 targetUserId); 5587 } 5588 } 5589 } 5590 return null; 5591 } 5592 5593 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5594 int sourceUserId, int targetUserId) { 5595 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5596 long ident = Binder.clearCallingIdentity(); 5597 boolean targetIsProfile; 5598 try { 5599 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5600 } finally { 5601 Binder.restoreCallingIdentity(ident); 5602 } 5603 String className; 5604 if (targetIsProfile) { 5605 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5606 } else { 5607 className = FORWARD_INTENT_TO_PARENT; 5608 } 5609 ComponentName forwardingActivityComponentName = new ComponentName( 5610 mAndroidApplication.packageName, className); 5611 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5612 sourceUserId); 5613 if (!targetIsProfile) { 5614 forwardingActivityInfo.showUserIcon = targetUserId; 5615 forwardingResolveInfo.noResourceId = true; 5616 } 5617 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5618 forwardingResolveInfo.priority = 0; 5619 forwardingResolveInfo.preferredOrder = 0; 5620 forwardingResolveInfo.match = 0; 5621 forwardingResolveInfo.isDefault = true; 5622 forwardingResolveInfo.filter = filter; 5623 forwardingResolveInfo.targetUserId = targetUserId; 5624 return forwardingResolveInfo; 5625 } 5626 5627 @Override 5628 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5629 Intent[] specifics, String[] specificTypes, Intent intent, 5630 String resolvedType, int flags, int userId) { 5631 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5632 specificTypes, intent, resolvedType, flags, userId)); 5633 } 5634 5635 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5636 Intent[] specifics, String[] specificTypes, Intent intent, 5637 String resolvedType, int flags, int userId) { 5638 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5639 flags = updateFlagsForResolve(flags, userId, intent); 5640 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5641 false /* requireFullPermission */, false /* checkShell */, 5642 "query intent activity options"); 5643 final String resultsAction = intent.getAction(); 5644 5645 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5646 | PackageManager.GET_RESOLVED_FILTER, userId); 5647 5648 if (DEBUG_INTENT_MATCHING) { 5649 Log.v(TAG, "Query " + intent + ": " + results); 5650 } 5651 5652 int specificsPos = 0; 5653 int N; 5654 5655 // todo: note that the algorithm used here is O(N^2). This 5656 // isn't a problem in our current environment, but if we start running 5657 // into situations where we have more than 5 or 10 matches then this 5658 // should probably be changed to something smarter... 5659 5660 // First we go through and resolve each of the specific items 5661 // that were supplied, taking care of removing any corresponding 5662 // duplicate items in the generic resolve list. 5663 if (specifics != null) { 5664 for (int i=0; i<specifics.length; i++) { 5665 final Intent sintent = specifics[i]; 5666 if (sintent == null) { 5667 continue; 5668 } 5669 5670 if (DEBUG_INTENT_MATCHING) { 5671 Log.v(TAG, "Specific #" + i + ": " + sintent); 5672 } 5673 5674 String action = sintent.getAction(); 5675 if (resultsAction != null && resultsAction.equals(action)) { 5676 // If this action was explicitly requested, then don't 5677 // remove things that have it. 5678 action = null; 5679 } 5680 5681 ResolveInfo ri = null; 5682 ActivityInfo ai = null; 5683 5684 ComponentName comp = sintent.getComponent(); 5685 if (comp == null) { 5686 ri = resolveIntent( 5687 sintent, 5688 specificTypes != null ? specificTypes[i] : null, 5689 flags, userId); 5690 if (ri == null) { 5691 continue; 5692 } 5693 if (ri == mResolveInfo) { 5694 // ACK! Must do something better with this. 5695 } 5696 ai = ri.activityInfo; 5697 comp = new ComponentName(ai.applicationInfo.packageName, 5698 ai.name); 5699 } else { 5700 ai = getActivityInfo(comp, flags, userId); 5701 if (ai == null) { 5702 continue; 5703 } 5704 } 5705 5706 // Look for any generic query activities that are duplicates 5707 // of this specific one, and remove them from the results. 5708 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5709 N = results.size(); 5710 int j; 5711 for (j=specificsPos; j<N; j++) { 5712 ResolveInfo sri = results.get(j); 5713 if ((sri.activityInfo.name.equals(comp.getClassName()) 5714 && sri.activityInfo.applicationInfo.packageName.equals( 5715 comp.getPackageName())) 5716 || (action != null && sri.filter.matchAction(action))) { 5717 results.remove(j); 5718 if (DEBUG_INTENT_MATCHING) Log.v( 5719 TAG, "Removing duplicate item from " + j 5720 + " due to specific " + specificsPos); 5721 if (ri == null) { 5722 ri = sri; 5723 } 5724 j--; 5725 N--; 5726 } 5727 } 5728 5729 // Add this specific item to its proper place. 5730 if (ri == null) { 5731 ri = new ResolveInfo(); 5732 ri.activityInfo = ai; 5733 } 5734 results.add(specificsPos, ri); 5735 ri.specificIndex = i; 5736 specificsPos++; 5737 } 5738 } 5739 5740 // Now we go through the remaining generic results and remove any 5741 // duplicate actions that are found here. 5742 N = results.size(); 5743 for (int i=specificsPos; i<N-1; i++) { 5744 final ResolveInfo rii = results.get(i); 5745 if (rii.filter == null) { 5746 continue; 5747 } 5748 5749 // Iterate over all of the actions of this result's intent 5750 // filter... typically this should be just one. 5751 final Iterator<String> it = rii.filter.actionsIterator(); 5752 if (it == null) { 5753 continue; 5754 } 5755 while (it.hasNext()) { 5756 final String action = it.next(); 5757 if (resultsAction != null && resultsAction.equals(action)) { 5758 // If this action was explicitly requested, then don't 5759 // remove things that have it. 5760 continue; 5761 } 5762 for (int j=i+1; j<N; j++) { 5763 final ResolveInfo rij = results.get(j); 5764 if (rij.filter != null && rij.filter.hasAction(action)) { 5765 results.remove(j); 5766 if (DEBUG_INTENT_MATCHING) Log.v( 5767 TAG, "Removing duplicate item from " + j 5768 + " due to action " + action + " at " + i); 5769 j--; 5770 N--; 5771 } 5772 } 5773 } 5774 5775 // If the caller didn't request filter information, drop it now 5776 // so we don't have to marshall/unmarshall it. 5777 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5778 rii.filter = null; 5779 } 5780 } 5781 5782 // Filter out the caller activity if so requested. 5783 if (caller != null) { 5784 N = results.size(); 5785 for (int i=0; i<N; i++) { 5786 ActivityInfo ainfo = results.get(i).activityInfo; 5787 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5788 && caller.getClassName().equals(ainfo.name)) { 5789 results.remove(i); 5790 break; 5791 } 5792 } 5793 } 5794 5795 // If the caller didn't request filter information, 5796 // drop them now so we don't have to 5797 // marshall/unmarshall it. 5798 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5799 N = results.size(); 5800 for (int i=0; i<N; i++) { 5801 results.get(i).filter = null; 5802 } 5803 } 5804 5805 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5806 return results; 5807 } 5808 5809 @Override 5810 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5811 String resolvedType, int flags, int userId) { 5812 return new ParceledListSlice<>( 5813 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5814 } 5815 5816 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5817 String resolvedType, int flags, int userId) { 5818 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5819 flags = updateFlagsForResolve(flags, userId, intent); 5820 ComponentName comp = intent.getComponent(); 5821 if (comp == null) { 5822 if (intent.getSelector() != null) { 5823 intent = intent.getSelector(); 5824 comp = intent.getComponent(); 5825 } 5826 } 5827 if (comp != null) { 5828 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5829 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5830 if (ai != null) { 5831 ResolveInfo ri = new ResolveInfo(); 5832 ri.activityInfo = ai; 5833 list.add(ri); 5834 } 5835 return list; 5836 } 5837 5838 // reader 5839 synchronized (mPackages) { 5840 String pkgName = intent.getPackage(); 5841 if (pkgName == null) { 5842 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5843 } 5844 final PackageParser.Package pkg = mPackages.get(pkgName); 5845 if (pkg != null) { 5846 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5847 userId); 5848 } 5849 return Collections.emptyList(); 5850 } 5851 } 5852 5853 @Override 5854 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5855 if (!sUserManager.exists(userId)) return null; 5856 flags = updateFlagsForResolve(flags, userId, intent); 5857 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5858 if (query != null) { 5859 if (query.size() >= 1) { 5860 // If there is more than one service with the same priority, 5861 // just arbitrarily pick the first one. 5862 return query.get(0); 5863 } 5864 } 5865 return null; 5866 } 5867 5868 @Override 5869 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5870 String resolvedType, int flags, int userId) { 5871 return new ParceledListSlice<>( 5872 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5873 } 5874 5875 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5876 String resolvedType, int flags, int userId) { 5877 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5878 flags = updateFlagsForResolve(flags, userId, intent); 5879 ComponentName comp = intent.getComponent(); 5880 if (comp == null) { 5881 if (intent.getSelector() != null) { 5882 intent = intent.getSelector(); 5883 comp = intent.getComponent(); 5884 } 5885 } 5886 if (comp != null) { 5887 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5888 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5889 if (si != null) { 5890 final ResolveInfo ri = new ResolveInfo(); 5891 ri.serviceInfo = si; 5892 list.add(ri); 5893 } 5894 return list; 5895 } 5896 5897 // reader 5898 synchronized (mPackages) { 5899 String pkgName = intent.getPackage(); 5900 if (pkgName == null) { 5901 return mServices.queryIntent(intent, resolvedType, flags, userId); 5902 } 5903 final PackageParser.Package pkg = mPackages.get(pkgName); 5904 if (pkg != null) { 5905 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5906 userId); 5907 } 5908 return Collections.emptyList(); 5909 } 5910 } 5911 5912 @Override 5913 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5914 String resolvedType, int flags, int userId) { 5915 return new ParceledListSlice<>( 5916 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5917 } 5918 5919 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5920 Intent intent, String resolvedType, int flags, int userId) { 5921 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5922 flags = updateFlagsForResolve(flags, userId, intent); 5923 ComponentName comp = intent.getComponent(); 5924 if (comp == null) { 5925 if (intent.getSelector() != null) { 5926 intent = intent.getSelector(); 5927 comp = intent.getComponent(); 5928 } 5929 } 5930 if (comp != null) { 5931 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5932 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5933 if (pi != null) { 5934 final ResolveInfo ri = new ResolveInfo(); 5935 ri.providerInfo = pi; 5936 list.add(ri); 5937 } 5938 return list; 5939 } 5940 5941 // reader 5942 synchronized (mPackages) { 5943 String pkgName = intent.getPackage(); 5944 if (pkgName == null) { 5945 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5946 } 5947 final PackageParser.Package pkg = mPackages.get(pkgName); 5948 if (pkg != null) { 5949 return mProviders.queryIntentForPackage( 5950 intent, resolvedType, flags, pkg.providers, userId); 5951 } 5952 return Collections.emptyList(); 5953 } 5954 } 5955 5956 @Override 5957 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5958 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5959 flags = updateFlagsForPackage(flags, userId, null); 5960 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5961 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5962 true /* requireFullPermission */, false /* checkShell */, 5963 "get installed packages"); 5964 5965 // writer 5966 synchronized (mPackages) { 5967 ArrayList<PackageInfo> list; 5968 if (listUninstalled) { 5969 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5970 for (PackageSetting ps : mSettings.mPackages.values()) { 5971 final PackageInfo pi; 5972 if (ps.pkg != null) { 5973 pi = generatePackageInfo(ps, flags, userId); 5974 } else { 5975 pi = generatePackageInfo(ps, flags, userId); 5976 } 5977 if (pi != null) { 5978 list.add(pi); 5979 } 5980 } 5981 } else { 5982 list = new ArrayList<PackageInfo>(mPackages.size()); 5983 for (PackageParser.Package p : mPackages.values()) { 5984 final PackageInfo pi = 5985 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 5986 if (pi != null) { 5987 list.add(pi); 5988 } 5989 } 5990 } 5991 5992 return new ParceledListSlice<PackageInfo>(list); 5993 } 5994 } 5995 5996 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5997 String[] permissions, boolean[] tmp, int flags, int userId) { 5998 int numMatch = 0; 5999 final PermissionsState permissionsState = ps.getPermissionsState(); 6000 for (int i=0; i<permissions.length; i++) { 6001 final String permission = permissions[i]; 6002 if (permissionsState.hasPermission(permission, userId)) { 6003 tmp[i] = true; 6004 numMatch++; 6005 } else { 6006 tmp[i] = false; 6007 } 6008 } 6009 if (numMatch == 0) { 6010 return; 6011 } 6012 final PackageInfo pi; 6013 if (ps.pkg != null) { 6014 pi = generatePackageInfo(ps, flags, userId); 6015 } else { 6016 pi = generatePackageInfo(ps, flags, userId); 6017 } 6018 // The above might return null in cases of uninstalled apps or install-state 6019 // skew across users/profiles. 6020 if (pi != null) { 6021 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6022 if (numMatch == permissions.length) { 6023 pi.requestedPermissions = permissions; 6024 } else { 6025 pi.requestedPermissions = new String[numMatch]; 6026 numMatch = 0; 6027 for (int i=0; i<permissions.length; i++) { 6028 if (tmp[i]) { 6029 pi.requestedPermissions[numMatch] = permissions[i]; 6030 numMatch++; 6031 } 6032 } 6033 } 6034 } 6035 list.add(pi); 6036 } 6037 } 6038 6039 @Override 6040 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6041 String[] permissions, int flags, int userId) { 6042 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6043 flags = updateFlagsForPackage(flags, userId, permissions); 6044 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6045 6046 // writer 6047 synchronized (mPackages) { 6048 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6049 boolean[] tmpBools = new boolean[permissions.length]; 6050 if (listUninstalled) { 6051 for (PackageSetting ps : mSettings.mPackages.values()) { 6052 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6053 } 6054 } else { 6055 for (PackageParser.Package pkg : mPackages.values()) { 6056 PackageSetting ps = (PackageSetting)pkg.mExtras; 6057 if (ps != null) { 6058 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6059 userId); 6060 } 6061 } 6062 } 6063 6064 return new ParceledListSlice<PackageInfo>(list); 6065 } 6066 } 6067 6068 @Override 6069 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6070 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6071 flags = updateFlagsForApplication(flags, userId, null); 6072 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6073 6074 // writer 6075 synchronized (mPackages) { 6076 ArrayList<ApplicationInfo> list; 6077 if (listUninstalled) { 6078 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6079 for (PackageSetting ps : mSettings.mPackages.values()) { 6080 ApplicationInfo ai; 6081 if (ps.pkg != null) { 6082 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6083 ps.readUserState(userId), userId); 6084 } else { 6085 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6086 } 6087 if (ai != null) { 6088 list.add(ai); 6089 } 6090 } 6091 } else { 6092 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6093 for (PackageParser.Package p : mPackages.values()) { 6094 if (p.mExtras != null) { 6095 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6096 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6097 if (ai != null) { 6098 list.add(ai); 6099 } 6100 } 6101 } 6102 } 6103 6104 return new ParceledListSlice<ApplicationInfo>(list); 6105 } 6106 } 6107 6108 @Override 6109 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6110 if (DISABLE_EPHEMERAL_APPS) { 6111 return null; 6112 } 6113 6114 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6115 "getEphemeralApplications"); 6116 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6117 true /* requireFullPermission */, false /* checkShell */, 6118 "getEphemeralApplications"); 6119 synchronized (mPackages) { 6120 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6121 .getEphemeralApplicationsLPw(userId); 6122 if (ephemeralApps != null) { 6123 return new ParceledListSlice<>(ephemeralApps); 6124 } 6125 } 6126 return null; 6127 } 6128 6129 @Override 6130 public boolean isEphemeralApplication(String packageName, int userId) { 6131 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6132 true /* requireFullPermission */, false /* checkShell */, 6133 "isEphemeral"); 6134 if (DISABLE_EPHEMERAL_APPS) { 6135 return false; 6136 } 6137 6138 if (!isCallerSameApp(packageName)) { 6139 return false; 6140 } 6141 synchronized (mPackages) { 6142 PackageParser.Package pkg = mPackages.get(packageName); 6143 if (pkg != null) { 6144 return pkg.applicationInfo.isEphemeralApp(); 6145 } 6146 } 6147 return false; 6148 } 6149 6150 @Override 6151 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6152 if (DISABLE_EPHEMERAL_APPS) { 6153 return null; 6154 } 6155 6156 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6157 true /* requireFullPermission */, false /* checkShell */, 6158 "getCookie"); 6159 if (!isCallerSameApp(packageName)) { 6160 return null; 6161 } 6162 synchronized (mPackages) { 6163 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6164 packageName, userId); 6165 } 6166 } 6167 6168 @Override 6169 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6170 if (DISABLE_EPHEMERAL_APPS) { 6171 return true; 6172 } 6173 6174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6175 true /* requireFullPermission */, true /* checkShell */, 6176 "setCookie"); 6177 if (!isCallerSameApp(packageName)) { 6178 return false; 6179 } 6180 synchronized (mPackages) { 6181 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6182 packageName, cookie, userId); 6183 } 6184 } 6185 6186 @Override 6187 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6188 if (DISABLE_EPHEMERAL_APPS) { 6189 return null; 6190 } 6191 6192 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6193 "getEphemeralApplicationIcon"); 6194 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6195 true /* requireFullPermission */, false /* checkShell */, 6196 "getEphemeralApplicationIcon"); 6197 synchronized (mPackages) { 6198 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6199 packageName, userId); 6200 } 6201 } 6202 6203 private boolean isCallerSameApp(String packageName) { 6204 PackageParser.Package pkg = mPackages.get(packageName); 6205 return pkg != null 6206 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6207 } 6208 6209 @Override 6210 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6211 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6212 } 6213 6214 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6215 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6216 6217 // reader 6218 synchronized (mPackages) { 6219 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6220 final int userId = UserHandle.getCallingUserId(); 6221 while (i.hasNext()) { 6222 final PackageParser.Package p = i.next(); 6223 if (p.applicationInfo == null) continue; 6224 6225 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6226 && !p.applicationInfo.isDirectBootAware(); 6227 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6228 && p.applicationInfo.isDirectBootAware(); 6229 6230 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6231 && (!mSafeMode || isSystemApp(p)) 6232 && (matchesUnaware || matchesAware)) { 6233 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6234 if (ps != null) { 6235 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6236 ps.readUserState(userId), userId); 6237 if (ai != null) { 6238 finalList.add(ai); 6239 } 6240 } 6241 } 6242 } 6243 } 6244 6245 return finalList; 6246 } 6247 6248 @Override 6249 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6250 if (!sUserManager.exists(userId)) return null; 6251 flags = updateFlagsForComponent(flags, userId, name); 6252 // reader 6253 synchronized (mPackages) { 6254 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6255 PackageSetting ps = provider != null 6256 ? mSettings.mPackages.get(provider.owner.packageName) 6257 : null; 6258 return ps != null 6259 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6260 ? PackageParser.generateProviderInfo(provider, flags, 6261 ps.readUserState(userId), userId) 6262 : null; 6263 } 6264 } 6265 6266 /** 6267 * @deprecated 6268 */ 6269 @Deprecated 6270 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6271 // reader 6272 synchronized (mPackages) { 6273 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6274 .entrySet().iterator(); 6275 final int userId = UserHandle.getCallingUserId(); 6276 while (i.hasNext()) { 6277 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6278 PackageParser.Provider p = entry.getValue(); 6279 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6280 6281 if (ps != null && p.syncable 6282 && (!mSafeMode || (p.info.applicationInfo.flags 6283 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6284 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6285 ps.readUserState(userId), userId); 6286 if (info != null) { 6287 outNames.add(entry.getKey()); 6288 outInfo.add(info); 6289 } 6290 } 6291 } 6292 } 6293 } 6294 6295 @Override 6296 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6297 int uid, int flags) { 6298 final int userId = processName != null ? UserHandle.getUserId(uid) 6299 : UserHandle.getCallingUserId(); 6300 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6301 flags = updateFlagsForComponent(flags, userId, processName); 6302 6303 ArrayList<ProviderInfo> finalList = null; 6304 // reader 6305 synchronized (mPackages) { 6306 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6307 while (i.hasNext()) { 6308 final PackageParser.Provider p = i.next(); 6309 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6310 if (ps != null && p.info.authority != null 6311 && (processName == null 6312 || (p.info.processName.equals(processName) 6313 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6314 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6315 if (finalList == null) { 6316 finalList = new ArrayList<ProviderInfo>(3); 6317 } 6318 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6319 ps.readUserState(userId), userId); 6320 if (info != null) { 6321 finalList.add(info); 6322 } 6323 } 6324 } 6325 } 6326 6327 if (finalList != null) { 6328 Collections.sort(finalList, mProviderInitOrderSorter); 6329 return new ParceledListSlice<ProviderInfo>(finalList); 6330 } 6331 6332 return ParceledListSlice.emptyList(); 6333 } 6334 6335 @Override 6336 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6337 // reader 6338 synchronized (mPackages) { 6339 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6340 return PackageParser.generateInstrumentationInfo(i, flags); 6341 } 6342 } 6343 6344 @Override 6345 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6346 String targetPackage, int flags) { 6347 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6348 } 6349 6350 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6351 int flags) { 6352 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6353 6354 // reader 6355 synchronized (mPackages) { 6356 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6357 while (i.hasNext()) { 6358 final PackageParser.Instrumentation p = i.next(); 6359 if (targetPackage == null 6360 || targetPackage.equals(p.info.targetPackage)) { 6361 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6362 flags); 6363 if (ii != null) { 6364 finalList.add(ii); 6365 } 6366 } 6367 } 6368 } 6369 6370 return finalList; 6371 } 6372 6373 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6374 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6375 if (overlays == null) { 6376 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6377 return; 6378 } 6379 for (PackageParser.Package opkg : overlays.values()) { 6380 // Not much to do if idmap fails: we already logged the error 6381 // and we certainly don't want to abort installation of pkg simply 6382 // because an overlay didn't fit properly. For these reasons, 6383 // ignore the return value of createIdmapForPackagePairLI. 6384 createIdmapForPackagePairLI(pkg, opkg); 6385 } 6386 } 6387 6388 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6389 PackageParser.Package opkg) { 6390 if (!opkg.mTrustedOverlay) { 6391 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6392 opkg.baseCodePath + ": overlay not trusted"); 6393 return false; 6394 } 6395 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6396 if (overlaySet == null) { 6397 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6398 opkg.baseCodePath + " but target package has no known overlays"); 6399 return false; 6400 } 6401 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6402 // TODO: generate idmap for split APKs 6403 try { 6404 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6405 } catch (InstallerException e) { 6406 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6407 + opkg.baseCodePath); 6408 return false; 6409 } 6410 PackageParser.Package[] overlayArray = 6411 overlaySet.values().toArray(new PackageParser.Package[0]); 6412 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6413 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6414 return p1.mOverlayPriority - p2.mOverlayPriority; 6415 } 6416 }; 6417 Arrays.sort(overlayArray, cmp); 6418 6419 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6420 int i = 0; 6421 for (PackageParser.Package p : overlayArray) { 6422 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6423 } 6424 return true; 6425 } 6426 6427 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6428 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6429 try { 6430 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6431 } finally { 6432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6433 } 6434 } 6435 6436 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6437 final File[] files = dir.listFiles(); 6438 if (ArrayUtils.isEmpty(files)) { 6439 Log.d(TAG, "No files in app dir " + dir); 6440 return; 6441 } 6442 6443 if (DEBUG_PACKAGE_SCANNING) { 6444 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6445 + " flags=0x" + Integer.toHexString(parseFlags)); 6446 } 6447 6448 for (File file : files) { 6449 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6450 && !PackageInstallerService.isStageName(file.getName()); 6451 if (!isPackage) { 6452 // Ignore entries which are not packages 6453 continue; 6454 } 6455 try { 6456 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6457 scanFlags, currentTime, null); 6458 } catch (PackageManagerException e) { 6459 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6460 6461 // Delete invalid userdata apps 6462 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6463 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6464 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6465 removeCodePathLI(file); 6466 } 6467 } 6468 } 6469 } 6470 6471 private static File getSettingsProblemFile() { 6472 File dataDir = Environment.getDataDirectory(); 6473 File systemDir = new File(dataDir, "system"); 6474 File fname = new File(systemDir, "uiderrors.txt"); 6475 return fname; 6476 } 6477 6478 static void reportSettingsProblem(int priority, String msg) { 6479 logCriticalInfo(priority, msg); 6480 } 6481 6482 static void logCriticalInfo(int priority, String msg) { 6483 Slog.println(priority, TAG, msg); 6484 EventLogTags.writePmCriticalInfo(msg); 6485 try { 6486 File fname = getSettingsProblemFile(); 6487 FileOutputStream out = new FileOutputStream(fname, true); 6488 PrintWriter pw = new FastPrintWriter(out); 6489 SimpleDateFormat formatter = new SimpleDateFormat(); 6490 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6491 pw.println(dateString + ": " + msg); 6492 pw.close(); 6493 FileUtils.setPermissions( 6494 fname.toString(), 6495 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6496 -1, -1); 6497 } catch (java.io.IOException e) { 6498 } 6499 } 6500 6501 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6502 int parseFlags) throws PackageManagerException { 6503 if (ps != null 6504 && ps.codePath.equals(srcFile) 6505 && ps.timeStamp == srcFile.lastModified() 6506 && !isCompatSignatureUpdateNeeded(pkg) 6507 && !isRecoverSignatureUpdateNeeded(pkg)) { 6508 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6509 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6510 ArraySet<PublicKey> signingKs; 6511 synchronized (mPackages) { 6512 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6513 } 6514 if (ps.signatures.mSignatures != null 6515 && ps.signatures.mSignatures.length != 0 6516 && signingKs != null) { 6517 // Optimization: reuse the existing cached certificates 6518 // if the package appears to be unchanged. 6519 pkg.mSignatures = ps.signatures.mSignatures; 6520 pkg.mSigningKeys = signingKs; 6521 return; 6522 } 6523 6524 Slog.w(TAG, "PackageSetting for " + ps.name 6525 + " is missing signatures. Collecting certs again to recover them."); 6526 } else { 6527 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6528 } 6529 6530 try { 6531 PackageParser.collectCertificates(pkg, parseFlags); 6532 } catch (PackageParserException e) { 6533 throw PackageManagerException.from(e); 6534 } 6535 } 6536 6537 /** 6538 * Traces a package scan. 6539 * @see #scanPackageLI(File, int, int, long, UserHandle) 6540 */ 6541 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6542 long currentTime, UserHandle user) throws PackageManagerException { 6543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6544 try { 6545 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6546 } finally { 6547 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6548 } 6549 } 6550 6551 /** 6552 * Scans a package and returns the newly parsed package. 6553 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6554 */ 6555 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6556 long currentTime, UserHandle user) throws PackageManagerException { 6557 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6558 parseFlags |= mDefParseFlags; 6559 PackageParser pp = new PackageParser(); 6560 pp.setSeparateProcesses(mSeparateProcesses); 6561 pp.setOnlyCoreApps(mOnlyCore); 6562 pp.setDisplayMetrics(mMetrics); 6563 6564 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6565 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6566 } 6567 6568 final PackageParser.Package pkg; 6569 try { 6570 pkg = pp.parsePackage(scanFile, parseFlags); 6571 } catch (PackageParserException e) { 6572 throw PackageManagerException.from(e); 6573 } 6574 6575 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6576 } 6577 6578 /** 6579 * Scans a package and returns the newly parsed package. 6580 * @throws PackageManagerException on a parse error. 6581 */ 6582 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6583 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6584 throws PackageManagerException { 6585 // If the package has children and this is the first dive in the function 6586 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6587 // packages (parent and children) would be successfully scanned before the 6588 // actual scan since scanning mutates internal state and we want to atomically 6589 // install the package and its children. 6590 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6591 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6592 scanFlags |= SCAN_CHECK_ONLY; 6593 } 6594 } else { 6595 scanFlags &= ~SCAN_CHECK_ONLY; 6596 } 6597 6598 // Scan the parent 6599 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6600 scanFlags, currentTime, user); 6601 6602 // Scan the children 6603 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6604 for (int i = 0; i < childCount; i++) { 6605 PackageParser.Package childPackage = pkg.childPackages.get(i); 6606 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6607 currentTime, user); 6608 } 6609 6610 6611 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6612 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6613 } 6614 6615 return scannedPkg; 6616 } 6617 6618 /** 6619 * Scans a package and returns the newly parsed package. 6620 * @throws PackageManagerException on a parse error. 6621 */ 6622 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6623 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6624 throws PackageManagerException { 6625 PackageSetting ps = null; 6626 PackageSetting updatedPkg; 6627 // reader 6628 synchronized (mPackages) { 6629 // Look to see if we already know about this package. 6630 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6631 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6632 // This package has been renamed to its original name. Let's 6633 // use that. 6634 ps = mSettings.peekPackageLPr(oldName); 6635 } 6636 // If there was no original package, see one for the real package name. 6637 if (ps == null) { 6638 ps = mSettings.peekPackageLPr(pkg.packageName); 6639 } 6640 // Check to see if this package could be hiding/updating a system 6641 // package. Must look for it either under the original or real 6642 // package name depending on our state. 6643 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6644 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6645 6646 // If this is a package we don't know about on the system partition, we 6647 // may need to remove disabled child packages on the system partition 6648 // or may need to not add child packages if the parent apk is updated 6649 // on the data partition and no longer defines this child package. 6650 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6651 // If this is a parent package for an updated system app and this system 6652 // app got an OTA update which no longer defines some of the child packages 6653 // we have to prune them from the disabled system packages. 6654 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6655 if (disabledPs != null) { 6656 final int scannedChildCount = (pkg.childPackages != null) 6657 ? pkg.childPackages.size() : 0; 6658 final int disabledChildCount = disabledPs.childPackageNames != null 6659 ? disabledPs.childPackageNames.size() : 0; 6660 for (int i = 0; i < disabledChildCount; i++) { 6661 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6662 boolean disabledPackageAvailable = false; 6663 for (int j = 0; j < scannedChildCount; j++) { 6664 PackageParser.Package childPkg = pkg.childPackages.get(j); 6665 if (childPkg.packageName.equals(disabledChildPackageName)) { 6666 disabledPackageAvailable = true; 6667 break; 6668 } 6669 } 6670 if (!disabledPackageAvailable) { 6671 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6672 } 6673 } 6674 } 6675 } 6676 } 6677 6678 boolean updatedPkgBetter = false; 6679 // First check if this is a system package that may involve an update 6680 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6681 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6682 // it needs to drop FLAG_PRIVILEGED. 6683 if (locationIsPrivileged(scanFile)) { 6684 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6685 } else { 6686 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6687 } 6688 6689 if (ps != null && !ps.codePath.equals(scanFile)) { 6690 // The path has changed from what was last scanned... check the 6691 // version of the new path against what we have stored to determine 6692 // what to do. 6693 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6694 if (pkg.mVersionCode <= ps.versionCode) { 6695 // The system package has been updated and the code path does not match 6696 // Ignore entry. Skip it. 6697 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6698 + " ignored: updated version " + ps.versionCode 6699 + " better than this " + pkg.mVersionCode); 6700 if (!updatedPkg.codePath.equals(scanFile)) { 6701 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6702 + ps.name + " changing from " + updatedPkg.codePathString 6703 + " to " + scanFile); 6704 updatedPkg.codePath = scanFile; 6705 updatedPkg.codePathString = scanFile.toString(); 6706 updatedPkg.resourcePath = scanFile; 6707 updatedPkg.resourcePathString = scanFile.toString(); 6708 } 6709 updatedPkg.pkg = pkg; 6710 updatedPkg.versionCode = pkg.mVersionCode; 6711 6712 // Update the disabled system child packages to point to the package too. 6713 final int childCount = updatedPkg.childPackageNames != null 6714 ? updatedPkg.childPackageNames.size() : 0; 6715 for (int i = 0; i < childCount; i++) { 6716 String childPackageName = updatedPkg.childPackageNames.get(i); 6717 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6718 childPackageName); 6719 if (updatedChildPkg != null) { 6720 updatedChildPkg.pkg = pkg; 6721 updatedChildPkg.versionCode = pkg.mVersionCode; 6722 } 6723 } 6724 6725 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6726 + scanFile + " ignored: updated version " + ps.versionCode 6727 + " better than this " + pkg.mVersionCode); 6728 } else { 6729 // The current app on the system partition is better than 6730 // what we have updated to on the data partition; switch 6731 // back to the system partition version. 6732 // At this point, its safely assumed that package installation for 6733 // apps in system partition will go through. If not there won't be a working 6734 // version of the app 6735 // writer 6736 synchronized (mPackages) { 6737 // Just remove the loaded entries from package lists. 6738 mPackages.remove(ps.name); 6739 } 6740 6741 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6742 + " reverting from " + ps.codePathString 6743 + ": new version " + pkg.mVersionCode 6744 + " better than installed " + ps.versionCode); 6745 6746 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6747 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6748 synchronized (mInstallLock) { 6749 args.cleanUpResourcesLI(); 6750 } 6751 synchronized (mPackages) { 6752 mSettings.enableSystemPackageLPw(ps.name); 6753 } 6754 updatedPkgBetter = true; 6755 } 6756 } 6757 } 6758 6759 if (updatedPkg != null) { 6760 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6761 // initially 6762 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6763 6764 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6765 // flag set initially 6766 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6767 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6768 } 6769 } 6770 6771 // Verify certificates against what was last scanned 6772 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6773 6774 /* 6775 * A new system app appeared, but we already had a non-system one of the 6776 * same name installed earlier. 6777 */ 6778 boolean shouldHideSystemApp = false; 6779 if (updatedPkg == null && ps != null 6780 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6781 /* 6782 * Check to make sure the signatures match first. If they don't, 6783 * wipe the installed application and its data. 6784 */ 6785 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6786 != PackageManager.SIGNATURE_MATCH) { 6787 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6788 + " signatures don't match existing userdata copy; removing"); 6789 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6790 ps = null; 6791 } else { 6792 /* 6793 * If the newly-added system app is an older version than the 6794 * already installed version, hide it. It will be scanned later 6795 * and re-added like an update. 6796 */ 6797 if (pkg.mVersionCode <= ps.versionCode) { 6798 shouldHideSystemApp = true; 6799 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6800 + " but new version " + pkg.mVersionCode + " better than installed " 6801 + ps.versionCode + "; hiding system"); 6802 } else { 6803 /* 6804 * The newly found system app is a newer version that the 6805 * one previously installed. Simply remove the 6806 * already-installed application and replace it with our own 6807 * while keeping the application data. 6808 */ 6809 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6810 + " reverting from " + ps.codePathString + ": new version " 6811 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6812 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6813 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6814 synchronized (mInstallLock) { 6815 args.cleanUpResourcesLI(); 6816 } 6817 } 6818 } 6819 } 6820 6821 // The apk is forward locked (not public) if its code and resources 6822 // are kept in different files. (except for app in either system or 6823 // vendor path). 6824 // TODO grab this value from PackageSettings 6825 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6826 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6827 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6828 } 6829 } 6830 6831 // TODO: extend to support forward-locked splits 6832 String resourcePath = null; 6833 String baseResourcePath = null; 6834 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6835 if (ps != null && ps.resourcePathString != null) { 6836 resourcePath = ps.resourcePathString; 6837 baseResourcePath = ps.resourcePathString; 6838 } else { 6839 // Should not happen at all. Just log an error. 6840 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6841 } 6842 } else { 6843 resourcePath = pkg.codePath; 6844 baseResourcePath = pkg.baseCodePath; 6845 } 6846 6847 // Set application objects path explicitly. 6848 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6849 pkg.setApplicationInfoCodePath(pkg.codePath); 6850 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6851 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6852 pkg.setApplicationInfoResourcePath(resourcePath); 6853 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6854 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6855 6856 // Note that we invoke the following method only if we are about to unpack an application 6857 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6858 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6859 6860 /* 6861 * If the system app should be overridden by a previously installed 6862 * data, hide the system app now and let the /data/app scan pick it up 6863 * again. 6864 */ 6865 if (shouldHideSystemApp) { 6866 synchronized (mPackages) { 6867 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6868 } 6869 } 6870 6871 return scannedPkg; 6872 } 6873 6874 private static String fixProcessName(String defProcessName, 6875 String processName, int uid) { 6876 if (processName == null) { 6877 return defProcessName; 6878 } 6879 return processName; 6880 } 6881 6882 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6883 throws PackageManagerException { 6884 if (pkgSetting.signatures.mSignatures != null) { 6885 // Already existing package. Make sure signatures match 6886 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6887 == PackageManager.SIGNATURE_MATCH; 6888 if (!match) { 6889 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6890 == PackageManager.SIGNATURE_MATCH; 6891 } 6892 if (!match) { 6893 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6894 == PackageManager.SIGNATURE_MATCH; 6895 } 6896 if (!match) { 6897 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6898 + pkg.packageName + " signatures do not match the " 6899 + "previously installed version; ignoring!"); 6900 } 6901 } 6902 6903 // Check for shared user signatures 6904 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6905 // Already existing package. Make sure signatures match 6906 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6907 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6908 if (!match) { 6909 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6910 == PackageManager.SIGNATURE_MATCH; 6911 } 6912 if (!match) { 6913 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6914 == PackageManager.SIGNATURE_MATCH; 6915 } 6916 if (!match) { 6917 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6918 "Package " + pkg.packageName 6919 + " has no signatures that match those in shared user " 6920 + pkgSetting.sharedUser.name + "; ignoring!"); 6921 } 6922 } 6923 } 6924 6925 /** 6926 * Enforces that only the system UID or root's UID can call a method exposed 6927 * via Binder. 6928 * 6929 * @param message used as message if SecurityException is thrown 6930 * @throws SecurityException if the caller is not system or root 6931 */ 6932 private static final void enforceSystemOrRoot(String message) { 6933 final int uid = Binder.getCallingUid(); 6934 if (uid != Process.SYSTEM_UID && uid != 0) { 6935 throw new SecurityException(message); 6936 } 6937 } 6938 6939 @Override 6940 public void performFstrimIfNeeded() { 6941 enforceSystemOrRoot("Only the system can request fstrim"); 6942 6943 // Before everything else, see whether we need to fstrim. 6944 try { 6945 IMountService ms = PackageHelper.getMountService(); 6946 if (ms != null) { 6947 final boolean isUpgrade = isUpgrade(); 6948 boolean doTrim = isUpgrade; 6949 if (doTrim) { 6950 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6951 } else { 6952 final long interval = android.provider.Settings.Global.getLong( 6953 mContext.getContentResolver(), 6954 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6955 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6956 if (interval > 0) { 6957 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6958 if (timeSinceLast > interval) { 6959 doTrim = true; 6960 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6961 + "; running immediately"); 6962 } 6963 } 6964 } 6965 if (doTrim) { 6966 if (!isFirstBoot()) { 6967 try { 6968 ActivityManagerNative.getDefault().showBootMessage( 6969 mContext.getResources().getString( 6970 R.string.android_upgrading_fstrim), true); 6971 } catch (RemoteException e) { 6972 } 6973 } 6974 ms.runMaintenance(); 6975 } 6976 } else { 6977 Slog.e(TAG, "Mount service unavailable!"); 6978 } 6979 } catch (RemoteException e) { 6980 // Can't happen; MountService is local 6981 } 6982 } 6983 6984 @Override 6985 public void updatePackagesIfNeeded() { 6986 enforceSystemOrRoot("Only the system can request package update"); 6987 6988 // We need to re-extract after an OTA. 6989 boolean causeUpgrade = isUpgrade(); 6990 6991 // First boot or factory reset. 6992 // Note: we also handle devices that are upgrading to N right now as if it is their 6993 // first boot, as they do not have profile data. 6994 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 6995 6996 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 6997 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 6998 6999 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7000 return; 7001 } 7002 7003 List<PackageParser.Package> pkgs; 7004 synchronized (mPackages) { 7005 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7006 } 7007 7008 int curr = 0; 7009 int total = pkgs.size(); 7010 for (PackageParser.Package pkg : pkgs) { 7011 curr++; 7012 7013 if (DEBUG_DEXOPT) { 7014 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7015 } 7016 7017 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 7018 // If the cache was pruned, any compiled odex files will likely be out of date 7019 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 7020 // Instead, force the extraction in this case. 7021 performDexOpt(pkg.packageName, 7022 null /* instructionSet */, 7023 false /* checkProfiles */, 7024 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7025 false /* force */); 7026 } 7027 } 7028 } 7029 7030 @Override 7031 public void notifyPackageUse(String packageName) { 7032 synchronized (mPackages) { 7033 PackageParser.Package p = mPackages.get(packageName); 7034 if (p == null) { 7035 return; 7036 } 7037 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7038 } 7039 } 7040 7041 // TODO: this is not used nor needed. Delete it. 7042 @Override 7043 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7044 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7045 getFullCompilerFilter(), false /* force */); 7046 } 7047 7048 @Override 7049 public boolean performDexOpt(String packageName, String instructionSet, 7050 boolean checkProfiles, int compileReason, boolean force) { 7051 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7052 getCompilerFilterForReason(compileReason), force); 7053 } 7054 7055 @Override 7056 public boolean performDexOptMode(String packageName, String instructionSet, 7057 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7058 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7059 targetCompilerFilter, force); 7060 } 7061 7062 private boolean performDexOptTraced(String packageName, String instructionSet, 7063 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7064 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7065 try { 7066 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7067 targetCompilerFilter, force); 7068 } finally { 7069 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7070 } 7071 } 7072 7073 private boolean performDexOptInternal(String packageName, String instructionSet, 7074 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7075 PackageParser.Package p; 7076 final String targetInstructionSet; 7077 synchronized (mPackages) { 7078 p = mPackages.get(packageName); 7079 if (p == null) { 7080 return false; 7081 } 7082 mPackageUsage.write(false); 7083 7084 targetInstructionSet = instructionSet != null ? instructionSet : 7085 getPrimaryInstructionSet(p.applicationInfo); 7086 } 7087 long callingId = Binder.clearCallingIdentity(); 7088 try { 7089 synchronized (mInstallLock) { 7090 final String[] instructionSets = new String[] { targetInstructionSet }; 7091 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7092 checkProfiles, targetCompilerFilter, force); 7093 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7094 } 7095 } finally { 7096 Binder.restoreCallingIdentity(callingId); 7097 } 7098 } 7099 7100 public ArraySet<String> getOptimizablePackages() { 7101 ArraySet<String> pkgs = new ArraySet<String>(); 7102 synchronized (mPackages) { 7103 for (PackageParser.Package p : mPackages.values()) { 7104 if (PackageDexOptimizer.canOptimizePackage(p)) { 7105 pkgs.add(p.packageName); 7106 } 7107 } 7108 } 7109 return pkgs; 7110 } 7111 7112 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7113 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7114 boolean force) { 7115 // Select the dex optimizer based on the force parameter. 7116 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7117 // allocate an object here. 7118 PackageDexOptimizer pdo = force 7119 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7120 : mPackageDexOptimizer; 7121 7122 // Optimize all dependencies first. Note: we ignore the return value and march on 7123 // on errors. 7124 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7125 if (!deps.isEmpty()) { 7126 for (PackageParser.Package depPackage : deps) { 7127 // TODO: Analyze and investigate if we (should) profile libraries. 7128 // Currently this will do a full compilation of the library by default. 7129 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7130 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7131 } 7132 } 7133 7134 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7135 } 7136 7137 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7138 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7139 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7140 Set<String> collectedNames = new HashSet<>(); 7141 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7142 7143 retValue.remove(p); 7144 7145 return retValue; 7146 } else { 7147 return Collections.emptyList(); 7148 } 7149 } 7150 7151 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7152 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7153 if (!collectedNames.contains(p.packageName)) { 7154 collectedNames.add(p.packageName); 7155 collected.add(p); 7156 7157 if (p.usesLibraries != null) { 7158 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7159 } 7160 if (p.usesOptionalLibraries != null) { 7161 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7162 collectedNames); 7163 } 7164 } 7165 } 7166 7167 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7168 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7169 for (String libName : libs) { 7170 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7171 if (libPkg != null) { 7172 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7173 } 7174 } 7175 } 7176 7177 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7178 synchronized (mPackages) { 7179 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7180 if (lib != null && lib.apk != null) { 7181 return mPackages.get(lib.apk); 7182 } 7183 } 7184 return null; 7185 } 7186 7187 public void shutdown() { 7188 mPackageUsage.write(true); 7189 } 7190 7191 @Override 7192 public void forceDexOpt(String packageName) { 7193 enforceSystemOrRoot("forceDexOpt"); 7194 7195 PackageParser.Package pkg; 7196 synchronized (mPackages) { 7197 pkg = mPackages.get(packageName); 7198 if (pkg == null) { 7199 throw new IllegalArgumentException("Unknown package: " + packageName); 7200 } 7201 } 7202 7203 synchronized (mInstallLock) { 7204 final String[] instructionSets = new String[] { 7205 getPrimaryInstructionSet(pkg.applicationInfo) }; 7206 7207 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7208 7209 // Whoever is calling forceDexOpt wants a fully compiled package. 7210 // Don't use profiles since that may cause compilation to be skipped. 7211 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7212 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7213 true /* force */); 7214 7215 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7216 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7217 throw new IllegalStateException("Failed to dexopt: " + res); 7218 } 7219 } 7220 } 7221 7222 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7223 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7224 Slog.w(TAG, "Unable to update from " + oldPkg.name 7225 + " to " + newPkg.packageName 7226 + ": old package not in system partition"); 7227 return false; 7228 } else if (mPackages.get(oldPkg.name) != null) { 7229 Slog.w(TAG, "Unable to update from " + oldPkg.name 7230 + " to " + newPkg.packageName 7231 + ": old package still exists"); 7232 return false; 7233 } 7234 return true; 7235 } 7236 7237 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7238 // TODO: triage flags as part of 26466827 7239 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7240 7241 boolean res = true; 7242 final int[] users = sUserManager.getUserIds(); 7243 for (int user : users) { 7244 try { 7245 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7246 } catch (InstallerException e) { 7247 Slog.w(TAG, "Failed to delete data directory", e); 7248 res = false; 7249 } 7250 } 7251 return res; 7252 } 7253 7254 void removeCodePathLI(File codePath) { 7255 if (codePath.isDirectory()) { 7256 try { 7257 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7258 } catch (InstallerException e) { 7259 Slog.w(TAG, "Failed to remove code path", e); 7260 } 7261 } else { 7262 codePath.delete(); 7263 } 7264 } 7265 7266 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7267 try { 7268 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7269 } catch (InstallerException e) { 7270 Slog.w(TAG, "Failed to destroy app data", e); 7271 } 7272 } 7273 7274 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7275 int appId, String seinfo) { 7276 try { 7277 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7278 } catch (InstallerException e) { 7279 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7280 } 7281 } 7282 7283 private void deleteProfilesLI(String packageName, boolean destroy) { 7284 final PackageParser.Package pkg; 7285 synchronized (mPackages) { 7286 pkg = mPackages.get(packageName); 7287 } 7288 if (pkg == null) { 7289 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7290 return; 7291 } 7292 deleteProfilesLI(pkg, destroy); 7293 } 7294 7295 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7296 try { 7297 if (destroy) { 7298 mInstaller.destroyAppProfiles(pkg.packageName); 7299 } else { 7300 mInstaller.clearAppProfiles(pkg.packageName); 7301 } 7302 } catch (InstallerException ex) { 7303 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7304 } 7305 } 7306 7307 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7308 final PackageParser.Package pkg; 7309 synchronized (mPackages) { 7310 pkg = mPackages.get(packageName); 7311 } 7312 if (pkg == null) { 7313 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7314 return; 7315 } 7316 deleteCodeCacheDirsLI(pkg); 7317 } 7318 7319 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7320 // TODO: triage flags as part of 26466827 7321 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7322 7323 int[] users = sUserManager.getUserIds(); 7324 int res = 0; 7325 for (int user : users) { 7326 // Remove the parent code cache 7327 try { 7328 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7329 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7330 } catch (InstallerException e) { 7331 Slog.w(TAG, "Failed to delete code cache directory", e); 7332 } 7333 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7334 for (int i = 0; i < childCount; i++) { 7335 PackageParser.Package childPkg = pkg.childPackages.get(i); 7336 // Remove the child code cache 7337 try { 7338 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7339 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7340 } catch (InstallerException e) { 7341 Slog.w(TAG, "Failed to delete code cache directory", e); 7342 } 7343 } 7344 } 7345 } 7346 7347 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7348 long lastUpdateTime) { 7349 // Set parent install/update time 7350 PackageSetting ps = (PackageSetting) pkg.mExtras; 7351 if (ps != null) { 7352 ps.firstInstallTime = firstInstallTime; 7353 ps.lastUpdateTime = lastUpdateTime; 7354 } 7355 // Set children install/update time 7356 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7357 for (int i = 0; i < childCount; i++) { 7358 PackageParser.Package childPkg = pkg.childPackages.get(i); 7359 ps = (PackageSetting) childPkg.mExtras; 7360 if (ps != null) { 7361 ps.firstInstallTime = firstInstallTime; 7362 ps.lastUpdateTime = lastUpdateTime; 7363 } 7364 } 7365 } 7366 7367 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7368 PackageParser.Package changingLib) { 7369 if (file.path != null) { 7370 usesLibraryFiles.add(file.path); 7371 return; 7372 } 7373 PackageParser.Package p = mPackages.get(file.apk); 7374 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7375 // If we are doing this while in the middle of updating a library apk, 7376 // then we need to make sure to use that new apk for determining the 7377 // dependencies here. (We haven't yet finished committing the new apk 7378 // to the package manager state.) 7379 if (p == null || p.packageName.equals(changingLib.packageName)) { 7380 p = changingLib; 7381 } 7382 } 7383 if (p != null) { 7384 usesLibraryFiles.addAll(p.getAllCodePaths()); 7385 } 7386 } 7387 7388 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7389 PackageParser.Package changingLib) throws PackageManagerException { 7390 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7391 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7392 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7393 for (int i=0; i<N; i++) { 7394 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7395 if (file == null) { 7396 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7397 "Package " + pkg.packageName + " requires unavailable shared library " 7398 + pkg.usesLibraries.get(i) + "; failing!"); 7399 } 7400 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7401 } 7402 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7403 for (int i=0; i<N; i++) { 7404 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7405 if (file == null) { 7406 Slog.w(TAG, "Package " + pkg.packageName 7407 + " desires unavailable shared library " 7408 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7409 } else { 7410 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7411 } 7412 } 7413 N = usesLibraryFiles.size(); 7414 if (N > 0) { 7415 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7416 } else { 7417 pkg.usesLibraryFiles = null; 7418 } 7419 } 7420 } 7421 7422 private static boolean hasString(List<String> list, List<String> which) { 7423 if (list == null) { 7424 return false; 7425 } 7426 for (int i=list.size()-1; i>=0; i--) { 7427 for (int j=which.size()-1; j>=0; j--) { 7428 if (which.get(j).equals(list.get(i))) { 7429 return true; 7430 } 7431 } 7432 } 7433 return false; 7434 } 7435 7436 private void updateAllSharedLibrariesLPw() { 7437 for (PackageParser.Package pkg : mPackages.values()) { 7438 try { 7439 updateSharedLibrariesLPw(pkg, null); 7440 } catch (PackageManagerException e) { 7441 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7442 } 7443 } 7444 } 7445 7446 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7447 PackageParser.Package changingPkg) { 7448 ArrayList<PackageParser.Package> res = null; 7449 for (PackageParser.Package pkg : mPackages.values()) { 7450 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7451 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7452 if (res == null) { 7453 res = new ArrayList<PackageParser.Package>(); 7454 } 7455 res.add(pkg); 7456 try { 7457 updateSharedLibrariesLPw(pkg, changingPkg); 7458 } catch (PackageManagerException e) { 7459 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7460 } 7461 } 7462 } 7463 return res; 7464 } 7465 7466 /** 7467 * Derive the value of the {@code cpuAbiOverride} based on the provided 7468 * value and an optional stored value from the package settings. 7469 */ 7470 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7471 String cpuAbiOverride = null; 7472 7473 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7474 cpuAbiOverride = null; 7475 } else if (abiOverride != null) { 7476 cpuAbiOverride = abiOverride; 7477 } else if (settings != null) { 7478 cpuAbiOverride = settings.cpuAbiOverrideString; 7479 } 7480 7481 return cpuAbiOverride; 7482 } 7483 7484 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7485 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7486 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7487 // If the package has children and this is the first dive in the function 7488 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7489 // whether all packages (parent and children) would be successfully scanned 7490 // before the actual scan since scanning mutates internal state and we want 7491 // to atomically install the package and its children. 7492 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7493 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7494 scanFlags |= SCAN_CHECK_ONLY; 7495 } 7496 } else { 7497 scanFlags &= ~SCAN_CHECK_ONLY; 7498 } 7499 7500 final PackageParser.Package scannedPkg; 7501 try { 7502 // Scan the parent 7503 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7504 // Scan the children 7505 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7506 for (int i = 0; i < childCount; i++) { 7507 PackageParser.Package childPkg = pkg.childPackages.get(i); 7508 scanPackageLI(childPkg, parseFlags, 7509 scanFlags, currentTime, user); 7510 } 7511 } finally { 7512 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7513 } 7514 7515 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7516 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7517 } 7518 7519 return scannedPkg; 7520 } 7521 7522 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7523 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7524 boolean success = false; 7525 try { 7526 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7527 currentTime, user); 7528 success = true; 7529 return res; 7530 } finally { 7531 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7532 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7533 } 7534 } 7535 } 7536 7537 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7538 int scanFlags, long currentTime, UserHandle user) 7539 throws PackageManagerException { 7540 final File scanFile = new File(pkg.codePath); 7541 if (pkg.applicationInfo.getCodePath() == null || 7542 pkg.applicationInfo.getResourcePath() == null) { 7543 // Bail out. The resource and code paths haven't been set. 7544 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7545 "Code and resource paths haven't been set correctly"); 7546 } 7547 7548 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7549 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7550 } else { 7551 // Only allow system apps to be flagged as core apps. 7552 pkg.coreApp = false; 7553 } 7554 7555 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7556 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7557 } 7558 7559 if (mCustomResolverComponentName != null && 7560 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7561 setUpCustomResolverActivity(pkg); 7562 } 7563 7564 if (pkg.packageName.equals("android")) { 7565 synchronized (mPackages) { 7566 if (mAndroidApplication != null) { 7567 Slog.w(TAG, "*************************************************"); 7568 Slog.w(TAG, "Core android package being redefined. Skipping."); 7569 Slog.w(TAG, " file=" + scanFile); 7570 Slog.w(TAG, "*************************************************"); 7571 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7572 "Core android package being redefined. Skipping."); 7573 } 7574 7575 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7576 // Set up information for our fall-back user intent resolution activity. 7577 mPlatformPackage = pkg; 7578 pkg.mVersionCode = mSdkVersion; 7579 mAndroidApplication = pkg.applicationInfo; 7580 7581 if (!mResolverReplaced) { 7582 mResolveActivity.applicationInfo = mAndroidApplication; 7583 mResolveActivity.name = ResolverActivity.class.getName(); 7584 mResolveActivity.packageName = mAndroidApplication.packageName; 7585 mResolveActivity.processName = "system:ui"; 7586 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7587 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7588 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7589 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7590 mResolveActivity.exported = true; 7591 mResolveActivity.enabled = true; 7592 mResolveInfo.activityInfo = mResolveActivity; 7593 mResolveInfo.priority = 0; 7594 mResolveInfo.preferredOrder = 0; 7595 mResolveInfo.match = 0; 7596 mResolveComponentName = new ComponentName( 7597 mAndroidApplication.packageName, mResolveActivity.name); 7598 } 7599 } 7600 } 7601 } 7602 7603 if (DEBUG_PACKAGE_SCANNING) { 7604 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7605 Log.d(TAG, "Scanning package " + pkg.packageName); 7606 } 7607 7608 synchronized (mPackages) { 7609 if (mPackages.containsKey(pkg.packageName) 7610 || mSharedLibraries.containsKey(pkg.packageName)) { 7611 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7612 "Application package " + pkg.packageName 7613 + " already installed. Skipping duplicate."); 7614 } 7615 7616 // If we're only installing presumed-existing packages, require that the 7617 // scanned APK is both already known and at the path previously established 7618 // for it. Previously unknown packages we pick up normally, but if we have an 7619 // a priori expectation about this package's install presence, enforce it. 7620 // With a singular exception for new system packages. When an OTA contains 7621 // a new system package, we allow the codepath to change from a system location 7622 // to the user-installed location. If we don't allow this change, any newer, 7623 // user-installed version of the application will be ignored. 7624 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7625 if (mExpectingBetter.containsKey(pkg.packageName)) { 7626 logCriticalInfo(Log.WARN, 7627 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7628 } else { 7629 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7630 if (known != null) { 7631 if (DEBUG_PACKAGE_SCANNING) { 7632 Log.d(TAG, "Examining " + pkg.codePath 7633 + " and requiring known paths " + known.codePathString 7634 + " & " + known.resourcePathString); 7635 } 7636 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7637 || !pkg.applicationInfo.getResourcePath().equals( 7638 known.resourcePathString)) { 7639 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7640 "Application package " + pkg.packageName 7641 + " found at " + pkg.applicationInfo.getCodePath() 7642 + " but expected at " + known.codePathString 7643 + "; ignoring."); 7644 } 7645 } 7646 } 7647 } 7648 } 7649 7650 // Initialize package source and resource directories 7651 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7652 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7653 7654 SharedUserSetting suid = null; 7655 PackageSetting pkgSetting = null; 7656 7657 if (!isSystemApp(pkg)) { 7658 // Only system apps can use these features. 7659 pkg.mOriginalPackages = null; 7660 pkg.mRealPackage = null; 7661 pkg.mAdoptPermissions = null; 7662 } 7663 7664 // Getting the package setting may have a side-effect, so if we 7665 // are only checking if scan would succeed, stash a copy of the 7666 // old setting to restore at the end. 7667 PackageSetting nonMutatedPs = null; 7668 7669 // writer 7670 synchronized (mPackages) { 7671 if (pkg.mSharedUserId != null) { 7672 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7673 if (suid == null) { 7674 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7675 "Creating application package " + pkg.packageName 7676 + " for shared user failed"); 7677 } 7678 if (DEBUG_PACKAGE_SCANNING) { 7679 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7680 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7681 + "): packages=" + suid.packages); 7682 } 7683 } 7684 7685 // Check if we are renaming from an original package name. 7686 PackageSetting origPackage = null; 7687 String realName = null; 7688 if (pkg.mOriginalPackages != null) { 7689 // This package may need to be renamed to a previously 7690 // installed name. Let's check on that... 7691 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7692 if (pkg.mOriginalPackages.contains(renamed)) { 7693 // This package had originally been installed as the 7694 // original name, and we have already taken care of 7695 // transitioning to the new one. Just update the new 7696 // one to continue using the old name. 7697 realName = pkg.mRealPackage; 7698 if (!pkg.packageName.equals(renamed)) { 7699 // Callers into this function may have already taken 7700 // care of renaming the package; only do it here if 7701 // it is not already done. 7702 pkg.setPackageName(renamed); 7703 } 7704 7705 } else { 7706 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7707 if ((origPackage = mSettings.peekPackageLPr( 7708 pkg.mOriginalPackages.get(i))) != null) { 7709 // We do have the package already installed under its 7710 // original name... should we use it? 7711 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7712 // New package is not compatible with original. 7713 origPackage = null; 7714 continue; 7715 } else if (origPackage.sharedUser != null) { 7716 // Make sure uid is compatible between packages. 7717 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7718 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7719 + " to " + pkg.packageName + ": old uid " 7720 + origPackage.sharedUser.name 7721 + " differs from " + pkg.mSharedUserId); 7722 origPackage = null; 7723 continue; 7724 } 7725 } else { 7726 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7727 + pkg.packageName + " to old name " + origPackage.name); 7728 } 7729 break; 7730 } 7731 } 7732 } 7733 } 7734 7735 if (mTransferedPackages.contains(pkg.packageName)) { 7736 Slog.w(TAG, "Package " + pkg.packageName 7737 + " was transferred to another, but its .apk remains"); 7738 } 7739 7740 // See comments in nonMutatedPs declaration 7741 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7742 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7743 if (foundPs != null) { 7744 nonMutatedPs = new PackageSetting(foundPs); 7745 } 7746 } 7747 7748 // Just create the setting, don't add it yet. For already existing packages 7749 // the PkgSetting exists already and doesn't have to be created. 7750 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7751 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7752 pkg.applicationInfo.primaryCpuAbi, 7753 pkg.applicationInfo.secondaryCpuAbi, 7754 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7755 user, false); 7756 if (pkgSetting == null) { 7757 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7758 "Creating application package " + pkg.packageName + " failed"); 7759 } 7760 7761 if (pkgSetting.origPackage != null) { 7762 // If we are first transitioning from an original package, 7763 // fix up the new package's name now. We need to do this after 7764 // looking up the package under its new name, so getPackageLP 7765 // can take care of fiddling things correctly. 7766 pkg.setPackageName(origPackage.name); 7767 7768 // File a report about this. 7769 String msg = "New package " + pkgSetting.realName 7770 + " renamed to replace old package " + pkgSetting.name; 7771 reportSettingsProblem(Log.WARN, msg); 7772 7773 // Make a note of it. 7774 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7775 mTransferedPackages.add(origPackage.name); 7776 } 7777 7778 // No longer need to retain this. 7779 pkgSetting.origPackage = null; 7780 } 7781 7782 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7783 // Make a note of it. 7784 mTransferedPackages.add(pkg.packageName); 7785 } 7786 7787 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7788 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7789 } 7790 7791 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7792 // Check all shared libraries and map to their actual file path. 7793 // We only do this here for apps not on a system dir, because those 7794 // are the only ones that can fail an install due to this. We 7795 // will take care of the system apps by updating all of their 7796 // library paths after the scan is done. 7797 updateSharedLibrariesLPw(pkg, null); 7798 } 7799 7800 if (mFoundPolicyFile) { 7801 SELinuxMMAC.assignSeinfoValue(pkg); 7802 } 7803 7804 pkg.applicationInfo.uid = pkgSetting.appId; 7805 pkg.mExtras = pkgSetting; 7806 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7807 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7808 // We just determined the app is signed correctly, so bring 7809 // over the latest parsed certs. 7810 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7811 } else { 7812 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7813 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7814 "Package " + pkg.packageName + " upgrade keys do not match the " 7815 + "previously installed version"); 7816 } else { 7817 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7818 String msg = "System package " + pkg.packageName 7819 + " signature changed; retaining data."; 7820 reportSettingsProblem(Log.WARN, msg); 7821 } 7822 } 7823 } else { 7824 try { 7825 verifySignaturesLP(pkgSetting, pkg); 7826 // We just determined the app is signed correctly, so bring 7827 // over the latest parsed certs. 7828 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7829 } catch (PackageManagerException e) { 7830 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7831 throw e; 7832 } 7833 // The signature has changed, but this package is in the system 7834 // image... let's recover! 7835 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7836 // However... if this package is part of a shared user, but it 7837 // doesn't match the signature of the shared user, let's fail. 7838 // What this means is that you can't change the signatures 7839 // associated with an overall shared user, which doesn't seem all 7840 // that unreasonable. 7841 if (pkgSetting.sharedUser != null) { 7842 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7843 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7844 throw new PackageManagerException( 7845 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7846 "Signature mismatch for shared user: " 7847 + pkgSetting.sharedUser); 7848 } 7849 } 7850 // File a report about this. 7851 String msg = "System package " + pkg.packageName 7852 + " signature changed; retaining data."; 7853 reportSettingsProblem(Log.WARN, msg); 7854 } 7855 } 7856 // Verify that this new package doesn't have any content providers 7857 // that conflict with existing packages. Only do this if the 7858 // package isn't already installed, since we don't want to break 7859 // things that are installed. 7860 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7861 final int N = pkg.providers.size(); 7862 int i; 7863 for (i=0; i<N; i++) { 7864 PackageParser.Provider p = pkg.providers.get(i); 7865 if (p.info.authority != null) { 7866 String names[] = p.info.authority.split(";"); 7867 for (int j = 0; j < names.length; j++) { 7868 if (mProvidersByAuthority.containsKey(names[j])) { 7869 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7870 final String otherPackageName = 7871 ((other != null && other.getComponentName() != null) ? 7872 other.getComponentName().getPackageName() : "?"); 7873 throw new PackageManagerException( 7874 INSTALL_FAILED_CONFLICTING_PROVIDER, 7875 "Can't install because provider name " + names[j] 7876 + " (in package " + pkg.applicationInfo.packageName 7877 + ") is already used by " + otherPackageName); 7878 } 7879 } 7880 } 7881 } 7882 } 7883 7884 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7885 // This package wants to adopt ownership of permissions from 7886 // another package. 7887 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7888 final String origName = pkg.mAdoptPermissions.get(i); 7889 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7890 if (orig != null) { 7891 if (verifyPackageUpdateLPr(orig, pkg)) { 7892 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7893 + pkg.packageName); 7894 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7895 } 7896 } 7897 } 7898 } 7899 } 7900 7901 final String pkgName = pkg.packageName; 7902 7903 final long scanFileTime = scanFile.lastModified(); 7904 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7905 pkg.applicationInfo.processName = fixProcessName( 7906 pkg.applicationInfo.packageName, 7907 pkg.applicationInfo.processName, 7908 pkg.applicationInfo.uid); 7909 7910 if (pkg != mPlatformPackage) { 7911 // Get all of our default paths setup 7912 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7913 } 7914 7915 final String path = scanFile.getPath(); 7916 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7917 7918 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7919 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7920 7921 // Some system apps still use directory structure for native libraries 7922 // in which case we might end up not detecting abi solely based on apk 7923 // structure. Try to detect abi based on directory structure. 7924 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7925 pkg.applicationInfo.primaryCpuAbi == null) { 7926 setBundledAppAbisAndRoots(pkg, pkgSetting); 7927 setNativeLibraryPaths(pkg); 7928 } 7929 7930 } else { 7931 if ((scanFlags & SCAN_MOVE) != 0) { 7932 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7933 // but we already have this packages package info in the PackageSetting. We just 7934 // use that and derive the native library path based on the new codepath. 7935 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7936 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7937 } 7938 7939 // Set native library paths again. For moves, the path will be updated based on the 7940 // ABIs we've determined above. For non-moves, the path will be updated based on the 7941 // ABIs we determined during compilation, but the path will depend on the final 7942 // package path (after the rename away from the stage path). 7943 setNativeLibraryPaths(pkg); 7944 } 7945 7946 // This is a special case for the "system" package, where the ABI is 7947 // dictated by the zygote configuration (and init.rc). We should keep track 7948 // of this ABI so that we can deal with "normal" applications that run under 7949 // the same UID correctly. 7950 if (mPlatformPackage == pkg) { 7951 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7952 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7953 } 7954 7955 // If there's a mismatch between the abi-override in the package setting 7956 // and the abiOverride specified for the install. Warn about this because we 7957 // would've already compiled the app without taking the package setting into 7958 // account. 7959 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7960 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7961 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7962 " for package " + pkg.packageName); 7963 } 7964 } 7965 7966 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7967 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7968 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7969 7970 // Copy the derived override back to the parsed package, so that we can 7971 // update the package settings accordingly. 7972 pkg.cpuAbiOverride = cpuAbiOverride; 7973 7974 if (DEBUG_ABI_SELECTION) { 7975 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7976 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7977 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7978 } 7979 7980 // Push the derived path down into PackageSettings so we know what to 7981 // clean up at uninstall time. 7982 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7983 7984 if (DEBUG_ABI_SELECTION) { 7985 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7986 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7987 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7988 } 7989 7990 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7991 // We don't do this here during boot because we can do it all 7992 // at once after scanning all existing packages. 7993 // 7994 // We also do this *before* we perform dexopt on this package, so that 7995 // we can avoid redundant dexopts, and also to make sure we've got the 7996 // code and package path correct. 7997 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7998 pkg, true /* boot complete */); 7999 } 8000 8001 if (mFactoryTest && pkg.requestedPermissions.contains( 8002 android.Manifest.permission.FACTORY_TEST)) { 8003 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8004 } 8005 8006 ArrayList<PackageParser.Package> clientLibPkgs = null; 8007 8008 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8009 if (nonMutatedPs != null) { 8010 synchronized (mPackages) { 8011 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8012 } 8013 } 8014 return pkg; 8015 } 8016 8017 // Only privileged apps and updated privileged apps can add child packages. 8018 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8019 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8020 throw new PackageManagerException("Only privileged apps and updated " 8021 + "privileged apps can add child packages. Ignoring package " 8022 + pkg.packageName); 8023 } 8024 final int childCount = pkg.childPackages.size(); 8025 for (int i = 0; i < childCount; i++) { 8026 PackageParser.Package childPkg = pkg.childPackages.get(i); 8027 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8028 childPkg.packageName)) { 8029 throw new PackageManagerException("Cannot override a child package of " 8030 + "another disabled system app. Ignoring package " + pkg.packageName); 8031 } 8032 } 8033 } 8034 8035 // writer 8036 synchronized (mPackages) { 8037 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8038 // Only system apps can add new shared libraries. 8039 if (pkg.libraryNames != null) { 8040 for (int i=0; i<pkg.libraryNames.size(); i++) { 8041 String name = pkg.libraryNames.get(i); 8042 boolean allowed = false; 8043 if (pkg.isUpdatedSystemApp()) { 8044 // New library entries can only be added through the 8045 // system image. This is important to get rid of a lot 8046 // of nasty edge cases: for example if we allowed a non- 8047 // system update of the app to add a library, then uninstalling 8048 // the update would make the library go away, and assumptions 8049 // we made such as through app install filtering would now 8050 // have allowed apps on the device which aren't compatible 8051 // with it. Better to just have the restriction here, be 8052 // conservative, and create many fewer cases that can negatively 8053 // impact the user experience. 8054 final PackageSetting sysPs = mSettings 8055 .getDisabledSystemPkgLPr(pkg.packageName); 8056 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8057 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8058 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8059 allowed = true; 8060 break; 8061 } 8062 } 8063 } 8064 } else { 8065 allowed = true; 8066 } 8067 if (allowed) { 8068 if (!mSharedLibraries.containsKey(name)) { 8069 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8070 } else if (!name.equals(pkg.packageName)) { 8071 Slog.w(TAG, "Package " + pkg.packageName + " library " 8072 + name + " already exists; skipping"); 8073 } 8074 } else { 8075 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8076 + name + " that is not declared on system image; skipping"); 8077 } 8078 } 8079 if ((scanFlags & SCAN_BOOTING) == 0) { 8080 // If we are not booting, we need to update any applications 8081 // that are clients of our shared library. If we are booting, 8082 // this will all be done once the scan is complete. 8083 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8084 } 8085 } 8086 } 8087 } 8088 8089 // Request the ActivityManager to kill the process(only for existing packages) 8090 // so that we do not end up in a confused state while the user is still using the older 8091 // version of the application while the new one gets installed. 8092 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8093 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8094 if (killApp) { 8095 if (isReplacing) { 8096 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8097 8098 killApplication(pkg.applicationInfo.packageName, 8099 pkg.applicationInfo.uid, "replace pkg"); 8100 8101 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8102 } 8103 } 8104 8105 // Also need to kill any apps that are dependent on the library. 8106 if (clientLibPkgs != null) { 8107 for (int i=0; i<clientLibPkgs.size(); i++) { 8108 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8109 killApplication(clientPkg.applicationInfo.packageName, 8110 clientPkg.applicationInfo.uid, "update lib"); 8111 } 8112 } 8113 8114 // Make sure we're not adding any bogus keyset info 8115 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8116 ksms.assertScannedPackageValid(pkg); 8117 8118 // writer 8119 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8120 8121 boolean createIdmapFailed = false; 8122 synchronized (mPackages) { 8123 // We don't expect installation to fail beyond this point 8124 8125 // Add the new setting to mSettings 8126 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8127 // Add the new setting to mPackages 8128 mPackages.put(pkg.applicationInfo.packageName, pkg); 8129 // Make sure we don't accidentally delete its data. 8130 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8131 while (iter.hasNext()) { 8132 PackageCleanItem item = iter.next(); 8133 if (pkgName.equals(item.packageName)) { 8134 iter.remove(); 8135 } 8136 } 8137 8138 // Take care of first install / last update times. 8139 if (currentTime != 0) { 8140 if (pkgSetting.firstInstallTime == 0) { 8141 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8142 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8143 pkgSetting.lastUpdateTime = currentTime; 8144 } 8145 } else if (pkgSetting.firstInstallTime == 0) { 8146 // We need *something*. Take time time stamp of the file. 8147 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8148 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8149 if (scanFileTime != pkgSetting.timeStamp) { 8150 // A package on the system image has changed; consider this 8151 // to be an update. 8152 pkgSetting.lastUpdateTime = scanFileTime; 8153 } 8154 } 8155 8156 // Add the package's KeySets to the global KeySetManagerService 8157 ksms.addScannedPackageLPw(pkg); 8158 8159 int N = pkg.providers.size(); 8160 StringBuilder r = null; 8161 int i; 8162 for (i=0; i<N; i++) { 8163 PackageParser.Provider p = pkg.providers.get(i); 8164 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8165 p.info.processName, pkg.applicationInfo.uid); 8166 mProviders.addProvider(p); 8167 p.syncable = p.info.isSyncable; 8168 if (p.info.authority != null) { 8169 String names[] = p.info.authority.split(";"); 8170 p.info.authority = null; 8171 for (int j = 0; j < names.length; j++) { 8172 if (j == 1 && p.syncable) { 8173 // We only want the first authority for a provider to possibly be 8174 // syncable, so if we already added this provider using a different 8175 // authority clear the syncable flag. We copy the provider before 8176 // changing it because the mProviders object contains a reference 8177 // to a provider that we don't want to change. 8178 // Only do this for the second authority since the resulting provider 8179 // object can be the same for all future authorities for this provider. 8180 p = new PackageParser.Provider(p); 8181 p.syncable = false; 8182 } 8183 if (!mProvidersByAuthority.containsKey(names[j])) { 8184 mProvidersByAuthority.put(names[j], p); 8185 if (p.info.authority == null) { 8186 p.info.authority = names[j]; 8187 } else { 8188 p.info.authority = p.info.authority + ";" + names[j]; 8189 } 8190 if (DEBUG_PACKAGE_SCANNING) { 8191 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8192 Log.d(TAG, "Registered content provider: " + names[j] 8193 + ", className = " + p.info.name + ", isSyncable = " 8194 + p.info.isSyncable); 8195 } 8196 } else { 8197 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8198 Slog.w(TAG, "Skipping provider name " + names[j] + 8199 " (in package " + pkg.applicationInfo.packageName + 8200 "): name already used by " 8201 + ((other != null && other.getComponentName() != null) 8202 ? other.getComponentName().getPackageName() : "?")); 8203 } 8204 } 8205 } 8206 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8207 if (r == null) { 8208 r = new StringBuilder(256); 8209 } else { 8210 r.append(' '); 8211 } 8212 r.append(p.info.name); 8213 } 8214 } 8215 if (r != null) { 8216 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8217 } 8218 8219 N = pkg.services.size(); 8220 r = null; 8221 for (i=0; i<N; i++) { 8222 PackageParser.Service s = pkg.services.get(i); 8223 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8224 s.info.processName, pkg.applicationInfo.uid); 8225 mServices.addService(s); 8226 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8227 if (r == null) { 8228 r = new StringBuilder(256); 8229 } else { 8230 r.append(' '); 8231 } 8232 r.append(s.info.name); 8233 } 8234 } 8235 if (r != null) { 8236 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8237 } 8238 8239 N = pkg.receivers.size(); 8240 r = null; 8241 for (i=0; i<N; i++) { 8242 PackageParser.Activity a = pkg.receivers.get(i); 8243 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8244 a.info.processName, pkg.applicationInfo.uid); 8245 mReceivers.addActivity(a, "receiver"); 8246 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8247 if (r == null) { 8248 r = new StringBuilder(256); 8249 } else { 8250 r.append(' '); 8251 } 8252 r.append(a.info.name); 8253 } 8254 } 8255 if (r != null) { 8256 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8257 } 8258 8259 N = pkg.activities.size(); 8260 r = null; 8261 for (i=0; i<N; i++) { 8262 PackageParser.Activity a = pkg.activities.get(i); 8263 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8264 a.info.processName, pkg.applicationInfo.uid); 8265 mActivities.addActivity(a, "activity"); 8266 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8267 if (r == null) { 8268 r = new StringBuilder(256); 8269 } else { 8270 r.append(' '); 8271 } 8272 r.append(a.info.name); 8273 } 8274 } 8275 if (r != null) { 8276 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8277 } 8278 8279 N = pkg.permissionGroups.size(); 8280 r = null; 8281 for (i=0; i<N; i++) { 8282 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8283 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8284 if (cur == null) { 8285 mPermissionGroups.put(pg.info.name, pg); 8286 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8287 if (r == null) { 8288 r = new StringBuilder(256); 8289 } else { 8290 r.append(' '); 8291 } 8292 r.append(pg.info.name); 8293 } 8294 } else { 8295 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8296 + pg.info.packageName + " ignored: original from " 8297 + cur.info.packageName); 8298 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8299 if (r == null) { 8300 r = new StringBuilder(256); 8301 } else { 8302 r.append(' '); 8303 } 8304 r.append("DUP:"); 8305 r.append(pg.info.name); 8306 } 8307 } 8308 } 8309 if (r != null) { 8310 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8311 } 8312 8313 N = pkg.permissions.size(); 8314 r = null; 8315 for (i=0; i<N; i++) { 8316 PackageParser.Permission p = pkg.permissions.get(i); 8317 8318 // Assume by default that we did not install this permission into the system. 8319 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8320 8321 // Now that permission groups have a special meaning, we ignore permission 8322 // groups for legacy apps to prevent unexpected behavior. In particular, 8323 // permissions for one app being granted to someone just becase they happen 8324 // to be in a group defined by another app (before this had no implications). 8325 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8326 p.group = mPermissionGroups.get(p.info.group); 8327 // Warn for a permission in an unknown group. 8328 if (p.info.group != null && p.group == null) { 8329 Slog.w(TAG, "Permission " + p.info.name + " from package " 8330 + p.info.packageName + " in an unknown group " + p.info.group); 8331 } 8332 } 8333 8334 ArrayMap<String, BasePermission> permissionMap = 8335 p.tree ? mSettings.mPermissionTrees 8336 : mSettings.mPermissions; 8337 BasePermission bp = permissionMap.get(p.info.name); 8338 8339 // Allow system apps to redefine non-system permissions 8340 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8341 final boolean currentOwnerIsSystem = (bp.perm != null 8342 && isSystemApp(bp.perm.owner)); 8343 if (isSystemApp(p.owner)) { 8344 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8345 // It's a built-in permission and no owner, take ownership now 8346 bp.packageSetting = pkgSetting; 8347 bp.perm = p; 8348 bp.uid = pkg.applicationInfo.uid; 8349 bp.sourcePackage = p.info.packageName; 8350 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8351 } else if (!currentOwnerIsSystem) { 8352 String msg = "New decl " + p.owner + " of permission " 8353 + p.info.name + " is system; overriding " + bp.sourcePackage; 8354 reportSettingsProblem(Log.WARN, msg); 8355 bp = null; 8356 } 8357 } 8358 } 8359 8360 if (bp == null) { 8361 bp = new BasePermission(p.info.name, p.info.packageName, 8362 BasePermission.TYPE_NORMAL); 8363 permissionMap.put(p.info.name, bp); 8364 } 8365 8366 if (bp.perm == null) { 8367 if (bp.sourcePackage == null 8368 || bp.sourcePackage.equals(p.info.packageName)) { 8369 BasePermission tree = findPermissionTreeLP(p.info.name); 8370 if (tree == null 8371 || tree.sourcePackage.equals(p.info.packageName)) { 8372 bp.packageSetting = pkgSetting; 8373 bp.perm = p; 8374 bp.uid = pkg.applicationInfo.uid; 8375 bp.sourcePackage = p.info.packageName; 8376 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8377 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8378 if (r == null) { 8379 r = new StringBuilder(256); 8380 } else { 8381 r.append(' '); 8382 } 8383 r.append(p.info.name); 8384 } 8385 } else { 8386 Slog.w(TAG, "Permission " + p.info.name + " from package " 8387 + p.info.packageName + " ignored: base tree " 8388 + tree.name + " is from package " 8389 + tree.sourcePackage); 8390 } 8391 } else { 8392 Slog.w(TAG, "Permission " + p.info.name + " from package " 8393 + p.info.packageName + " ignored: original from " 8394 + bp.sourcePackage); 8395 } 8396 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8397 if (r == null) { 8398 r = new StringBuilder(256); 8399 } else { 8400 r.append(' '); 8401 } 8402 r.append("DUP:"); 8403 r.append(p.info.name); 8404 } 8405 if (bp.perm == p) { 8406 bp.protectionLevel = p.info.protectionLevel; 8407 } 8408 } 8409 8410 if (r != null) { 8411 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8412 } 8413 8414 N = pkg.instrumentation.size(); 8415 r = null; 8416 for (i=0; i<N; i++) { 8417 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8418 a.info.packageName = pkg.applicationInfo.packageName; 8419 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8420 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8421 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8422 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8423 a.info.dataDir = pkg.applicationInfo.dataDir; 8424 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8425 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8426 8427 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8428 // need other information about the application, like the ABI and what not ? 8429 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8430 mInstrumentation.put(a.getComponentName(), a); 8431 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8432 if (r == null) { 8433 r = new StringBuilder(256); 8434 } else { 8435 r.append(' '); 8436 } 8437 r.append(a.info.name); 8438 } 8439 } 8440 if (r != null) { 8441 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8442 } 8443 8444 if (pkg.protectedBroadcasts != null) { 8445 N = pkg.protectedBroadcasts.size(); 8446 for (i=0; i<N; i++) { 8447 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8448 } 8449 } 8450 8451 pkgSetting.setTimeStamp(scanFileTime); 8452 8453 // Create idmap files for pairs of (packages, overlay packages). 8454 // Note: "android", ie framework-res.apk, is handled by native layers. 8455 if (pkg.mOverlayTarget != null) { 8456 // This is an overlay package. 8457 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8458 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8459 mOverlays.put(pkg.mOverlayTarget, 8460 new ArrayMap<String, PackageParser.Package>()); 8461 } 8462 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8463 map.put(pkg.packageName, pkg); 8464 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8465 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8466 createIdmapFailed = true; 8467 } 8468 } 8469 } else if (mOverlays.containsKey(pkg.packageName) && 8470 !pkg.packageName.equals("android")) { 8471 // This is a regular package, with one or more known overlay packages. 8472 createIdmapsForPackageLI(pkg); 8473 } 8474 } 8475 8476 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8477 8478 if (createIdmapFailed) { 8479 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8480 "scanPackageLI failed to createIdmap"); 8481 } 8482 return pkg; 8483 } 8484 8485 /** 8486 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8487 * is derived purely on the basis of the contents of {@code scanFile} and 8488 * {@code cpuAbiOverride}. 8489 * 8490 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8491 */ 8492 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8493 String cpuAbiOverride, boolean extractLibs) 8494 throws PackageManagerException { 8495 // TODO: We can probably be smarter about this stuff. For installed apps, 8496 // we can calculate this information at install time once and for all. For 8497 // system apps, we can probably assume that this information doesn't change 8498 // after the first boot scan. As things stand, we do lots of unnecessary work. 8499 8500 // Give ourselves some initial paths; we'll come back for another 8501 // pass once we've determined ABI below. 8502 setNativeLibraryPaths(pkg); 8503 8504 // We would never need to extract libs for forward-locked and external packages, 8505 // since the container service will do it for us. We shouldn't attempt to 8506 // extract libs from system app when it was not updated. 8507 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8508 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8509 extractLibs = false; 8510 } 8511 8512 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8513 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8514 8515 NativeLibraryHelper.Handle handle = null; 8516 try { 8517 handle = NativeLibraryHelper.Handle.create(pkg); 8518 // TODO(multiArch): This can be null for apps that didn't go through the 8519 // usual installation process. We can calculate it again, like we 8520 // do during install time. 8521 // 8522 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8523 // unnecessary. 8524 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8525 8526 // Null out the abis so that they can be recalculated. 8527 pkg.applicationInfo.primaryCpuAbi = null; 8528 pkg.applicationInfo.secondaryCpuAbi = null; 8529 if (isMultiArch(pkg.applicationInfo)) { 8530 // Warn if we've set an abiOverride for multi-lib packages.. 8531 // By definition, we need to copy both 32 and 64 bit libraries for 8532 // such packages. 8533 if (pkg.cpuAbiOverride != null 8534 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8535 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8536 } 8537 8538 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8539 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8540 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8541 if (extractLibs) { 8542 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8543 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8544 useIsaSpecificSubdirs); 8545 } else { 8546 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8547 } 8548 } 8549 8550 maybeThrowExceptionForMultiArchCopy( 8551 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8552 8553 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8554 if (extractLibs) { 8555 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8556 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8557 useIsaSpecificSubdirs); 8558 } else { 8559 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8560 } 8561 } 8562 8563 maybeThrowExceptionForMultiArchCopy( 8564 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8565 8566 if (abi64 >= 0) { 8567 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8568 } 8569 8570 if (abi32 >= 0) { 8571 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8572 if (abi64 >= 0) { 8573 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8574 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8575 pkg.applicationInfo.primaryCpuAbi = abi; 8576 } else { 8577 pkg.applicationInfo.secondaryCpuAbi = abi; 8578 } 8579 } else { 8580 pkg.applicationInfo.primaryCpuAbi = abi; 8581 } 8582 } 8583 8584 } else { 8585 String[] abiList = (cpuAbiOverride != null) ? 8586 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8587 8588 // Enable gross and lame hacks for apps that are built with old 8589 // SDK tools. We must scan their APKs for renderscript bitcode and 8590 // not launch them if it's present. Don't bother checking on devices 8591 // that don't have 64 bit support. 8592 boolean needsRenderScriptOverride = false; 8593 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8594 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8595 abiList = Build.SUPPORTED_32_BIT_ABIS; 8596 needsRenderScriptOverride = true; 8597 } 8598 8599 final int copyRet; 8600 if (extractLibs) { 8601 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8602 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8603 } else { 8604 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8605 } 8606 8607 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8608 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8609 "Error unpackaging native libs for app, errorCode=" + copyRet); 8610 } 8611 8612 if (copyRet >= 0) { 8613 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8614 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8615 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8616 } else if (needsRenderScriptOverride) { 8617 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8618 } 8619 } 8620 } catch (IOException ioe) { 8621 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8622 } finally { 8623 IoUtils.closeQuietly(handle); 8624 } 8625 8626 // Now that we've calculated the ABIs and determined if it's an internal app, 8627 // we will go ahead and populate the nativeLibraryPath. 8628 setNativeLibraryPaths(pkg); 8629 } 8630 8631 /** 8632 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8633 * i.e, so that all packages can be run inside a single process if required. 8634 * 8635 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8636 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8637 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8638 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8639 * updating a package that belongs to a shared user. 8640 * 8641 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8642 * adds unnecessary complexity. 8643 */ 8644 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8645 PackageParser.Package scannedPackage, boolean bootComplete) { 8646 String requiredInstructionSet = null; 8647 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8648 requiredInstructionSet = VMRuntime.getInstructionSet( 8649 scannedPackage.applicationInfo.primaryCpuAbi); 8650 } 8651 8652 PackageSetting requirer = null; 8653 for (PackageSetting ps : packagesForUser) { 8654 // If packagesForUser contains scannedPackage, we skip it. This will happen 8655 // when scannedPackage is an update of an existing package. Without this check, 8656 // we will never be able to change the ABI of any package belonging to a shared 8657 // user, even if it's compatible with other packages. 8658 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8659 if (ps.primaryCpuAbiString == null) { 8660 continue; 8661 } 8662 8663 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8664 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8665 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8666 // this but there's not much we can do. 8667 String errorMessage = "Instruction set mismatch, " 8668 + ((requirer == null) ? "[caller]" : requirer) 8669 + " requires " + requiredInstructionSet + " whereas " + ps 8670 + " requires " + instructionSet; 8671 Slog.w(TAG, errorMessage); 8672 } 8673 8674 if (requiredInstructionSet == null) { 8675 requiredInstructionSet = instructionSet; 8676 requirer = ps; 8677 } 8678 } 8679 } 8680 8681 if (requiredInstructionSet != null) { 8682 String adjustedAbi; 8683 if (requirer != null) { 8684 // requirer != null implies that either scannedPackage was null or that scannedPackage 8685 // did not require an ABI, in which case we have to adjust scannedPackage to match 8686 // the ABI of the set (which is the same as requirer's ABI) 8687 adjustedAbi = requirer.primaryCpuAbiString; 8688 if (scannedPackage != null) { 8689 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8690 } 8691 } else { 8692 // requirer == null implies that we're updating all ABIs in the set to 8693 // match scannedPackage. 8694 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8695 } 8696 8697 for (PackageSetting ps : packagesForUser) { 8698 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8699 if (ps.primaryCpuAbiString != null) { 8700 continue; 8701 } 8702 8703 ps.primaryCpuAbiString = adjustedAbi; 8704 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8705 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8706 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8707 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8708 + " (requirer=" 8709 + (requirer == null ? "null" : requirer.pkg.packageName) 8710 + ", scannedPackage=" 8711 + (scannedPackage != null ? scannedPackage.packageName : "null") 8712 + ")"); 8713 try { 8714 mInstaller.rmdex(ps.codePathString, 8715 getDexCodeInstructionSet(getPreferredInstructionSet())); 8716 } catch (InstallerException ignored) { 8717 } 8718 } 8719 } 8720 } 8721 } 8722 } 8723 8724 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8725 synchronized (mPackages) { 8726 mResolverReplaced = true; 8727 // Set up information for custom user intent resolution activity. 8728 mResolveActivity.applicationInfo = pkg.applicationInfo; 8729 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8730 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8731 mResolveActivity.processName = pkg.applicationInfo.packageName; 8732 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8733 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8734 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8735 mResolveActivity.theme = 0; 8736 mResolveActivity.exported = true; 8737 mResolveActivity.enabled = true; 8738 mResolveInfo.activityInfo = mResolveActivity; 8739 mResolveInfo.priority = 0; 8740 mResolveInfo.preferredOrder = 0; 8741 mResolveInfo.match = 0; 8742 mResolveComponentName = mCustomResolverComponentName; 8743 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8744 mResolveComponentName); 8745 } 8746 } 8747 8748 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8749 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8750 8751 // Set up information for ephemeral installer activity 8752 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8753 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8754 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8755 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8756 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8757 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8758 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8759 mEphemeralInstallerActivity.theme = 0; 8760 mEphemeralInstallerActivity.exported = true; 8761 mEphemeralInstallerActivity.enabled = true; 8762 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8763 mEphemeralInstallerInfo.priority = 0; 8764 mEphemeralInstallerInfo.preferredOrder = 0; 8765 mEphemeralInstallerInfo.match = 0; 8766 8767 if (DEBUG_EPHEMERAL) { 8768 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8769 } 8770 } 8771 8772 private static String calculateBundledApkRoot(final String codePathString) { 8773 final File codePath = new File(codePathString); 8774 final File codeRoot; 8775 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8776 codeRoot = Environment.getRootDirectory(); 8777 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8778 codeRoot = Environment.getOemDirectory(); 8779 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8780 codeRoot = Environment.getVendorDirectory(); 8781 } else { 8782 // Unrecognized code path; take its top real segment as the apk root: 8783 // e.g. /something/app/blah.apk => /something 8784 try { 8785 File f = codePath.getCanonicalFile(); 8786 File parent = f.getParentFile(); // non-null because codePath is a file 8787 File tmp; 8788 while ((tmp = parent.getParentFile()) != null) { 8789 f = parent; 8790 parent = tmp; 8791 } 8792 codeRoot = f; 8793 Slog.w(TAG, "Unrecognized code path " 8794 + codePath + " - using " + codeRoot); 8795 } catch (IOException e) { 8796 // Can't canonicalize the code path -- shenanigans? 8797 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8798 return Environment.getRootDirectory().getPath(); 8799 } 8800 } 8801 return codeRoot.getPath(); 8802 } 8803 8804 /** 8805 * Derive and set the location of native libraries for the given package, 8806 * which varies depending on where and how the package was installed. 8807 */ 8808 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8809 final ApplicationInfo info = pkg.applicationInfo; 8810 final String codePath = pkg.codePath; 8811 final File codeFile = new File(codePath); 8812 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8813 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8814 8815 info.nativeLibraryRootDir = null; 8816 info.nativeLibraryRootRequiresIsa = false; 8817 info.nativeLibraryDir = null; 8818 info.secondaryNativeLibraryDir = null; 8819 8820 if (isApkFile(codeFile)) { 8821 // Monolithic install 8822 if (bundledApp) { 8823 // If "/system/lib64/apkname" exists, assume that is the per-package 8824 // native library directory to use; otherwise use "/system/lib/apkname". 8825 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8826 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8827 getPrimaryInstructionSet(info)); 8828 8829 // This is a bundled system app so choose the path based on the ABI. 8830 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8831 // is just the default path. 8832 final String apkName = deriveCodePathName(codePath); 8833 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8834 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8835 apkName).getAbsolutePath(); 8836 8837 if (info.secondaryCpuAbi != null) { 8838 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8839 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8840 secondaryLibDir, apkName).getAbsolutePath(); 8841 } 8842 } else if (asecApp) { 8843 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8844 .getAbsolutePath(); 8845 } else { 8846 final String apkName = deriveCodePathName(codePath); 8847 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8848 .getAbsolutePath(); 8849 } 8850 8851 info.nativeLibraryRootRequiresIsa = false; 8852 info.nativeLibraryDir = info.nativeLibraryRootDir; 8853 } else { 8854 // Cluster install 8855 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8856 info.nativeLibraryRootRequiresIsa = true; 8857 8858 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8859 getPrimaryInstructionSet(info)).getAbsolutePath(); 8860 8861 if (info.secondaryCpuAbi != null) { 8862 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8863 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8864 } 8865 } 8866 } 8867 8868 /** 8869 * Calculate the abis and roots for a bundled app. These can uniquely 8870 * be determined from the contents of the system partition, i.e whether 8871 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8872 * of this information, and instead assume that the system was built 8873 * sensibly. 8874 */ 8875 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8876 PackageSetting pkgSetting) { 8877 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8878 8879 // If "/system/lib64/apkname" exists, assume that is the per-package 8880 // native library directory to use; otherwise use "/system/lib/apkname". 8881 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8882 setBundledAppAbi(pkg, apkRoot, apkName); 8883 // pkgSetting might be null during rescan following uninstall of updates 8884 // to a bundled app, so accommodate that possibility. The settings in 8885 // that case will be established later from the parsed package. 8886 // 8887 // If the settings aren't null, sync them up with what we've just derived. 8888 // note that apkRoot isn't stored in the package settings. 8889 if (pkgSetting != null) { 8890 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8891 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8892 } 8893 } 8894 8895 /** 8896 * Deduces the ABI of a bundled app and sets the relevant fields on the 8897 * parsed pkg object. 8898 * 8899 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8900 * under which system libraries are installed. 8901 * @param apkName the name of the installed package. 8902 */ 8903 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8904 final File codeFile = new File(pkg.codePath); 8905 8906 final boolean has64BitLibs; 8907 final boolean has32BitLibs; 8908 if (isApkFile(codeFile)) { 8909 // Monolithic install 8910 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8911 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8912 } else { 8913 // Cluster install 8914 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8915 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8916 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8917 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8918 has64BitLibs = (new File(rootDir, isa)).exists(); 8919 } else { 8920 has64BitLibs = false; 8921 } 8922 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8923 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8924 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8925 has32BitLibs = (new File(rootDir, isa)).exists(); 8926 } else { 8927 has32BitLibs = false; 8928 } 8929 } 8930 8931 if (has64BitLibs && !has32BitLibs) { 8932 // The package has 64 bit libs, but not 32 bit libs. Its primary 8933 // ABI should be 64 bit. We can safely assume here that the bundled 8934 // native libraries correspond to the most preferred ABI in the list. 8935 8936 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8937 pkg.applicationInfo.secondaryCpuAbi = null; 8938 } else if (has32BitLibs && !has64BitLibs) { 8939 // The package has 32 bit libs but not 64 bit libs. Its primary 8940 // ABI should be 32 bit. 8941 8942 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8943 pkg.applicationInfo.secondaryCpuAbi = null; 8944 } else if (has32BitLibs && has64BitLibs) { 8945 // The application has both 64 and 32 bit bundled libraries. We check 8946 // here that the app declares multiArch support, and warn if it doesn't. 8947 // 8948 // We will be lenient here and record both ABIs. The primary will be the 8949 // ABI that's higher on the list, i.e, a device that's configured to prefer 8950 // 64 bit apps will see a 64 bit primary ABI, 8951 8952 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8953 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8954 } 8955 8956 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8957 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8958 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8959 } else { 8960 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8961 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8962 } 8963 } else { 8964 pkg.applicationInfo.primaryCpuAbi = null; 8965 pkg.applicationInfo.secondaryCpuAbi = null; 8966 } 8967 } 8968 8969 private void killPackage(PackageParser.Package pkg, String reason) { 8970 // Kill the parent package 8971 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8972 // Kill the child packages 8973 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8974 for (int i = 0; i < childCount; i++) { 8975 PackageParser.Package childPkg = pkg.childPackages.get(i); 8976 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8977 } 8978 } 8979 8980 private void killApplication(String pkgName, int appId, String reason) { 8981 // Request the ActivityManager to kill the process(only for existing packages) 8982 // so that we do not end up in a confused state while the user is still using the older 8983 // version of the application while the new one gets installed. 8984 IActivityManager am = ActivityManagerNative.getDefault(); 8985 if (am != null) { 8986 try { 8987 am.killApplicationWithAppId(pkgName, appId, reason); 8988 } catch (RemoteException e) { 8989 } 8990 } 8991 } 8992 8993 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8994 // Remove the parent package setting 8995 PackageSetting ps = (PackageSetting) pkg.mExtras; 8996 if (ps != null) { 8997 removePackageLI(ps, chatty); 8998 } 8999 // Remove the child package setting 9000 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9001 for (int i = 0; i < childCount; i++) { 9002 PackageParser.Package childPkg = pkg.childPackages.get(i); 9003 ps = (PackageSetting) childPkg.mExtras; 9004 if (ps != null) { 9005 removePackageLI(ps, chatty); 9006 } 9007 } 9008 } 9009 9010 void removePackageLI(PackageSetting ps, boolean chatty) { 9011 if (DEBUG_INSTALL) { 9012 if (chatty) 9013 Log.d(TAG, "Removing package " + ps.name); 9014 } 9015 9016 // writer 9017 synchronized (mPackages) { 9018 mPackages.remove(ps.name); 9019 final PackageParser.Package pkg = ps.pkg; 9020 if (pkg != null) { 9021 cleanPackageDataStructuresLILPw(pkg, chatty); 9022 } 9023 } 9024 } 9025 9026 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9027 if (DEBUG_INSTALL) { 9028 if (chatty) 9029 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9030 } 9031 9032 // writer 9033 synchronized (mPackages) { 9034 // Remove the parent package 9035 mPackages.remove(pkg.applicationInfo.packageName); 9036 cleanPackageDataStructuresLILPw(pkg, chatty); 9037 9038 // Remove the child packages 9039 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9040 for (int i = 0; i < childCount; i++) { 9041 PackageParser.Package childPkg = pkg.childPackages.get(i); 9042 mPackages.remove(childPkg.applicationInfo.packageName); 9043 cleanPackageDataStructuresLILPw(childPkg, chatty); 9044 } 9045 } 9046 } 9047 9048 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9049 int N = pkg.providers.size(); 9050 StringBuilder r = null; 9051 int i; 9052 for (i=0; i<N; i++) { 9053 PackageParser.Provider p = pkg.providers.get(i); 9054 mProviders.removeProvider(p); 9055 if (p.info.authority == null) { 9056 9057 /* There was another ContentProvider with this authority when 9058 * this app was installed so this authority is null, 9059 * Ignore it as we don't have to unregister the provider. 9060 */ 9061 continue; 9062 } 9063 String names[] = p.info.authority.split(";"); 9064 for (int j = 0; j < names.length; j++) { 9065 if (mProvidersByAuthority.get(names[j]) == p) { 9066 mProvidersByAuthority.remove(names[j]); 9067 if (DEBUG_REMOVE) { 9068 if (chatty) 9069 Log.d(TAG, "Unregistered content provider: " + names[j] 9070 + ", className = " + p.info.name + ", isSyncable = " 9071 + p.info.isSyncable); 9072 } 9073 } 9074 } 9075 if (DEBUG_REMOVE && chatty) { 9076 if (r == null) { 9077 r = new StringBuilder(256); 9078 } else { 9079 r.append(' '); 9080 } 9081 r.append(p.info.name); 9082 } 9083 } 9084 if (r != null) { 9085 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9086 } 9087 9088 N = pkg.services.size(); 9089 r = null; 9090 for (i=0; i<N; i++) { 9091 PackageParser.Service s = pkg.services.get(i); 9092 mServices.removeService(s); 9093 if (chatty) { 9094 if (r == null) { 9095 r = new StringBuilder(256); 9096 } else { 9097 r.append(' '); 9098 } 9099 r.append(s.info.name); 9100 } 9101 } 9102 if (r != null) { 9103 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9104 } 9105 9106 N = pkg.receivers.size(); 9107 r = null; 9108 for (i=0; i<N; i++) { 9109 PackageParser.Activity a = pkg.receivers.get(i); 9110 mReceivers.removeActivity(a, "receiver"); 9111 if (DEBUG_REMOVE && chatty) { 9112 if (r == null) { 9113 r = new StringBuilder(256); 9114 } else { 9115 r.append(' '); 9116 } 9117 r.append(a.info.name); 9118 } 9119 } 9120 if (r != null) { 9121 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9122 } 9123 9124 N = pkg.activities.size(); 9125 r = null; 9126 for (i=0; i<N; i++) { 9127 PackageParser.Activity a = pkg.activities.get(i); 9128 mActivities.removeActivity(a, "activity"); 9129 if (DEBUG_REMOVE && chatty) { 9130 if (r == null) { 9131 r = new StringBuilder(256); 9132 } else { 9133 r.append(' '); 9134 } 9135 r.append(a.info.name); 9136 } 9137 } 9138 if (r != null) { 9139 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9140 } 9141 9142 N = pkg.permissions.size(); 9143 r = null; 9144 for (i=0; i<N; i++) { 9145 PackageParser.Permission p = pkg.permissions.get(i); 9146 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9147 if (bp == null) { 9148 bp = mSettings.mPermissionTrees.get(p.info.name); 9149 } 9150 if (bp != null && bp.perm == p) { 9151 bp.perm = null; 9152 if (DEBUG_REMOVE && chatty) { 9153 if (r == null) { 9154 r = new StringBuilder(256); 9155 } else { 9156 r.append(' '); 9157 } 9158 r.append(p.info.name); 9159 } 9160 } 9161 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9162 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9163 if (appOpPkgs != null) { 9164 appOpPkgs.remove(pkg.packageName); 9165 } 9166 } 9167 } 9168 if (r != null) { 9169 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9170 } 9171 9172 N = pkg.requestedPermissions.size(); 9173 r = null; 9174 for (i=0; i<N; i++) { 9175 String perm = pkg.requestedPermissions.get(i); 9176 BasePermission bp = mSettings.mPermissions.get(perm); 9177 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9178 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9179 if (appOpPkgs != null) { 9180 appOpPkgs.remove(pkg.packageName); 9181 if (appOpPkgs.isEmpty()) { 9182 mAppOpPermissionPackages.remove(perm); 9183 } 9184 } 9185 } 9186 } 9187 if (r != null) { 9188 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9189 } 9190 9191 N = pkg.instrumentation.size(); 9192 r = null; 9193 for (i=0; i<N; i++) { 9194 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9195 mInstrumentation.remove(a.getComponentName()); 9196 if (DEBUG_REMOVE && chatty) { 9197 if (r == null) { 9198 r = new StringBuilder(256); 9199 } else { 9200 r.append(' '); 9201 } 9202 r.append(a.info.name); 9203 } 9204 } 9205 if (r != null) { 9206 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9207 } 9208 9209 r = null; 9210 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9211 // Only system apps can hold shared libraries. 9212 if (pkg.libraryNames != null) { 9213 for (i=0; i<pkg.libraryNames.size(); i++) { 9214 String name = pkg.libraryNames.get(i); 9215 SharedLibraryEntry cur = mSharedLibraries.get(name); 9216 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9217 mSharedLibraries.remove(name); 9218 if (DEBUG_REMOVE && chatty) { 9219 if (r == null) { 9220 r = new StringBuilder(256); 9221 } else { 9222 r.append(' '); 9223 } 9224 r.append(name); 9225 } 9226 } 9227 } 9228 } 9229 } 9230 if (r != null) { 9231 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9232 } 9233 } 9234 9235 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9236 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9237 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9238 return true; 9239 } 9240 } 9241 return false; 9242 } 9243 9244 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9245 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9246 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9247 9248 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9249 // Update the parent permissions 9250 updatePermissionsLPw(pkg.packageName, pkg, flags); 9251 // Update the child permissions 9252 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9253 for (int i = 0; i < childCount; i++) { 9254 PackageParser.Package childPkg = pkg.childPackages.get(i); 9255 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9256 } 9257 } 9258 9259 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9260 int flags) { 9261 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9262 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9263 } 9264 9265 private void updatePermissionsLPw(String changingPkg, 9266 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9267 // Make sure there are no dangling permission trees. 9268 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9269 while (it.hasNext()) { 9270 final BasePermission bp = it.next(); 9271 if (bp.packageSetting == null) { 9272 // We may not yet have parsed the package, so just see if 9273 // we still know about its settings. 9274 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9275 } 9276 if (bp.packageSetting == null) { 9277 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9278 + " from package " + bp.sourcePackage); 9279 it.remove(); 9280 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9281 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9282 Slog.i(TAG, "Removing old permission tree: " + bp.name 9283 + " from package " + bp.sourcePackage); 9284 flags |= UPDATE_PERMISSIONS_ALL; 9285 it.remove(); 9286 } 9287 } 9288 } 9289 9290 // Make sure all dynamic permissions have been assigned to a package, 9291 // and make sure there are no dangling permissions. 9292 it = mSettings.mPermissions.values().iterator(); 9293 while (it.hasNext()) { 9294 final BasePermission bp = it.next(); 9295 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9296 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9297 + bp.name + " pkg=" + bp.sourcePackage 9298 + " info=" + bp.pendingInfo); 9299 if (bp.packageSetting == null && bp.pendingInfo != null) { 9300 final BasePermission tree = findPermissionTreeLP(bp.name); 9301 if (tree != null && tree.perm != null) { 9302 bp.packageSetting = tree.packageSetting; 9303 bp.perm = new PackageParser.Permission(tree.perm.owner, 9304 new PermissionInfo(bp.pendingInfo)); 9305 bp.perm.info.packageName = tree.perm.info.packageName; 9306 bp.perm.info.name = bp.name; 9307 bp.uid = tree.uid; 9308 } 9309 } 9310 } 9311 if (bp.packageSetting == null) { 9312 // We may not yet have parsed the package, so just see if 9313 // we still know about its settings. 9314 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9315 } 9316 if (bp.packageSetting == null) { 9317 Slog.w(TAG, "Removing dangling permission: " + bp.name 9318 + " from package " + bp.sourcePackage); 9319 it.remove(); 9320 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9321 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9322 Slog.i(TAG, "Removing old permission: " + bp.name 9323 + " from package " + bp.sourcePackage); 9324 flags |= UPDATE_PERMISSIONS_ALL; 9325 it.remove(); 9326 } 9327 } 9328 } 9329 9330 // Now update the permissions for all packages, in particular 9331 // replace the granted permissions of the system packages. 9332 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9333 for (PackageParser.Package pkg : mPackages.values()) { 9334 if (pkg != pkgInfo) { 9335 // Only replace for packages on requested volume 9336 final String volumeUuid = getVolumeUuidForPackage(pkg); 9337 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9338 && Objects.equals(replaceVolumeUuid, volumeUuid); 9339 grantPermissionsLPw(pkg, replace, changingPkg); 9340 } 9341 } 9342 } 9343 9344 if (pkgInfo != null) { 9345 // Only replace for packages on requested volume 9346 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9347 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9348 && Objects.equals(replaceVolumeUuid, volumeUuid); 9349 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9350 } 9351 } 9352 9353 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9354 String packageOfInterest) { 9355 // IMPORTANT: There are two types of permissions: install and runtime. 9356 // Install time permissions are granted when the app is installed to 9357 // all device users and users added in the future. Runtime permissions 9358 // are granted at runtime explicitly to specific users. Normal and signature 9359 // protected permissions are install time permissions. Dangerous permissions 9360 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9361 // otherwise they are runtime permissions. This function does not manage 9362 // runtime permissions except for the case an app targeting Lollipop MR1 9363 // being upgraded to target a newer SDK, in which case dangerous permissions 9364 // are transformed from install time to runtime ones. 9365 9366 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9367 if (ps == null) { 9368 return; 9369 } 9370 9371 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9372 9373 PermissionsState permissionsState = ps.getPermissionsState(); 9374 PermissionsState origPermissions = permissionsState; 9375 9376 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9377 9378 boolean runtimePermissionsRevoked = false; 9379 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9380 9381 boolean changedInstallPermission = false; 9382 9383 if (replace) { 9384 ps.installPermissionsFixed = false; 9385 if (!ps.isSharedUser()) { 9386 origPermissions = new PermissionsState(permissionsState); 9387 permissionsState.reset(); 9388 } else { 9389 // We need to know only about runtime permission changes since the 9390 // calling code always writes the install permissions state but 9391 // the runtime ones are written only if changed. The only cases of 9392 // changed runtime permissions here are promotion of an install to 9393 // runtime and revocation of a runtime from a shared user. 9394 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9395 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9396 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9397 runtimePermissionsRevoked = true; 9398 } 9399 } 9400 } 9401 9402 permissionsState.setGlobalGids(mGlobalGids); 9403 9404 final int N = pkg.requestedPermissions.size(); 9405 for (int i=0; i<N; i++) { 9406 final String name = pkg.requestedPermissions.get(i); 9407 final BasePermission bp = mSettings.mPermissions.get(name); 9408 9409 if (DEBUG_INSTALL) { 9410 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9411 } 9412 9413 if (bp == null || bp.packageSetting == null) { 9414 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9415 Slog.w(TAG, "Unknown permission " + name 9416 + " in package " + pkg.packageName); 9417 } 9418 continue; 9419 } 9420 9421 final String perm = bp.name; 9422 boolean allowedSig = false; 9423 int grant = GRANT_DENIED; 9424 9425 // Keep track of app op permissions. 9426 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9427 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9428 if (pkgs == null) { 9429 pkgs = new ArraySet<>(); 9430 mAppOpPermissionPackages.put(bp.name, pkgs); 9431 } 9432 pkgs.add(pkg.packageName); 9433 } 9434 9435 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9436 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9437 >= Build.VERSION_CODES.M; 9438 switch (level) { 9439 case PermissionInfo.PROTECTION_NORMAL: { 9440 // For all apps normal permissions are install time ones. 9441 grant = GRANT_INSTALL; 9442 } break; 9443 9444 case PermissionInfo.PROTECTION_DANGEROUS: { 9445 // If a permission review is required for legacy apps we represent 9446 // their permissions as always granted runtime ones since we need 9447 // to keep the review required permission flag per user while an 9448 // install permission's state is shared across all users. 9449 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9450 // For legacy apps dangerous permissions are install time ones. 9451 grant = GRANT_INSTALL; 9452 } else if (origPermissions.hasInstallPermission(bp.name)) { 9453 // For legacy apps that became modern, install becomes runtime. 9454 grant = GRANT_UPGRADE; 9455 } else if (mPromoteSystemApps 9456 && isSystemApp(ps) 9457 && mExistingSystemPackages.contains(ps.name)) { 9458 // For legacy system apps, install becomes runtime. 9459 // We cannot check hasInstallPermission() for system apps since those 9460 // permissions were granted implicitly and not persisted pre-M. 9461 grant = GRANT_UPGRADE; 9462 } else { 9463 // For modern apps keep runtime permissions unchanged. 9464 grant = GRANT_RUNTIME; 9465 } 9466 } break; 9467 9468 case PermissionInfo.PROTECTION_SIGNATURE: { 9469 // For all apps signature permissions are install time ones. 9470 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9471 if (allowedSig) { 9472 grant = GRANT_INSTALL; 9473 } 9474 } break; 9475 } 9476 9477 if (DEBUG_INSTALL) { 9478 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9479 } 9480 9481 if (grant != GRANT_DENIED) { 9482 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9483 // If this is an existing, non-system package, then 9484 // we can't add any new permissions to it. 9485 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9486 // Except... if this is a permission that was added 9487 // to the platform (note: need to only do this when 9488 // updating the platform). 9489 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9490 grant = GRANT_DENIED; 9491 } 9492 } 9493 } 9494 9495 switch (grant) { 9496 case GRANT_INSTALL: { 9497 // Revoke this as runtime permission to handle the case of 9498 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9499 for (int userId : UserManagerService.getInstance().getUserIds()) { 9500 if (origPermissions.getRuntimePermissionState( 9501 bp.name, userId) != null) { 9502 // Revoke the runtime permission and clear the flags. 9503 origPermissions.revokeRuntimePermission(bp, userId); 9504 origPermissions.updatePermissionFlags(bp, userId, 9505 PackageManager.MASK_PERMISSION_FLAGS, 0); 9506 // If we revoked a permission permission, we have to write. 9507 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9508 changedRuntimePermissionUserIds, userId); 9509 } 9510 } 9511 // Grant an install permission. 9512 if (permissionsState.grantInstallPermission(bp) != 9513 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9514 changedInstallPermission = true; 9515 } 9516 } break; 9517 9518 case GRANT_RUNTIME: { 9519 // Grant previously granted runtime permissions. 9520 for (int userId : UserManagerService.getInstance().getUserIds()) { 9521 PermissionState permissionState = origPermissions 9522 .getRuntimePermissionState(bp.name, userId); 9523 int flags = permissionState != null 9524 ? permissionState.getFlags() : 0; 9525 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9526 if (permissionsState.grantRuntimePermission(bp, userId) == 9527 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9528 // If we cannot put the permission as it was, we have to write. 9529 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9530 changedRuntimePermissionUserIds, userId); 9531 } 9532 // If the app supports runtime permissions no need for a review. 9533 if (Build.PERMISSIONS_REVIEW_REQUIRED 9534 && appSupportsRuntimePermissions 9535 && (flags & PackageManager 9536 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9537 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9538 // Since we changed the flags, we have to write. 9539 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9540 changedRuntimePermissionUserIds, userId); 9541 } 9542 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9543 && !appSupportsRuntimePermissions) { 9544 // For legacy apps that need a permission review, every new 9545 // runtime permission is granted but it is pending a review. 9546 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9547 permissionsState.grantRuntimePermission(bp, userId); 9548 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9549 // We changed the permission and flags, hence have to write. 9550 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9551 changedRuntimePermissionUserIds, userId); 9552 } 9553 } 9554 // Propagate the permission flags. 9555 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9556 } 9557 } break; 9558 9559 case GRANT_UPGRADE: { 9560 // Grant runtime permissions for a previously held install permission. 9561 PermissionState permissionState = origPermissions 9562 .getInstallPermissionState(bp.name); 9563 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9564 9565 if (origPermissions.revokeInstallPermission(bp) 9566 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9567 // We will be transferring the permission flags, so clear them. 9568 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9569 PackageManager.MASK_PERMISSION_FLAGS, 0); 9570 changedInstallPermission = true; 9571 } 9572 9573 // If the permission is not to be promoted to runtime we ignore it and 9574 // also its other flags as they are not applicable to install permissions. 9575 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9576 for (int userId : currentUserIds) { 9577 if (permissionsState.grantRuntimePermission(bp, userId) != 9578 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9579 // Transfer the permission flags. 9580 permissionsState.updatePermissionFlags(bp, userId, 9581 flags, flags); 9582 // If we granted the permission, we have to write. 9583 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9584 changedRuntimePermissionUserIds, userId); 9585 } 9586 } 9587 } 9588 } break; 9589 9590 default: { 9591 if (packageOfInterest == null 9592 || packageOfInterest.equals(pkg.packageName)) { 9593 Slog.w(TAG, "Not granting permission " + perm 9594 + " to package " + pkg.packageName 9595 + " because it was previously installed without"); 9596 } 9597 } break; 9598 } 9599 } else { 9600 if (permissionsState.revokeInstallPermission(bp) != 9601 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9602 // Also drop the permission flags. 9603 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9604 PackageManager.MASK_PERMISSION_FLAGS, 0); 9605 changedInstallPermission = true; 9606 Slog.i(TAG, "Un-granting permission " + perm 9607 + " from package " + pkg.packageName 9608 + " (protectionLevel=" + bp.protectionLevel 9609 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9610 + ")"); 9611 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9612 // Don't print warning for app op permissions, since it is fine for them 9613 // not to be granted, there is a UI for the user to decide. 9614 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9615 Slog.w(TAG, "Not granting permission " + perm 9616 + " to package " + pkg.packageName 9617 + " (protectionLevel=" + bp.protectionLevel 9618 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9619 + ")"); 9620 } 9621 } 9622 } 9623 } 9624 9625 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9626 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9627 // This is the first that we have heard about this package, so the 9628 // permissions we have now selected are fixed until explicitly 9629 // changed. 9630 ps.installPermissionsFixed = true; 9631 } 9632 9633 // Persist the runtime permissions state for users with changes. If permissions 9634 // were revoked because no app in the shared user declares them we have to 9635 // write synchronously to avoid losing runtime permissions state. 9636 for (int userId : changedRuntimePermissionUserIds) { 9637 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9638 } 9639 9640 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9641 } 9642 9643 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9644 boolean allowed = false; 9645 final int NP = PackageParser.NEW_PERMISSIONS.length; 9646 for (int ip=0; ip<NP; ip++) { 9647 final PackageParser.NewPermissionInfo npi 9648 = PackageParser.NEW_PERMISSIONS[ip]; 9649 if (npi.name.equals(perm) 9650 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9651 allowed = true; 9652 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9653 + pkg.packageName); 9654 break; 9655 } 9656 } 9657 return allowed; 9658 } 9659 9660 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9661 BasePermission bp, PermissionsState origPermissions) { 9662 boolean allowed; 9663 allowed = (compareSignatures( 9664 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9665 == PackageManager.SIGNATURE_MATCH) 9666 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9667 == PackageManager.SIGNATURE_MATCH); 9668 if (!allowed && (bp.protectionLevel 9669 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9670 if (isSystemApp(pkg)) { 9671 // For updated system applications, a system permission 9672 // is granted only if it had been defined by the original application. 9673 if (pkg.isUpdatedSystemApp()) { 9674 final PackageSetting sysPs = mSettings 9675 .getDisabledSystemPkgLPr(pkg.packageName); 9676 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9677 // If the original was granted this permission, we take 9678 // that grant decision as read and propagate it to the 9679 // update. 9680 if (sysPs.isPrivileged()) { 9681 allowed = true; 9682 } 9683 } else { 9684 // The system apk may have been updated with an older 9685 // version of the one on the data partition, but which 9686 // granted a new system permission that it didn't have 9687 // before. In this case we do want to allow the app to 9688 // now get the new permission if the ancestral apk is 9689 // privileged to get it. 9690 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9691 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9692 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9693 allowed = true; 9694 break; 9695 } 9696 } 9697 } 9698 // Also if a privileged parent package on the system image or any of 9699 // its children requested a privileged permission, the updated child 9700 // packages can also get the permission. 9701 if (pkg.parentPackage != null) { 9702 final PackageSetting disabledSysParentPs = mSettings 9703 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9704 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9705 && disabledSysParentPs.isPrivileged()) { 9706 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9707 allowed = true; 9708 } else if (disabledSysParentPs.pkg.childPackages != null) { 9709 final int count = disabledSysParentPs.pkg.childPackages.size(); 9710 for (int i = 0; i < count; i++) { 9711 PackageParser.Package disabledSysChildPkg = 9712 disabledSysParentPs.pkg.childPackages.get(i); 9713 if (isPackageRequestingPermission(disabledSysChildPkg, 9714 perm)) { 9715 allowed = true; 9716 break; 9717 } 9718 } 9719 } 9720 } 9721 } 9722 } 9723 } else { 9724 allowed = isPrivilegedApp(pkg); 9725 } 9726 } 9727 } 9728 if (!allowed) { 9729 if (!allowed && (bp.protectionLevel 9730 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9731 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9732 // If this was a previously normal/dangerous permission that got moved 9733 // to a system permission as part of the runtime permission redesign, then 9734 // we still want to blindly grant it to old apps. 9735 allowed = true; 9736 } 9737 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9738 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9739 // If this permission is to be granted to the system installer and 9740 // this app is an installer, then it gets the permission. 9741 allowed = true; 9742 } 9743 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9744 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9745 // If this permission is to be granted to the system verifier and 9746 // this app is a verifier, then it gets the permission. 9747 allowed = true; 9748 } 9749 if (!allowed && (bp.protectionLevel 9750 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9751 && isSystemApp(pkg)) { 9752 // Any pre-installed system app is allowed to get this permission. 9753 allowed = true; 9754 } 9755 if (!allowed && (bp.protectionLevel 9756 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9757 // For development permissions, a development permission 9758 // is granted only if it was already granted. 9759 allowed = origPermissions.hasInstallPermission(perm); 9760 } 9761 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9762 && pkg.packageName.equals(mSetupWizardPackage)) { 9763 // If this permission is to be granted to the system setup wizard and 9764 // this app is a setup wizard, then it gets the permission. 9765 allowed = true; 9766 } 9767 } 9768 return allowed; 9769 } 9770 9771 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9772 final int permCount = pkg.requestedPermissions.size(); 9773 for (int j = 0; j < permCount; j++) { 9774 String requestedPermission = pkg.requestedPermissions.get(j); 9775 if (permission.equals(requestedPermission)) { 9776 return true; 9777 } 9778 } 9779 return false; 9780 } 9781 9782 final class ActivityIntentResolver 9783 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9784 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9785 boolean defaultOnly, int userId) { 9786 if (!sUserManager.exists(userId)) return null; 9787 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9788 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9789 } 9790 9791 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9792 int userId) { 9793 if (!sUserManager.exists(userId)) return null; 9794 mFlags = flags; 9795 return super.queryIntent(intent, resolvedType, 9796 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9797 } 9798 9799 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9800 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9801 if (!sUserManager.exists(userId)) return null; 9802 if (packageActivities == null) { 9803 return null; 9804 } 9805 mFlags = flags; 9806 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9807 final int N = packageActivities.size(); 9808 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9809 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9810 9811 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9812 for (int i = 0; i < N; ++i) { 9813 intentFilters = packageActivities.get(i).intents; 9814 if (intentFilters != null && intentFilters.size() > 0) { 9815 PackageParser.ActivityIntentInfo[] array = 9816 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9817 intentFilters.toArray(array); 9818 listCut.add(array); 9819 } 9820 } 9821 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9822 } 9823 9824 /** 9825 * Finds a privileged activity that matches the specified activity names. 9826 */ 9827 private PackageParser.Activity findMatchingActivity( 9828 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9829 for (PackageParser.Activity sysActivity : activityList) { 9830 if (sysActivity.info.name.equals(activityInfo.name)) { 9831 return sysActivity; 9832 } 9833 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9834 return sysActivity; 9835 } 9836 if (sysActivity.info.targetActivity != null) { 9837 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9838 return sysActivity; 9839 } 9840 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9841 return sysActivity; 9842 } 9843 } 9844 } 9845 return null; 9846 } 9847 9848 public class IterGenerator<E> { 9849 public Iterator<E> generate(ActivityIntentInfo info) { 9850 return null; 9851 } 9852 } 9853 9854 public class ActionIterGenerator extends IterGenerator<String> { 9855 @Override 9856 public Iterator<String> generate(ActivityIntentInfo info) { 9857 return info.actionsIterator(); 9858 } 9859 } 9860 9861 public class CategoriesIterGenerator extends IterGenerator<String> { 9862 @Override 9863 public Iterator<String> generate(ActivityIntentInfo info) { 9864 return info.categoriesIterator(); 9865 } 9866 } 9867 9868 public class SchemesIterGenerator extends IterGenerator<String> { 9869 @Override 9870 public Iterator<String> generate(ActivityIntentInfo info) { 9871 return info.schemesIterator(); 9872 } 9873 } 9874 9875 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9876 @Override 9877 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9878 return info.authoritiesIterator(); 9879 } 9880 } 9881 9882 /** 9883 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9884 * MODIFIED. Do not pass in a list that should not be changed. 9885 */ 9886 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9887 IterGenerator<T> generator, Iterator<T> searchIterator) { 9888 // loop through the set of actions; every one must be found in the intent filter 9889 while (searchIterator.hasNext()) { 9890 // we must have at least one filter in the list to consider a match 9891 if (intentList.size() == 0) { 9892 break; 9893 } 9894 9895 final T searchAction = searchIterator.next(); 9896 9897 // loop through the set of intent filters 9898 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9899 while (intentIter.hasNext()) { 9900 final ActivityIntentInfo intentInfo = intentIter.next(); 9901 boolean selectionFound = false; 9902 9903 // loop through the intent filter's selection criteria; at least one 9904 // of them must match the searched criteria 9905 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9906 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9907 final T intentSelection = intentSelectionIter.next(); 9908 if (intentSelection != null && intentSelection.equals(searchAction)) { 9909 selectionFound = true; 9910 break; 9911 } 9912 } 9913 9914 // the selection criteria wasn't found in this filter's set; this filter 9915 // is not a potential match 9916 if (!selectionFound) { 9917 intentIter.remove(); 9918 } 9919 } 9920 } 9921 } 9922 9923 private boolean isProtectedAction(ActivityIntentInfo filter) { 9924 final Iterator<String> actionsIter = filter.actionsIterator(); 9925 while (actionsIter != null && actionsIter.hasNext()) { 9926 final String filterAction = actionsIter.next(); 9927 if (PROTECTED_ACTIONS.contains(filterAction)) { 9928 return true; 9929 } 9930 } 9931 return false; 9932 } 9933 9934 /** 9935 * Adjusts the priority of the given intent filter according to policy. 9936 * <p> 9937 * <ul> 9938 * <li>The priority for non privileged applications is capped to '0'</li> 9939 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 9940 * <li>The priority for unbundled updates to privileged applications is capped to the 9941 * priority defined on the system partition</li> 9942 * </ul> 9943 * <p> 9944 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 9945 * allowed to obtain any priority on any action. 9946 */ 9947 private void adjustPriority( 9948 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 9949 // nothing to do; priority is fine as-is 9950 if (intent.getPriority() <= 0) { 9951 return; 9952 } 9953 9954 final ActivityInfo activityInfo = intent.activity.info; 9955 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 9956 9957 final boolean privilegedApp = 9958 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 9959 if (!privilegedApp) { 9960 // non-privileged applications can never define a priority >0 9961 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 9962 + " package: " + applicationInfo.packageName 9963 + " activity: " + intent.activity.className 9964 + " origPrio: " + intent.getPriority()); 9965 intent.setPriority(0); 9966 return; 9967 } 9968 9969 if (systemActivities == null) { 9970 // the system package is not disabled; we're parsing the system partition 9971 if (isProtectedAction(intent)) { 9972 if (mDeferProtectedFilters) { 9973 // We can't deal with these just yet. No component should ever obtain a 9974 // >0 priority for a protected actions, with ONE exception -- the setup 9975 // wizard. The setup wizard, however, cannot be known until we're able to 9976 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 9977 // until all intent filters have been processed. Chicken, meet egg. 9978 // Let the filter temporarily have a high priority and rectify the 9979 // priorities after all system packages have been scanned. 9980 mProtectedFilters.add(intent); 9981 if (DEBUG_FILTERS) { 9982 Slog.i(TAG, "Protected action; save for later;" 9983 + " package: " + applicationInfo.packageName 9984 + " activity: " + intent.activity.className 9985 + " origPrio: " + intent.getPriority()); 9986 } 9987 return; 9988 } else { 9989 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 9990 Slog.i(TAG, "No setup wizard;" 9991 + " All protected intents capped to priority 0"); 9992 } 9993 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 9994 if (DEBUG_FILTERS) { 9995 Slog.i(TAG, "Found setup wizard;" 9996 + " allow priority " + intent.getPriority() + ";" 9997 + " package: " + intent.activity.info.packageName 9998 + " activity: " + intent.activity.className 9999 + " priority: " + intent.getPriority()); 10000 } 10001 // setup wizard gets whatever it wants 10002 return; 10003 } 10004 Slog.w(TAG, "Protected action; cap priority to 0;" 10005 + " package: " + intent.activity.info.packageName 10006 + " activity: " + intent.activity.className 10007 + " origPrio: " + intent.getPriority()); 10008 intent.setPriority(0); 10009 return; 10010 } 10011 } 10012 // privileged apps on the system image get whatever priority they request 10013 return; 10014 } 10015 10016 // privileged app unbundled update ... try to find the same activity 10017 final PackageParser.Activity foundActivity = 10018 findMatchingActivity(systemActivities, activityInfo); 10019 if (foundActivity == null) { 10020 // this is a new activity; it cannot obtain >0 priority 10021 if (DEBUG_FILTERS) { 10022 Slog.i(TAG, "New activity; cap priority to 0;" 10023 + " package: " + applicationInfo.packageName 10024 + " activity: " + intent.activity.className 10025 + " origPrio: " + intent.getPriority()); 10026 } 10027 intent.setPriority(0); 10028 return; 10029 } 10030 10031 // found activity, now check for filter equivalence 10032 10033 // a shallow copy is enough; we modify the list, not its contents 10034 final List<ActivityIntentInfo> intentListCopy = 10035 new ArrayList<>(foundActivity.intents); 10036 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10037 10038 // find matching action subsets 10039 final Iterator<String> actionsIterator = intent.actionsIterator(); 10040 if (actionsIterator != null) { 10041 getIntentListSubset( 10042 intentListCopy, new ActionIterGenerator(), actionsIterator); 10043 if (intentListCopy.size() == 0) { 10044 // no more intents to match; we're not equivalent 10045 if (DEBUG_FILTERS) { 10046 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10047 + " package: " + applicationInfo.packageName 10048 + " activity: " + intent.activity.className 10049 + " origPrio: " + intent.getPriority()); 10050 } 10051 intent.setPriority(0); 10052 return; 10053 } 10054 } 10055 10056 // find matching category subsets 10057 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10058 if (categoriesIterator != null) { 10059 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10060 categoriesIterator); 10061 if (intentListCopy.size() == 0) { 10062 // no more intents to match; we're not equivalent 10063 if (DEBUG_FILTERS) { 10064 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10065 + " package: " + applicationInfo.packageName 10066 + " activity: " + intent.activity.className 10067 + " origPrio: " + intent.getPriority()); 10068 } 10069 intent.setPriority(0); 10070 return; 10071 } 10072 } 10073 10074 // find matching schemes subsets 10075 final Iterator<String> schemesIterator = intent.schemesIterator(); 10076 if (schemesIterator != null) { 10077 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10078 schemesIterator); 10079 if (intentListCopy.size() == 0) { 10080 // no more intents to match; we're not equivalent 10081 if (DEBUG_FILTERS) { 10082 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10083 + " package: " + applicationInfo.packageName 10084 + " activity: " + intent.activity.className 10085 + " origPrio: " + intent.getPriority()); 10086 } 10087 intent.setPriority(0); 10088 return; 10089 } 10090 } 10091 10092 // find matching authorities subsets 10093 final Iterator<IntentFilter.AuthorityEntry> 10094 authoritiesIterator = intent.authoritiesIterator(); 10095 if (authoritiesIterator != null) { 10096 getIntentListSubset(intentListCopy, 10097 new AuthoritiesIterGenerator(), 10098 authoritiesIterator); 10099 if (intentListCopy.size() == 0) { 10100 // no more intents to match; we're not equivalent 10101 if (DEBUG_FILTERS) { 10102 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10103 + " package: " + applicationInfo.packageName 10104 + " activity: " + intent.activity.className 10105 + " origPrio: " + intent.getPriority()); 10106 } 10107 intent.setPriority(0); 10108 return; 10109 } 10110 } 10111 10112 // we found matching filter(s); app gets the max priority of all intents 10113 int cappedPriority = 0; 10114 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10115 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10116 } 10117 if (intent.getPriority() > cappedPriority) { 10118 if (DEBUG_FILTERS) { 10119 Slog.i(TAG, "Found matching filter(s);" 10120 + " cap priority to " + cappedPriority + ";" 10121 + " package: " + applicationInfo.packageName 10122 + " activity: " + intent.activity.className 10123 + " origPrio: " + intent.getPriority()); 10124 } 10125 intent.setPriority(cappedPriority); 10126 return; 10127 } 10128 // all this for nothing; the requested priority was <= what was on the system 10129 } 10130 10131 public final void addActivity(PackageParser.Activity a, String type) { 10132 mActivities.put(a.getComponentName(), a); 10133 if (DEBUG_SHOW_INFO) 10134 Log.v( 10135 TAG, " " + type + " " + 10136 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10137 if (DEBUG_SHOW_INFO) 10138 Log.v(TAG, " Class=" + a.info.name); 10139 final int NI = a.intents.size(); 10140 for (int j=0; j<NI; j++) { 10141 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10142 if ("activity".equals(type)) { 10143 final PackageSetting ps = 10144 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10145 final List<PackageParser.Activity> systemActivities = 10146 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10147 adjustPriority(systemActivities, intent); 10148 } 10149 if (DEBUG_SHOW_INFO) { 10150 Log.v(TAG, " IntentFilter:"); 10151 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10152 } 10153 if (!intent.debugCheck()) { 10154 Log.w(TAG, "==> For Activity " + a.info.name); 10155 } 10156 addFilter(intent); 10157 } 10158 } 10159 10160 public final void removeActivity(PackageParser.Activity a, String type) { 10161 mActivities.remove(a.getComponentName()); 10162 if (DEBUG_SHOW_INFO) { 10163 Log.v(TAG, " " + type + " " 10164 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10165 : a.info.name) + ":"); 10166 Log.v(TAG, " Class=" + a.info.name); 10167 } 10168 final int NI = a.intents.size(); 10169 for (int j=0; j<NI; j++) { 10170 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10171 if (DEBUG_SHOW_INFO) { 10172 Log.v(TAG, " IntentFilter:"); 10173 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10174 } 10175 removeFilter(intent); 10176 } 10177 } 10178 10179 @Override 10180 protected boolean allowFilterResult( 10181 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10182 ActivityInfo filterAi = filter.activity.info; 10183 for (int i=dest.size()-1; i>=0; i--) { 10184 ActivityInfo destAi = dest.get(i).activityInfo; 10185 if (destAi.name == filterAi.name 10186 && destAi.packageName == filterAi.packageName) { 10187 return false; 10188 } 10189 } 10190 return true; 10191 } 10192 10193 @Override 10194 protected ActivityIntentInfo[] newArray(int size) { 10195 return new ActivityIntentInfo[size]; 10196 } 10197 10198 @Override 10199 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10200 if (!sUserManager.exists(userId)) return true; 10201 PackageParser.Package p = filter.activity.owner; 10202 if (p != null) { 10203 PackageSetting ps = (PackageSetting)p.mExtras; 10204 if (ps != null) { 10205 // System apps are never considered stopped for purposes of 10206 // filtering, because there may be no way for the user to 10207 // actually re-launch them. 10208 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10209 && ps.getStopped(userId); 10210 } 10211 } 10212 return false; 10213 } 10214 10215 @Override 10216 protected boolean isPackageForFilter(String packageName, 10217 PackageParser.ActivityIntentInfo info) { 10218 return packageName.equals(info.activity.owner.packageName); 10219 } 10220 10221 @Override 10222 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10223 int match, int userId) { 10224 if (!sUserManager.exists(userId)) return null; 10225 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10226 return null; 10227 } 10228 final PackageParser.Activity activity = info.activity; 10229 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10230 if (ps == null) { 10231 return null; 10232 } 10233 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10234 ps.readUserState(userId), userId); 10235 if (ai == null) { 10236 return null; 10237 } 10238 final ResolveInfo res = new ResolveInfo(); 10239 res.activityInfo = ai; 10240 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10241 res.filter = info; 10242 } 10243 if (info != null) { 10244 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10245 } 10246 res.priority = info.getPriority(); 10247 res.preferredOrder = activity.owner.mPreferredOrder; 10248 //System.out.println("Result: " + res.activityInfo.className + 10249 // " = " + res.priority); 10250 res.match = match; 10251 res.isDefault = info.hasDefault; 10252 res.labelRes = info.labelRes; 10253 res.nonLocalizedLabel = info.nonLocalizedLabel; 10254 if (userNeedsBadging(userId)) { 10255 res.noResourceId = true; 10256 } else { 10257 res.icon = info.icon; 10258 } 10259 res.iconResourceId = info.icon; 10260 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10261 return res; 10262 } 10263 10264 @Override 10265 protected void sortResults(List<ResolveInfo> results) { 10266 Collections.sort(results, mResolvePrioritySorter); 10267 } 10268 10269 @Override 10270 protected void dumpFilter(PrintWriter out, String prefix, 10271 PackageParser.ActivityIntentInfo filter) { 10272 out.print(prefix); out.print( 10273 Integer.toHexString(System.identityHashCode(filter.activity))); 10274 out.print(' '); 10275 filter.activity.printComponentShortName(out); 10276 out.print(" filter "); 10277 out.println(Integer.toHexString(System.identityHashCode(filter))); 10278 } 10279 10280 @Override 10281 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10282 return filter.activity; 10283 } 10284 10285 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10286 PackageParser.Activity activity = (PackageParser.Activity)label; 10287 out.print(prefix); out.print( 10288 Integer.toHexString(System.identityHashCode(activity))); 10289 out.print(' '); 10290 activity.printComponentShortName(out); 10291 if (count > 1) { 10292 out.print(" ("); out.print(count); out.print(" filters)"); 10293 } 10294 out.println(); 10295 } 10296 10297 // Keys are String (activity class name), values are Activity. 10298 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10299 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10300 private int mFlags; 10301 } 10302 10303 private final class ServiceIntentResolver 10304 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10305 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10306 boolean defaultOnly, int userId) { 10307 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10308 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10309 } 10310 10311 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10312 int userId) { 10313 if (!sUserManager.exists(userId)) return null; 10314 mFlags = flags; 10315 return super.queryIntent(intent, resolvedType, 10316 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10317 } 10318 10319 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10320 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10321 if (!sUserManager.exists(userId)) return null; 10322 if (packageServices == null) { 10323 return null; 10324 } 10325 mFlags = flags; 10326 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10327 final int N = packageServices.size(); 10328 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10329 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10330 10331 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10332 for (int i = 0; i < N; ++i) { 10333 intentFilters = packageServices.get(i).intents; 10334 if (intentFilters != null && intentFilters.size() > 0) { 10335 PackageParser.ServiceIntentInfo[] array = 10336 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10337 intentFilters.toArray(array); 10338 listCut.add(array); 10339 } 10340 } 10341 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10342 } 10343 10344 public final void addService(PackageParser.Service s) { 10345 mServices.put(s.getComponentName(), s); 10346 if (DEBUG_SHOW_INFO) { 10347 Log.v(TAG, " " 10348 + (s.info.nonLocalizedLabel != null 10349 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10350 Log.v(TAG, " Class=" + s.info.name); 10351 } 10352 final int NI = s.intents.size(); 10353 int j; 10354 for (j=0; j<NI; j++) { 10355 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10356 if (DEBUG_SHOW_INFO) { 10357 Log.v(TAG, " IntentFilter:"); 10358 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10359 } 10360 if (!intent.debugCheck()) { 10361 Log.w(TAG, "==> For Service " + s.info.name); 10362 } 10363 addFilter(intent); 10364 } 10365 } 10366 10367 public final void removeService(PackageParser.Service s) { 10368 mServices.remove(s.getComponentName()); 10369 if (DEBUG_SHOW_INFO) { 10370 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10371 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10372 Log.v(TAG, " Class=" + s.info.name); 10373 } 10374 final int NI = s.intents.size(); 10375 int j; 10376 for (j=0; j<NI; j++) { 10377 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10378 if (DEBUG_SHOW_INFO) { 10379 Log.v(TAG, " IntentFilter:"); 10380 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10381 } 10382 removeFilter(intent); 10383 } 10384 } 10385 10386 @Override 10387 protected boolean allowFilterResult( 10388 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10389 ServiceInfo filterSi = filter.service.info; 10390 for (int i=dest.size()-1; i>=0; i--) { 10391 ServiceInfo destAi = dest.get(i).serviceInfo; 10392 if (destAi.name == filterSi.name 10393 && destAi.packageName == filterSi.packageName) { 10394 return false; 10395 } 10396 } 10397 return true; 10398 } 10399 10400 @Override 10401 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10402 return new PackageParser.ServiceIntentInfo[size]; 10403 } 10404 10405 @Override 10406 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10407 if (!sUserManager.exists(userId)) return true; 10408 PackageParser.Package p = filter.service.owner; 10409 if (p != null) { 10410 PackageSetting ps = (PackageSetting)p.mExtras; 10411 if (ps != null) { 10412 // System apps are never considered stopped for purposes of 10413 // filtering, because there may be no way for the user to 10414 // actually re-launch them. 10415 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10416 && ps.getStopped(userId); 10417 } 10418 } 10419 return false; 10420 } 10421 10422 @Override 10423 protected boolean isPackageForFilter(String packageName, 10424 PackageParser.ServiceIntentInfo info) { 10425 return packageName.equals(info.service.owner.packageName); 10426 } 10427 10428 @Override 10429 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10430 int match, int userId) { 10431 if (!sUserManager.exists(userId)) return null; 10432 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10433 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10434 return null; 10435 } 10436 final PackageParser.Service service = info.service; 10437 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10438 if (ps == null) { 10439 return null; 10440 } 10441 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10442 ps.readUserState(userId), userId); 10443 if (si == null) { 10444 return null; 10445 } 10446 final ResolveInfo res = new ResolveInfo(); 10447 res.serviceInfo = si; 10448 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10449 res.filter = filter; 10450 } 10451 res.priority = info.getPriority(); 10452 res.preferredOrder = service.owner.mPreferredOrder; 10453 res.match = match; 10454 res.isDefault = info.hasDefault; 10455 res.labelRes = info.labelRes; 10456 res.nonLocalizedLabel = info.nonLocalizedLabel; 10457 res.icon = info.icon; 10458 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10459 return res; 10460 } 10461 10462 @Override 10463 protected void sortResults(List<ResolveInfo> results) { 10464 Collections.sort(results, mResolvePrioritySorter); 10465 } 10466 10467 @Override 10468 protected void dumpFilter(PrintWriter out, String prefix, 10469 PackageParser.ServiceIntentInfo filter) { 10470 out.print(prefix); out.print( 10471 Integer.toHexString(System.identityHashCode(filter.service))); 10472 out.print(' '); 10473 filter.service.printComponentShortName(out); 10474 out.print(" filter "); 10475 out.println(Integer.toHexString(System.identityHashCode(filter))); 10476 } 10477 10478 @Override 10479 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10480 return filter.service; 10481 } 10482 10483 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10484 PackageParser.Service service = (PackageParser.Service)label; 10485 out.print(prefix); out.print( 10486 Integer.toHexString(System.identityHashCode(service))); 10487 out.print(' '); 10488 service.printComponentShortName(out); 10489 if (count > 1) { 10490 out.print(" ("); out.print(count); out.print(" filters)"); 10491 } 10492 out.println(); 10493 } 10494 10495// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10496// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10497// final List<ResolveInfo> retList = Lists.newArrayList(); 10498// while (i.hasNext()) { 10499// final ResolveInfo resolveInfo = (ResolveInfo) i; 10500// if (isEnabledLP(resolveInfo.serviceInfo)) { 10501// retList.add(resolveInfo); 10502// } 10503// } 10504// return retList; 10505// } 10506 10507 // Keys are String (activity class name), values are Activity. 10508 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10509 = new ArrayMap<ComponentName, PackageParser.Service>(); 10510 private int mFlags; 10511 }; 10512 10513 private final class ProviderIntentResolver 10514 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10515 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10516 boolean defaultOnly, int userId) { 10517 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10518 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10519 } 10520 10521 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10522 int userId) { 10523 if (!sUserManager.exists(userId)) 10524 return null; 10525 mFlags = flags; 10526 return super.queryIntent(intent, resolvedType, 10527 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10528 } 10529 10530 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10531 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10532 if (!sUserManager.exists(userId)) 10533 return null; 10534 if (packageProviders == null) { 10535 return null; 10536 } 10537 mFlags = flags; 10538 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10539 final int N = packageProviders.size(); 10540 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10541 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10542 10543 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10544 for (int i = 0; i < N; ++i) { 10545 intentFilters = packageProviders.get(i).intents; 10546 if (intentFilters != null && intentFilters.size() > 0) { 10547 PackageParser.ProviderIntentInfo[] array = 10548 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10549 intentFilters.toArray(array); 10550 listCut.add(array); 10551 } 10552 } 10553 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10554 } 10555 10556 public final void addProvider(PackageParser.Provider p) { 10557 if (mProviders.containsKey(p.getComponentName())) { 10558 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10559 return; 10560 } 10561 10562 mProviders.put(p.getComponentName(), p); 10563 if (DEBUG_SHOW_INFO) { 10564 Log.v(TAG, " " 10565 + (p.info.nonLocalizedLabel != null 10566 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10567 Log.v(TAG, " Class=" + p.info.name); 10568 } 10569 final int NI = p.intents.size(); 10570 int j; 10571 for (j = 0; j < NI; j++) { 10572 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10573 if (DEBUG_SHOW_INFO) { 10574 Log.v(TAG, " IntentFilter:"); 10575 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10576 } 10577 if (!intent.debugCheck()) { 10578 Log.w(TAG, "==> For Provider " + p.info.name); 10579 } 10580 addFilter(intent); 10581 } 10582 } 10583 10584 public final void removeProvider(PackageParser.Provider p) { 10585 mProviders.remove(p.getComponentName()); 10586 if (DEBUG_SHOW_INFO) { 10587 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10588 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10589 Log.v(TAG, " Class=" + p.info.name); 10590 } 10591 final int NI = p.intents.size(); 10592 int j; 10593 for (j = 0; j < NI; j++) { 10594 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10595 if (DEBUG_SHOW_INFO) { 10596 Log.v(TAG, " IntentFilter:"); 10597 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10598 } 10599 removeFilter(intent); 10600 } 10601 } 10602 10603 @Override 10604 protected boolean allowFilterResult( 10605 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10606 ProviderInfo filterPi = filter.provider.info; 10607 for (int i = dest.size() - 1; i >= 0; i--) { 10608 ProviderInfo destPi = dest.get(i).providerInfo; 10609 if (destPi.name == filterPi.name 10610 && destPi.packageName == filterPi.packageName) { 10611 return false; 10612 } 10613 } 10614 return true; 10615 } 10616 10617 @Override 10618 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10619 return new PackageParser.ProviderIntentInfo[size]; 10620 } 10621 10622 @Override 10623 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10624 if (!sUserManager.exists(userId)) 10625 return true; 10626 PackageParser.Package p = filter.provider.owner; 10627 if (p != null) { 10628 PackageSetting ps = (PackageSetting) p.mExtras; 10629 if (ps != null) { 10630 // System apps are never considered stopped for purposes of 10631 // filtering, because there may be no way for the user to 10632 // actually re-launch them. 10633 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10634 && ps.getStopped(userId); 10635 } 10636 } 10637 return false; 10638 } 10639 10640 @Override 10641 protected boolean isPackageForFilter(String packageName, 10642 PackageParser.ProviderIntentInfo info) { 10643 return packageName.equals(info.provider.owner.packageName); 10644 } 10645 10646 @Override 10647 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10648 int match, int userId) { 10649 if (!sUserManager.exists(userId)) 10650 return null; 10651 final PackageParser.ProviderIntentInfo info = filter; 10652 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10653 return null; 10654 } 10655 final PackageParser.Provider provider = info.provider; 10656 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10657 if (ps == null) { 10658 return null; 10659 } 10660 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10661 ps.readUserState(userId), userId); 10662 if (pi == null) { 10663 return null; 10664 } 10665 final ResolveInfo res = new ResolveInfo(); 10666 res.providerInfo = pi; 10667 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10668 res.filter = filter; 10669 } 10670 res.priority = info.getPriority(); 10671 res.preferredOrder = provider.owner.mPreferredOrder; 10672 res.match = match; 10673 res.isDefault = info.hasDefault; 10674 res.labelRes = info.labelRes; 10675 res.nonLocalizedLabel = info.nonLocalizedLabel; 10676 res.icon = info.icon; 10677 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10678 return res; 10679 } 10680 10681 @Override 10682 protected void sortResults(List<ResolveInfo> results) { 10683 Collections.sort(results, mResolvePrioritySorter); 10684 } 10685 10686 @Override 10687 protected void dumpFilter(PrintWriter out, String prefix, 10688 PackageParser.ProviderIntentInfo filter) { 10689 out.print(prefix); 10690 out.print( 10691 Integer.toHexString(System.identityHashCode(filter.provider))); 10692 out.print(' '); 10693 filter.provider.printComponentShortName(out); 10694 out.print(" filter "); 10695 out.println(Integer.toHexString(System.identityHashCode(filter))); 10696 } 10697 10698 @Override 10699 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10700 return filter.provider; 10701 } 10702 10703 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10704 PackageParser.Provider provider = (PackageParser.Provider)label; 10705 out.print(prefix); out.print( 10706 Integer.toHexString(System.identityHashCode(provider))); 10707 out.print(' '); 10708 provider.printComponentShortName(out); 10709 if (count > 1) { 10710 out.print(" ("); out.print(count); out.print(" filters)"); 10711 } 10712 out.println(); 10713 } 10714 10715 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10716 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10717 private int mFlags; 10718 } 10719 10720 private static final class EphemeralIntentResolver 10721 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10722 @Override 10723 protected EphemeralResolveIntentInfo[] newArray(int size) { 10724 return new EphemeralResolveIntentInfo[size]; 10725 } 10726 10727 @Override 10728 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10729 return true; 10730 } 10731 10732 @Override 10733 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10734 int userId) { 10735 if (!sUserManager.exists(userId)) { 10736 return null; 10737 } 10738 return info.getEphemeralResolveInfo(); 10739 } 10740 } 10741 10742 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10743 new Comparator<ResolveInfo>() { 10744 public int compare(ResolveInfo r1, ResolveInfo r2) { 10745 int v1 = r1.priority; 10746 int v2 = r2.priority; 10747 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10748 if (v1 != v2) { 10749 return (v1 > v2) ? -1 : 1; 10750 } 10751 v1 = r1.preferredOrder; 10752 v2 = r2.preferredOrder; 10753 if (v1 != v2) { 10754 return (v1 > v2) ? -1 : 1; 10755 } 10756 if (r1.isDefault != r2.isDefault) { 10757 return r1.isDefault ? -1 : 1; 10758 } 10759 v1 = r1.match; 10760 v2 = r2.match; 10761 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10762 if (v1 != v2) { 10763 return (v1 > v2) ? -1 : 1; 10764 } 10765 if (r1.system != r2.system) { 10766 return r1.system ? -1 : 1; 10767 } 10768 if (r1.activityInfo != null) { 10769 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10770 } 10771 if (r1.serviceInfo != null) { 10772 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10773 } 10774 if (r1.providerInfo != null) { 10775 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10776 } 10777 return 0; 10778 } 10779 }; 10780 10781 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10782 new Comparator<ProviderInfo>() { 10783 public int compare(ProviderInfo p1, ProviderInfo p2) { 10784 final int v1 = p1.initOrder; 10785 final int v2 = p2.initOrder; 10786 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10787 } 10788 }; 10789 10790 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10791 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10792 final int[] userIds) { 10793 mHandler.post(new Runnable() { 10794 @Override 10795 public void run() { 10796 try { 10797 final IActivityManager am = ActivityManagerNative.getDefault(); 10798 if (am == null) return; 10799 final int[] resolvedUserIds; 10800 if (userIds == null) { 10801 resolvedUserIds = am.getRunningUserIds(); 10802 } else { 10803 resolvedUserIds = userIds; 10804 } 10805 for (int id : resolvedUserIds) { 10806 final Intent intent = new Intent(action, 10807 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10808 if (extras != null) { 10809 intent.putExtras(extras); 10810 } 10811 if (targetPkg != null) { 10812 intent.setPackage(targetPkg); 10813 } 10814 // Modify the UID when posting to other users 10815 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10816 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10817 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10818 intent.putExtra(Intent.EXTRA_UID, uid); 10819 } 10820 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10821 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10822 if (DEBUG_BROADCASTS) { 10823 RuntimeException here = new RuntimeException("here"); 10824 here.fillInStackTrace(); 10825 Slog.d(TAG, "Sending to user " + id + ": " 10826 + intent.toShortString(false, true, false, false) 10827 + " " + intent.getExtras(), here); 10828 } 10829 am.broadcastIntent(null, intent, null, finishedReceiver, 10830 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10831 null, finishedReceiver != null, false, id); 10832 } 10833 } catch (RemoteException ex) { 10834 } 10835 } 10836 }); 10837 } 10838 10839 /** 10840 * Check if the external storage media is available. This is true if there 10841 * is a mounted external storage medium or if the external storage is 10842 * emulated. 10843 */ 10844 private boolean isExternalMediaAvailable() { 10845 return mMediaMounted || Environment.isExternalStorageEmulated(); 10846 } 10847 10848 @Override 10849 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10850 // writer 10851 synchronized (mPackages) { 10852 if (!isExternalMediaAvailable()) { 10853 // If the external storage is no longer mounted at this point, 10854 // the caller may not have been able to delete all of this 10855 // packages files and can not delete any more. Bail. 10856 return null; 10857 } 10858 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10859 if (lastPackage != null) { 10860 pkgs.remove(lastPackage); 10861 } 10862 if (pkgs.size() > 0) { 10863 return pkgs.get(0); 10864 } 10865 } 10866 return null; 10867 } 10868 10869 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10870 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10871 userId, andCode ? 1 : 0, packageName); 10872 if (mSystemReady) { 10873 msg.sendToTarget(); 10874 } else { 10875 if (mPostSystemReadyMessages == null) { 10876 mPostSystemReadyMessages = new ArrayList<>(); 10877 } 10878 mPostSystemReadyMessages.add(msg); 10879 } 10880 } 10881 10882 void startCleaningPackages() { 10883 // reader 10884 if (!isExternalMediaAvailable()) { 10885 return; 10886 } 10887 synchronized (mPackages) { 10888 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10889 return; 10890 } 10891 } 10892 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10893 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10894 IActivityManager am = ActivityManagerNative.getDefault(); 10895 if (am != null) { 10896 try { 10897 am.startService(null, intent, null, mContext.getOpPackageName(), 10898 UserHandle.USER_SYSTEM); 10899 } catch (RemoteException e) { 10900 } 10901 } 10902 } 10903 10904 @Override 10905 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10906 int installFlags, String installerPackageName, int userId) { 10907 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10908 10909 final int callingUid = Binder.getCallingUid(); 10910 enforceCrossUserPermission(callingUid, userId, 10911 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10912 10913 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10914 try { 10915 if (observer != null) { 10916 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10917 } 10918 } catch (RemoteException re) { 10919 } 10920 return; 10921 } 10922 10923 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10924 installFlags |= PackageManager.INSTALL_FROM_ADB; 10925 10926 } else { 10927 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10928 // about installerPackageName. 10929 10930 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10931 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10932 } 10933 10934 UserHandle user; 10935 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10936 user = UserHandle.ALL; 10937 } else { 10938 user = new UserHandle(userId); 10939 } 10940 10941 // Only system components can circumvent runtime permissions when installing. 10942 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10943 && mContext.checkCallingOrSelfPermission(Manifest.permission 10944 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10945 throw new SecurityException("You need the " 10946 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10947 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10948 } 10949 10950 final File originFile = new File(originPath); 10951 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10952 10953 final Message msg = mHandler.obtainMessage(INIT_COPY); 10954 final VerificationInfo verificationInfo = new VerificationInfo( 10955 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10956 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10957 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10958 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10959 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10960 msg.obj = params; 10961 10962 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10963 System.identityHashCode(msg.obj)); 10964 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10965 System.identityHashCode(msg.obj)); 10966 10967 mHandler.sendMessage(msg); 10968 } 10969 10970 void installStage(String packageName, File stagedDir, String stagedCid, 10971 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10972 String installerPackageName, int installerUid, UserHandle user) { 10973 if (DEBUG_EPHEMERAL) { 10974 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10975 Slog.d(TAG, "Ephemeral install of " + packageName); 10976 } 10977 } 10978 final VerificationInfo verificationInfo = new VerificationInfo( 10979 sessionParams.originatingUri, sessionParams.referrerUri, 10980 sessionParams.originatingUid, installerUid); 10981 10982 final OriginInfo origin; 10983 if (stagedDir != null) { 10984 origin = OriginInfo.fromStagedFile(stagedDir); 10985 } else { 10986 origin = OriginInfo.fromStagedContainer(stagedCid); 10987 } 10988 10989 final Message msg = mHandler.obtainMessage(INIT_COPY); 10990 final InstallParams params = new InstallParams(origin, null, observer, 10991 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10992 verificationInfo, user, sessionParams.abiOverride, 10993 sessionParams.grantedRuntimePermissions); 10994 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10995 msg.obj = params; 10996 10997 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10998 System.identityHashCode(msg.obj)); 10999 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11000 System.identityHashCode(msg.obj)); 11001 11002 mHandler.sendMessage(msg); 11003 } 11004 11005 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11006 int userId) { 11007 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11008 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11009 } 11010 11011 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11012 int appId, int userId) { 11013 Bundle extras = new Bundle(1); 11014 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11015 11016 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11017 packageName, extras, 0, null, null, new int[] {userId}); 11018 try { 11019 IActivityManager am = ActivityManagerNative.getDefault(); 11020 if (isSystem && am.isUserRunning(userId, 0)) { 11021 // The just-installed/enabled app is bundled on the system, so presumed 11022 // to be able to run automatically without needing an explicit launch. 11023 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11024 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11025 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11026 .setPackage(packageName); 11027 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11028 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11029 } 11030 } catch (RemoteException e) { 11031 // shouldn't happen 11032 Slog.w(TAG, "Unable to bootstrap installed package", e); 11033 } 11034 } 11035 11036 @Override 11037 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11038 int userId) { 11039 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11040 PackageSetting pkgSetting; 11041 final int uid = Binder.getCallingUid(); 11042 enforceCrossUserPermission(uid, userId, 11043 true /* requireFullPermission */, true /* checkShell */, 11044 "setApplicationHiddenSetting for user " + userId); 11045 11046 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11047 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11048 return false; 11049 } 11050 11051 long callingId = Binder.clearCallingIdentity(); 11052 try { 11053 boolean sendAdded = false; 11054 boolean sendRemoved = false; 11055 // writer 11056 synchronized (mPackages) { 11057 pkgSetting = mSettings.mPackages.get(packageName); 11058 if (pkgSetting == null) { 11059 return false; 11060 } 11061 if (pkgSetting.getHidden(userId) != hidden) { 11062 pkgSetting.setHidden(hidden, userId); 11063 mSettings.writePackageRestrictionsLPr(userId); 11064 if (hidden) { 11065 sendRemoved = true; 11066 } else { 11067 sendAdded = true; 11068 } 11069 } 11070 } 11071 if (sendAdded) { 11072 sendPackageAddedForUser(packageName, pkgSetting, userId); 11073 return true; 11074 } 11075 if (sendRemoved) { 11076 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11077 "hiding pkg"); 11078 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11079 return true; 11080 } 11081 } finally { 11082 Binder.restoreCallingIdentity(callingId); 11083 } 11084 return false; 11085 } 11086 11087 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11088 int userId) { 11089 final PackageRemovedInfo info = new PackageRemovedInfo(); 11090 info.removedPackage = packageName; 11091 info.removedUsers = new int[] {userId}; 11092 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11093 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11094 } 11095 11096 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11097 if (pkgList.length > 0) { 11098 Bundle extras = new Bundle(1); 11099 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11100 11101 sendPackageBroadcast( 11102 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11103 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11104 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11105 new int[] {userId}); 11106 } 11107 } 11108 11109 /** 11110 * Returns true if application is not found or there was an error. Otherwise it returns 11111 * the hidden state of the package for the given user. 11112 */ 11113 @Override 11114 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11115 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11116 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11117 true /* requireFullPermission */, false /* checkShell */, 11118 "getApplicationHidden for user " + userId); 11119 PackageSetting pkgSetting; 11120 long callingId = Binder.clearCallingIdentity(); 11121 try { 11122 // writer 11123 synchronized (mPackages) { 11124 pkgSetting = mSettings.mPackages.get(packageName); 11125 if (pkgSetting == null) { 11126 return true; 11127 } 11128 return pkgSetting.getHidden(userId); 11129 } 11130 } finally { 11131 Binder.restoreCallingIdentity(callingId); 11132 } 11133 } 11134 11135 /** 11136 * @hide 11137 */ 11138 @Override 11139 public int installExistingPackageAsUser(String packageName, int userId) { 11140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11141 null); 11142 PackageSetting pkgSetting; 11143 final int uid = Binder.getCallingUid(); 11144 enforceCrossUserPermission(uid, userId, 11145 true /* requireFullPermission */, true /* checkShell */, 11146 "installExistingPackage for user " + userId); 11147 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11148 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11149 } 11150 11151 long callingId = Binder.clearCallingIdentity(); 11152 try { 11153 boolean installed = false; 11154 11155 // writer 11156 synchronized (mPackages) { 11157 pkgSetting = mSettings.mPackages.get(packageName); 11158 if (pkgSetting == null) { 11159 return PackageManager.INSTALL_FAILED_INVALID_URI; 11160 } 11161 if (!pkgSetting.getInstalled(userId)) { 11162 pkgSetting.setInstalled(true, userId); 11163 pkgSetting.setHidden(false, userId); 11164 mSettings.writePackageRestrictionsLPr(userId); 11165 installed = true; 11166 } 11167 } 11168 11169 if (installed) { 11170 if (pkgSetting.pkg != null) { 11171 prepareAppDataAfterInstall(pkgSetting.pkg); 11172 } 11173 sendPackageAddedForUser(packageName, pkgSetting, userId); 11174 } 11175 } finally { 11176 Binder.restoreCallingIdentity(callingId); 11177 } 11178 11179 return PackageManager.INSTALL_SUCCEEDED; 11180 } 11181 11182 boolean isUserRestricted(int userId, String restrictionKey) { 11183 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11184 if (restrictions.getBoolean(restrictionKey, false)) { 11185 Log.w(TAG, "User is restricted: " + restrictionKey); 11186 return true; 11187 } 11188 return false; 11189 } 11190 11191 @Override 11192 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11193 int userId) { 11194 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11195 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11196 true /* requireFullPermission */, true /* checkShell */, 11197 "setPackagesSuspended for user " + userId); 11198 11199 if (ArrayUtils.isEmpty(packageNames)) { 11200 return packageNames; 11201 } 11202 11203 // List of package names for whom the suspended state has changed. 11204 List<String> changedPackages = new ArrayList<>(packageNames.length); 11205 // List of package names for whom the suspended state is not set as requested in this 11206 // method. 11207 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11208 for (int i = 0; i < packageNames.length; i++) { 11209 String packageName = packageNames[i]; 11210 long callingId = Binder.clearCallingIdentity(); 11211 try { 11212 boolean changed = false; 11213 final int appId; 11214 synchronized (mPackages) { 11215 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11216 if (pkgSetting == null) { 11217 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11218 + "\". Skipping suspending/un-suspending."); 11219 unactionedPackages.add(packageName); 11220 continue; 11221 } 11222 appId = pkgSetting.appId; 11223 if (pkgSetting.getSuspended(userId) != suspended) { 11224 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11225 unactionedPackages.add(packageName); 11226 continue; 11227 } 11228 pkgSetting.setSuspended(suspended, userId); 11229 mSettings.writePackageRestrictionsLPr(userId); 11230 changed = true; 11231 changedPackages.add(packageName); 11232 } 11233 } 11234 11235 if (changed && suspended) { 11236 killApplication(packageName, UserHandle.getUid(userId, appId), 11237 "suspending package"); 11238 } 11239 } finally { 11240 Binder.restoreCallingIdentity(callingId); 11241 } 11242 } 11243 11244 if (!changedPackages.isEmpty()) { 11245 sendPackagesSuspendedForUser(changedPackages.toArray( 11246 new String[changedPackages.size()]), userId, suspended); 11247 } 11248 11249 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11250 } 11251 11252 @Override 11253 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11254 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11255 true /* requireFullPermission */, false /* checkShell */, 11256 "isPackageSuspendedForUser for user " + userId); 11257 synchronized (mPackages) { 11258 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11259 if (pkgSetting == null) { 11260 throw new IllegalArgumentException("Unknown target package: " + packageName); 11261 } 11262 return pkgSetting.getSuspended(userId); 11263 } 11264 } 11265 11266 /** 11267 * TODO: cache and disallow blocking the active dialer. 11268 * 11269 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11270 */ 11271 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11272 if (isPackageDeviceAdmin(packageName, userId)) { 11273 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11274 + "\": has an active device admin"); 11275 return false; 11276 } 11277 11278 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11279 if (packageName.equals(activeLauncherPackageName)) { 11280 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11281 + "\": contains the active launcher"); 11282 return false; 11283 } 11284 11285 if (packageName.equals(mRequiredInstallerPackage)) { 11286 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11287 + "\": required for package installation"); 11288 return false; 11289 } 11290 11291 if (packageName.equals(mRequiredVerifierPackage)) { 11292 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11293 + "\": required for package verification"); 11294 return false; 11295 } 11296 11297 final PackageParser.Package pkg = mPackages.get(packageName); 11298 if (pkg != null && isPrivilegedApp(pkg)) { 11299 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11300 + "\": is a privileged app"); 11301 return false; 11302 } 11303 11304 return true; 11305 } 11306 11307 private String getActiveLauncherPackageName(int userId) { 11308 Intent intent = new Intent(Intent.ACTION_MAIN); 11309 intent.addCategory(Intent.CATEGORY_HOME); 11310 ResolveInfo resolveInfo = resolveIntent( 11311 intent, 11312 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11313 PackageManager.MATCH_DEFAULT_ONLY, 11314 userId); 11315 11316 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11317 } 11318 11319 @Override 11320 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11321 mContext.enforceCallingOrSelfPermission( 11322 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11323 "Only package verification agents can verify applications"); 11324 11325 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11326 final PackageVerificationResponse response = new PackageVerificationResponse( 11327 verificationCode, Binder.getCallingUid()); 11328 msg.arg1 = id; 11329 msg.obj = response; 11330 mHandler.sendMessage(msg); 11331 } 11332 11333 @Override 11334 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11335 long millisecondsToDelay) { 11336 mContext.enforceCallingOrSelfPermission( 11337 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11338 "Only package verification agents can extend verification timeouts"); 11339 11340 final PackageVerificationState state = mPendingVerification.get(id); 11341 final PackageVerificationResponse response = new PackageVerificationResponse( 11342 verificationCodeAtTimeout, Binder.getCallingUid()); 11343 11344 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11345 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11346 } 11347 if (millisecondsToDelay < 0) { 11348 millisecondsToDelay = 0; 11349 } 11350 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11351 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11352 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11353 } 11354 11355 if ((state != null) && !state.timeoutExtended()) { 11356 state.extendTimeout(); 11357 11358 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11359 msg.arg1 = id; 11360 msg.obj = response; 11361 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11362 } 11363 } 11364 11365 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11366 int verificationCode, UserHandle user) { 11367 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11368 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11369 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11370 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11371 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11372 11373 mContext.sendBroadcastAsUser(intent, user, 11374 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11375 } 11376 11377 private ComponentName matchComponentForVerifier(String packageName, 11378 List<ResolveInfo> receivers) { 11379 ActivityInfo targetReceiver = null; 11380 11381 final int NR = receivers.size(); 11382 for (int i = 0; i < NR; i++) { 11383 final ResolveInfo info = receivers.get(i); 11384 if (info.activityInfo == null) { 11385 continue; 11386 } 11387 11388 if (packageName.equals(info.activityInfo.packageName)) { 11389 targetReceiver = info.activityInfo; 11390 break; 11391 } 11392 } 11393 11394 if (targetReceiver == null) { 11395 return null; 11396 } 11397 11398 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11399 } 11400 11401 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11402 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11403 if (pkgInfo.verifiers.length == 0) { 11404 return null; 11405 } 11406 11407 final int N = pkgInfo.verifiers.length; 11408 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11409 for (int i = 0; i < N; i++) { 11410 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11411 11412 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11413 receivers); 11414 if (comp == null) { 11415 continue; 11416 } 11417 11418 final int verifierUid = getUidForVerifier(verifierInfo); 11419 if (verifierUid == -1) { 11420 continue; 11421 } 11422 11423 if (DEBUG_VERIFY) { 11424 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11425 + " with the correct signature"); 11426 } 11427 sufficientVerifiers.add(comp); 11428 verificationState.addSufficientVerifier(verifierUid); 11429 } 11430 11431 return sufficientVerifiers; 11432 } 11433 11434 private int getUidForVerifier(VerifierInfo verifierInfo) { 11435 synchronized (mPackages) { 11436 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11437 if (pkg == null) { 11438 return -1; 11439 } else if (pkg.mSignatures.length != 1) { 11440 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11441 + " has more than one signature; ignoring"); 11442 return -1; 11443 } 11444 11445 /* 11446 * If the public key of the package's signature does not match 11447 * our expected public key, then this is a different package and 11448 * we should skip. 11449 */ 11450 11451 final byte[] expectedPublicKey; 11452 try { 11453 final Signature verifierSig = pkg.mSignatures[0]; 11454 final PublicKey publicKey = verifierSig.getPublicKey(); 11455 expectedPublicKey = publicKey.getEncoded(); 11456 } catch (CertificateException e) { 11457 return -1; 11458 } 11459 11460 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11461 11462 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11463 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11464 + " does not have the expected public key; ignoring"); 11465 return -1; 11466 } 11467 11468 return pkg.applicationInfo.uid; 11469 } 11470 } 11471 11472 @Override 11473 public void finishPackageInstall(int token) { 11474 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11475 11476 if (DEBUG_INSTALL) { 11477 Slog.v(TAG, "BM finishing package install for " + token); 11478 } 11479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11480 11481 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11482 mHandler.sendMessage(msg); 11483 } 11484 11485 /** 11486 * Get the verification agent timeout. 11487 * 11488 * @return verification timeout in milliseconds 11489 */ 11490 private long getVerificationTimeout() { 11491 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11492 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11493 DEFAULT_VERIFICATION_TIMEOUT); 11494 } 11495 11496 /** 11497 * Get the default verification agent response code. 11498 * 11499 * @return default verification response code 11500 */ 11501 private int getDefaultVerificationResponse() { 11502 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11503 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11504 DEFAULT_VERIFICATION_RESPONSE); 11505 } 11506 11507 /** 11508 * Check whether or not package verification has been enabled. 11509 * 11510 * @return true if verification should be performed 11511 */ 11512 private boolean isVerificationEnabled(int userId, int installFlags) { 11513 if (!DEFAULT_VERIFY_ENABLE) { 11514 return false; 11515 } 11516 // Ephemeral apps don't get the full verification treatment 11517 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11518 if (DEBUG_EPHEMERAL) { 11519 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11520 } 11521 return false; 11522 } 11523 11524 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11525 11526 // Check if installing from ADB 11527 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11528 // Do not run verification in a test harness environment 11529 if (ActivityManager.isRunningInTestHarness()) { 11530 return false; 11531 } 11532 if (ensureVerifyAppsEnabled) { 11533 return true; 11534 } 11535 // Check if the developer does not want package verification for ADB installs 11536 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11537 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11538 return false; 11539 } 11540 } 11541 11542 if (ensureVerifyAppsEnabled) { 11543 return true; 11544 } 11545 11546 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11547 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11548 } 11549 11550 @Override 11551 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11552 throws RemoteException { 11553 mContext.enforceCallingOrSelfPermission( 11554 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11555 "Only intentfilter verification agents can verify applications"); 11556 11557 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11558 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11559 Binder.getCallingUid(), verificationCode, failedDomains); 11560 msg.arg1 = id; 11561 msg.obj = response; 11562 mHandler.sendMessage(msg); 11563 } 11564 11565 @Override 11566 public int getIntentVerificationStatus(String packageName, int userId) { 11567 synchronized (mPackages) { 11568 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11569 } 11570 } 11571 11572 @Override 11573 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11574 mContext.enforceCallingOrSelfPermission( 11575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11576 11577 boolean result = false; 11578 synchronized (mPackages) { 11579 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11580 } 11581 if (result) { 11582 scheduleWritePackageRestrictionsLocked(userId); 11583 } 11584 return result; 11585 } 11586 11587 @Override 11588 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11589 String packageName) { 11590 synchronized (mPackages) { 11591 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11592 } 11593 } 11594 11595 @Override 11596 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11597 if (TextUtils.isEmpty(packageName)) { 11598 return ParceledListSlice.emptyList(); 11599 } 11600 synchronized (mPackages) { 11601 PackageParser.Package pkg = mPackages.get(packageName); 11602 if (pkg == null || pkg.activities == null) { 11603 return ParceledListSlice.emptyList(); 11604 } 11605 final int count = pkg.activities.size(); 11606 ArrayList<IntentFilter> result = new ArrayList<>(); 11607 for (int n=0; n<count; n++) { 11608 PackageParser.Activity activity = pkg.activities.get(n); 11609 if (activity.intents != null && activity.intents.size() > 0) { 11610 result.addAll(activity.intents); 11611 } 11612 } 11613 return new ParceledListSlice<>(result); 11614 } 11615 } 11616 11617 @Override 11618 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11619 mContext.enforceCallingOrSelfPermission( 11620 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11621 11622 synchronized (mPackages) { 11623 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11624 if (packageName != null) { 11625 result |= updateIntentVerificationStatus(packageName, 11626 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11627 userId); 11628 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11629 packageName, userId); 11630 } 11631 return result; 11632 } 11633 } 11634 11635 @Override 11636 public String getDefaultBrowserPackageName(int userId) { 11637 synchronized (mPackages) { 11638 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11639 } 11640 } 11641 11642 /** 11643 * Get the "allow unknown sources" setting. 11644 * 11645 * @return the current "allow unknown sources" setting 11646 */ 11647 private int getUnknownSourcesSettings() { 11648 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11649 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11650 -1); 11651 } 11652 11653 @Override 11654 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11655 final int uid = Binder.getCallingUid(); 11656 // writer 11657 synchronized (mPackages) { 11658 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11659 if (targetPackageSetting == null) { 11660 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11661 } 11662 11663 PackageSetting installerPackageSetting; 11664 if (installerPackageName != null) { 11665 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11666 if (installerPackageSetting == null) { 11667 throw new IllegalArgumentException("Unknown installer package: " 11668 + installerPackageName); 11669 } 11670 } else { 11671 installerPackageSetting = null; 11672 } 11673 11674 Signature[] callerSignature; 11675 Object obj = mSettings.getUserIdLPr(uid); 11676 if (obj != null) { 11677 if (obj instanceof SharedUserSetting) { 11678 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11679 } else if (obj instanceof PackageSetting) { 11680 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11681 } else { 11682 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11683 } 11684 } else { 11685 throw new SecurityException("Unknown calling UID: " + uid); 11686 } 11687 11688 // Verify: can't set installerPackageName to a package that is 11689 // not signed with the same cert as the caller. 11690 if (installerPackageSetting != null) { 11691 if (compareSignatures(callerSignature, 11692 installerPackageSetting.signatures.mSignatures) 11693 != PackageManager.SIGNATURE_MATCH) { 11694 throw new SecurityException( 11695 "Caller does not have same cert as new installer package " 11696 + installerPackageName); 11697 } 11698 } 11699 11700 // Verify: if target already has an installer package, it must 11701 // be signed with the same cert as the caller. 11702 if (targetPackageSetting.installerPackageName != null) { 11703 PackageSetting setting = mSettings.mPackages.get( 11704 targetPackageSetting.installerPackageName); 11705 // If the currently set package isn't valid, then it's always 11706 // okay to change it. 11707 if (setting != null) { 11708 if (compareSignatures(callerSignature, 11709 setting.signatures.mSignatures) 11710 != PackageManager.SIGNATURE_MATCH) { 11711 throw new SecurityException( 11712 "Caller does not have same cert as old installer package " 11713 + targetPackageSetting.installerPackageName); 11714 } 11715 } 11716 } 11717 11718 // Okay! 11719 targetPackageSetting.installerPackageName = installerPackageName; 11720 scheduleWriteSettingsLocked(); 11721 } 11722 } 11723 11724 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11725 // Queue up an async operation since the package installation may take a little while. 11726 mHandler.post(new Runnable() { 11727 public void run() { 11728 mHandler.removeCallbacks(this); 11729 // Result object to be returned 11730 PackageInstalledInfo res = new PackageInstalledInfo(); 11731 res.setReturnCode(currentStatus); 11732 res.uid = -1; 11733 res.pkg = null; 11734 res.removedInfo = null; 11735 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11736 args.doPreInstall(res.returnCode); 11737 synchronized (mInstallLock) { 11738 installPackageTracedLI(args, res); 11739 } 11740 args.doPostInstall(res.returnCode, res.uid); 11741 } 11742 11743 // A restore should be performed at this point if (a) the install 11744 // succeeded, (b) the operation is not an update, and (c) the new 11745 // package has not opted out of backup participation. 11746 final boolean update = res.removedInfo != null 11747 && res.removedInfo.removedPackage != null; 11748 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11749 boolean doRestore = !update 11750 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11751 11752 // Set up the post-install work request bookkeeping. This will be used 11753 // and cleaned up by the post-install event handling regardless of whether 11754 // there's a restore pass performed. Token values are >= 1. 11755 int token; 11756 if (mNextInstallToken < 0) mNextInstallToken = 1; 11757 token = mNextInstallToken++; 11758 11759 PostInstallData data = new PostInstallData(args, res); 11760 mRunningInstalls.put(token, data); 11761 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11762 11763 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11764 // Pass responsibility to the Backup Manager. It will perform a 11765 // restore if appropriate, then pass responsibility back to the 11766 // Package Manager to run the post-install observer callbacks 11767 // and broadcasts. 11768 IBackupManager bm = IBackupManager.Stub.asInterface( 11769 ServiceManager.getService(Context.BACKUP_SERVICE)); 11770 if (bm != null) { 11771 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11772 + " to BM for possible restore"); 11773 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11774 try { 11775 // TODO: http://b/22388012 11776 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11777 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11778 } else { 11779 doRestore = false; 11780 } 11781 } catch (RemoteException e) { 11782 // can't happen; the backup manager is local 11783 } catch (Exception e) { 11784 Slog.e(TAG, "Exception trying to enqueue restore", e); 11785 doRestore = false; 11786 } 11787 } else { 11788 Slog.e(TAG, "Backup Manager not found!"); 11789 doRestore = false; 11790 } 11791 } 11792 11793 if (!doRestore) { 11794 // No restore possible, or the Backup Manager was mysteriously not 11795 // available -- just fire the post-install work request directly. 11796 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11797 11798 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11799 11800 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11801 mHandler.sendMessage(msg); 11802 } 11803 } 11804 }); 11805 } 11806 11807 private abstract class HandlerParams { 11808 private static final int MAX_RETRIES = 4; 11809 11810 /** 11811 * Number of times startCopy() has been attempted and had a non-fatal 11812 * error. 11813 */ 11814 private int mRetries = 0; 11815 11816 /** User handle for the user requesting the information or installation. */ 11817 private final UserHandle mUser; 11818 String traceMethod; 11819 int traceCookie; 11820 11821 HandlerParams(UserHandle user) { 11822 mUser = user; 11823 } 11824 11825 UserHandle getUser() { 11826 return mUser; 11827 } 11828 11829 HandlerParams setTraceMethod(String traceMethod) { 11830 this.traceMethod = traceMethod; 11831 return this; 11832 } 11833 11834 HandlerParams setTraceCookie(int traceCookie) { 11835 this.traceCookie = traceCookie; 11836 return this; 11837 } 11838 11839 final boolean startCopy() { 11840 boolean res; 11841 try { 11842 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11843 11844 if (++mRetries > MAX_RETRIES) { 11845 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11846 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11847 handleServiceError(); 11848 return false; 11849 } else { 11850 handleStartCopy(); 11851 res = true; 11852 } 11853 } catch (RemoteException e) { 11854 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11855 mHandler.sendEmptyMessage(MCS_RECONNECT); 11856 res = false; 11857 } 11858 handleReturnCode(); 11859 return res; 11860 } 11861 11862 final void serviceError() { 11863 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11864 handleServiceError(); 11865 handleReturnCode(); 11866 } 11867 11868 abstract void handleStartCopy() throws RemoteException; 11869 abstract void handleServiceError(); 11870 abstract void handleReturnCode(); 11871 } 11872 11873 class MeasureParams extends HandlerParams { 11874 private final PackageStats mStats; 11875 private boolean mSuccess; 11876 11877 private final IPackageStatsObserver mObserver; 11878 11879 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11880 super(new UserHandle(stats.userHandle)); 11881 mObserver = observer; 11882 mStats = stats; 11883 } 11884 11885 @Override 11886 public String toString() { 11887 return "MeasureParams{" 11888 + Integer.toHexString(System.identityHashCode(this)) 11889 + " " + mStats.packageName + "}"; 11890 } 11891 11892 @Override 11893 void handleStartCopy() throws RemoteException { 11894 synchronized (mInstallLock) { 11895 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11896 } 11897 11898 if (mSuccess) { 11899 final boolean mounted; 11900 if (Environment.isExternalStorageEmulated()) { 11901 mounted = true; 11902 } else { 11903 final String status = Environment.getExternalStorageState(); 11904 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11905 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11906 } 11907 11908 if (mounted) { 11909 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11910 11911 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11912 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11913 11914 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11915 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11916 11917 // Always subtract cache size, since it's a subdirectory 11918 mStats.externalDataSize -= mStats.externalCacheSize; 11919 11920 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11921 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11922 11923 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11924 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11925 } 11926 } 11927 } 11928 11929 @Override 11930 void handleReturnCode() { 11931 if (mObserver != null) { 11932 try { 11933 mObserver.onGetStatsCompleted(mStats, mSuccess); 11934 } catch (RemoteException e) { 11935 Slog.i(TAG, "Observer no longer exists."); 11936 } 11937 } 11938 } 11939 11940 @Override 11941 void handleServiceError() { 11942 Slog.e(TAG, "Could not measure application " + mStats.packageName 11943 + " external storage"); 11944 } 11945 } 11946 11947 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11948 throws RemoteException { 11949 long result = 0; 11950 for (File path : paths) { 11951 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11952 } 11953 return result; 11954 } 11955 11956 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11957 for (File path : paths) { 11958 try { 11959 mcs.clearDirectory(path.getAbsolutePath()); 11960 } catch (RemoteException e) { 11961 } 11962 } 11963 } 11964 11965 static class OriginInfo { 11966 /** 11967 * Location where install is coming from, before it has been 11968 * copied/renamed into place. This could be a single monolithic APK 11969 * file, or a cluster directory. This location may be untrusted. 11970 */ 11971 final File file; 11972 final String cid; 11973 11974 /** 11975 * Flag indicating that {@link #file} or {@link #cid} has already been 11976 * staged, meaning downstream users don't need to defensively copy the 11977 * contents. 11978 */ 11979 final boolean staged; 11980 11981 /** 11982 * Flag indicating that {@link #file} or {@link #cid} is an already 11983 * installed app that is being moved. 11984 */ 11985 final boolean existing; 11986 11987 final String resolvedPath; 11988 final File resolvedFile; 11989 11990 static OriginInfo fromNothing() { 11991 return new OriginInfo(null, null, false, false); 11992 } 11993 11994 static OriginInfo fromUntrustedFile(File file) { 11995 return new OriginInfo(file, null, false, false); 11996 } 11997 11998 static OriginInfo fromExistingFile(File file) { 11999 return new OriginInfo(file, null, false, true); 12000 } 12001 12002 static OriginInfo fromStagedFile(File file) { 12003 return new OriginInfo(file, null, true, false); 12004 } 12005 12006 static OriginInfo fromStagedContainer(String cid) { 12007 return new OriginInfo(null, cid, true, false); 12008 } 12009 12010 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12011 this.file = file; 12012 this.cid = cid; 12013 this.staged = staged; 12014 this.existing = existing; 12015 12016 if (cid != null) { 12017 resolvedPath = PackageHelper.getSdDir(cid); 12018 resolvedFile = new File(resolvedPath); 12019 } else if (file != null) { 12020 resolvedPath = file.getAbsolutePath(); 12021 resolvedFile = file; 12022 } else { 12023 resolvedPath = null; 12024 resolvedFile = null; 12025 } 12026 } 12027 } 12028 12029 static class MoveInfo { 12030 final int moveId; 12031 final String fromUuid; 12032 final String toUuid; 12033 final String packageName; 12034 final String dataAppName; 12035 final int appId; 12036 final String seinfo; 12037 final int targetSdkVersion; 12038 12039 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12040 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12041 this.moveId = moveId; 12042 this.fromUuid = fromUuid; 12043 this.toUuid = toUuid; 12044 this.packageName = packageName; 12045 this.dataAppName = dataAppName; 12046 this.appId = appId; 12047 this.seinfo = seinfo; 12048 this.targetSdkVersion = targetSdkVersion; 12049 } 12050 } 12051 12052 static class VerificationInfo { 12053 /** A constant used to indicate that a uid value is not present. */ 12054 public static final int NO_UID = -1; 12055 12056 /** URI referencing where the package was downloaded from. */ 12057 final Uri originatingUri; 12058 12059 /** HTTP referrer URI associated with the originatingURI. */ 12060 final Uri referrer; 12061 12062 /** UID of the application that the install request originated from. */ 12063 final int originatingUid; 12064 12065 /** UID of application requesting the install */ 12066 final int installerUid; 12067 12068 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12069 this.originatingUri = originatingUri; 12070 this.referrer = referrer; 12071 this.originatingUid = originatingUid; 12072 this.installerUid = installerUid; 12073 } 12074 } 12075 12076 class InstallParams extends HandlerParams { 12077 final OriginInfo origin; 12078 final MoveInfo move; 12079 final IPackageInstallObserver2 observer; 12080 int installFlags; 12081 final String installerPackageName; 12082 final String volumeUuid; 12083 private InstallArgs mArgs; 12084 private int mRet; 12085 final String packageAbiOverride; 12086 final String[] grantedRuntimePermissions; 12087 final VerificationInfo verificationInfo; 12088 12089 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12090 int installFlags, String installerPackageName, String volumeUuid, 12091 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12092 String[] grantedPermissions) { 12093 super(user); 12094 this.origin = origin; 12095 this.move = move; 12096 this.observer = observer; 12097 this.installFlags = installFlags; 12098 this.installerPackageName = installerPackageName; 12099 this.volumeUuid = volumeUuid; 12100 this.verificationInfo = verificationInfo; 12101 this.packageAbiOverride = packageAbiOverride; 12102 this.grantedRuntimePermissions = grantedPermissions; 12103 } 12104 12105 @Override 12106 public String toString() { 12107 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12108 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12109 } 12110 12111 private int installLocationPolicy(PackageInfoLite pkgLite) { 12112 String packageName = pkgLite.packageName; 12113 int installLocation = pkgLite.installLocation; 12114 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12115 // reader 12116 synchronized (mPackages) { 12117 // Currently installed package which the new package is attempting to replace or 12118 // null if no such package is installed. 12119 PackageParser.Package installedPkg = mPackages.get(packageName); 12120 // Package which currently owns the data which the new package will own if installed. 12121 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12122 // will be null whereas dataOwnerPkg will contain information about the package 12123 // which was uninstalled while keeping its data. 12124 PackageParser.Package dataOwnerPkg = installedPkg; 12125 if (dataOwnerPkg == null) { 12126 PackageSetting ps = mSettings.mPackages.get(packageName); 12127 if (ps != null) { 12128 dataOwnerPkg = ps.pkg; 12129 } 12130 } 12131 12132 if (dataOwnerPkg != null) { 12133 // If installed, the package will get access to data left on the device by its 12134 // predecessor. As a security measure, this is permited only if this is not a 12135 // version downgrade or if the predecessor package is marked as debuggable and 12136 // a downgrade is explicitly requested. 12137 // 12138 // On debuggable platform builds, downgrades are permitted even for 12139 // non-debuggable packages to make testing easier. Debuggable platform builds do 12140 // not offer security guarantees and thus it's OK to disable some security 12141 // mechanisms to make debugging/testing easier on those builds. However, even on 12142 // debuggable builds downgrades of packages are permitted only if requested via 12143 // installFlags. This is because we aim to keep the behavior of debuggable 12144 // platform builds as close as possible to the behavior of non-debuggable 12145 // platform builds. 12146 final boolean downgradeRequested = 12147 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12148 final boolean packageDebuggable = 12149 (dataOwnerPkg.applicationInfo.flags 12150 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12151 final boolean downgradePermitted = 12152 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12153 if (!downgradePermitted) { 12154 try { 12155 checkDowngrade(dataOwnerPkg, pkgLite); 12156 } catch (PackageManagerException e) { 12157 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12158 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12159 } 12160 } 12161 } 12162 12163 if (installedPkg != null) { 12164 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12165 // Check for updated system application. 12166 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12167 if (onSd) { 12168 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12169 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12170 } 12171 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12172 } else { 12173 if (onSd) { 12174 // Install flag overrides everything. 12175 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12176 } 12177 // If current upgrade specifies particular preference 12178 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12179 // Application explicitly specified internal. 12180 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12181 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12182 // App explictly prefers external. Let policy decide 12183 } else { 12184 // Prefer previous location 12185 if (isExternal(installedPkg)) { 12186 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12187 } 12188 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12189 } 12190 } 12191 } else { 12192 // Invalid install. Return error code 12193 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12194 } 12195 } 12196 } 12197 // All the special cases have been taken care of. 12198 // Return result based on recommended install location. 12199 if (onSd) { 12200 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12201 } 12202 return pkgLite.recommendedInstallLocation; 12203 } 12204 12205 /* 12206 * Invoke remote method to get package information and install 12207 * location values. Override install location based on default 12208 * policy if needed and then create install arguments based 12209 * on the install location. 12210 */ 12211 public void handleStartCopy() throws RemoteException { 12212 int ret = PackageManager.INSTALL_SUCCEEDED; 12213 12214 // If we're already staged, we've firmly committed to an install location 12215 if (origin.staged) { 12216 if (origin.file != null) { 12217 installFlags |= PackageManager.INSTALL_INTERNAL; 12218 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12219 } else if (origin.cid != null) { 12220 installFlags |= PackageManager.INSTALL_EXTERNAL; 12221 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12222 } else { 12223 throw new IllegalStateException("Invalid stage location"); 12224 } 12225 } 12226 12227 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12228 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12229 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12230 PackageInfoLite pkgLite = null; 12231 12232 if (onInt && onSd) { 12233 // Check if both bits are set. 12234 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12235 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12236 } else if (onSd && ephemeral) { 12237 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12238 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12239 } else { 12240 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12241 packageAbiOverride); 12242 12243 if (DEBUG_EPHEMERAL && ephemeral) { 12244 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12245 } 12246 12247 /* 12248 * If we have too little free space, try to free cache 12249 * before giving up. 12250 */ 12251 if (!origin.staged && pkgLite.recommendedInstallLocation 12252 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12253 // TODO: focus freeing disk space on the target device 12254 final StorageManager storage = StorageManager.from(mContext); 12255 final long lowThreshold = storage.getStorageLowBytes( 12256 Environment.getDataDirectory()); 12257 12258 final long sizeBytes = mContainerService.calculateInstalledSize( 12259 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12260 12261 try { 12262 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12263 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12264 installFlags, packageAbiOverride); 12265 } catch (InstallerException e) { 12266 Slog.w(TAG, "Failed to free cache", e); 12267 } 12268 12269 /* 12270 * The cache free must have deleted the file we 12271 * downloaded to install. 12272 * 12273 * TODO: fix the "freeCache" call to not delete 12274 * the file we care about. 12275 */ 12276 if (pkgLite.recommendedInstallLocation 12277 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12278 pkgLite.recommendedInstallLocation 12279 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12280 } 12281 } 12282 } 12283 12284 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12285 int loc = pkgLite.recommendedInstallLocation; 12286 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12287 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12288 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12289 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12290 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12291 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12292 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12293 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12294 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12295 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12296 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12297 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12298 } else { 12299 // Override with defaults if needed. 12300 loc = installLocationPolicy(pkgLite); 12301 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12302 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12303 } else if (!onSd && !onInt) { 12304 // Override install location with flags 12305 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12306 // Set the flag to install on external media. 12307 installFlags |= PackageManager.INSTALL_EXTERNAL; 12308 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12309 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12310 if (DEBUG_EPHEMERAL) { 12311 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12312 } 12313 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12314 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12315 |PackageManager.INSTALL_INTERNAL); 12316 } else { 12317 // Make sure the flag for installing on external 12318 // media is unset 12319 installFlags |= PackageManager.INSTALL_INTERNAL; 12320 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12321 } 12322 } 12323 } 12324 } 12325 12326 final InstallArgs args = createInstallArgs(this); 12327 mArgs = args; 12328 12329 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12330 // TODO: http://b/22976637 12331 // Apps installed for "all" users use the device owner to verify the app 12332 UserHandle verifierUser = getUser(); 12333 if (verifierUser == UserHandle.ALL) { 12334 verifierUser = UserHandle.SYSTEM; 12335 } 12336 12337 /* 12338 * Determine if we have any installed package verifiers. If we 12339 * do, then we'll defer to them to verify the packages. 12340 */ 12341 final int requiredUid = mRequiredVerifierPackage == null ? -1 12342 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12343 verifierUser.getIdentifier()); 12344 if (!origin.existing && requiredUid != -1 12345 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12346 final Intent verification = new Intent( 12347 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12348 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12349 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12350 PACKAGE_MIME_TYPE); 12351 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12352 12353 // Query all live verifiers based on current user state 12354 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12355 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12356 12357 if (DEBUG_VERIFY) { 12358 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12359 + verification.toString() + " with " + pkgLite.verifiers.length 12360 + " optional verifiers"); 12361 } 12362 12363 final int verificationId = mPendingVerificationToken++; 12364 12365 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12366 12367 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12368 installerPackageName); 12369 12370 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12371 installFlags); 12372 12373 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12374 pkgLite.packageName); 12375 12376 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12377 pkgLite.versionCode); 12378 12379 if (verificationInfo != null) { 12380 if (verificationInfo.originatingUri != null) { 12381 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12382 verificationInfo.originatingUri); 12383 } 12384 if (verificationInfo.referrer != null) { 12385 verification.putExtra(Intent.EXTRA_REFERRER, 12386 verificationInfo.referrer); 12387 } 12388 if (verificationInfo.originatingUid >= 0) { 12389 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12390 verificationInfo.originatingUid); 12391 } 12392 if (verificationInfo.installerUid >= 0) { 12393 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12394 verificationInfo.installerUid); 12395 } 12396 } 12397 12398 final PackageVerificationState verificationState = new PackageVerificationState( 12399 requiredUid, args); 12400 12401 mPendingVerification.append(verificationId, verificationState); 12402 12403 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12404 receivers, verificationState); 12405 12406 /* 12407 * If any sufficient verifiers were listed in the package 12408 * manifest, attempt to ask them. 12409 */ 12410 if (sufficientVerifiers != null) { 12411 final int N = sufficientVerifiers.size(); 12412 if (N == 0) { 12413 Slog.i(TAG, "Additional verifiers required, but none installed."); 12414 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12415 } else { 12416 for (int i = 0; i < N; i++) { 12417 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12418 12419 final Intent sufficientIntent = new Intent(verification); 12420 sufficientIntent.setComponent(verifierComponent); 12421 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12422 } 12423 } 12424 } 12425 12426 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12427 mRequiredVerifierPackage, receivers); 12428 if (ret == PackageManager.INSTALL_SUCCEEDED 12429 && mRequiredVerifierPackage != null) { 12430 Trace.asyncTraceBegin( 12431 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12432 /* 12433 * Send the intent to the required verification agent, 12434 * but only start the verification timeout after the 12435 * target BroadcastReceivers have run. 12436 */ 12437 verification.setComponent(requiredVerifierComponent); 12438 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12439 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12440 new BroadcastReceiver() { 12441 @Override 12442 public void onReceive(Context context, Intent intent) { 12443 final Message msg = mHandler 12444 .obtainMessage(CHECK_PENDING_VERIFICATION); 12445 msg.arg1 = verificationId; 12446 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12447 } 12448 }, null, 0, null, null); 12449 12450 /* 12451 * We don't want the copy to proceed until verification 12452 * succeeds, so null out this field. 12453 */ 12454 mArgs = null; 12455 } 12456 } else { 12457 /* 12458 * No package verification is enabled, so immediately start 12459 * the remote call to initiate copy using temporary file. 12460 */ 12461 ret = args.copyApk(mContainerService, true); 12462 } 12463 } 12464 12465 mRet = ret; 12466 } 12467 12468 @Override 12469 void handleReturnCode() { 12470 // If mArgs is null, then MCS couldn't be reached. When it 12471 // reconnects, it will try again to install. At that point, this 12472 // will succeed. 12473 if (mArgs != null) { 12474 processPendingInstall(mArgs, mRet); 12475 } 12476 } 12477 12478 @Override 12479 void handleServiceError() { 12480 mArgs = createInstallArgs(this); 12481 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12482 } 12483 12484 public boolean isForwardLocked() { 12485 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12486 } 12487 } 12488 12489 /** 12490 * Used during creation of InstallArgs 12491 * 12492 * @param installFlags package installation flags 12493 * @return true if should be installed on external storage 12494 */ 12495 private static boolean installOnExternalAsec(int installFlags) { 12496 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12497 return false; 12498 } 12499 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12500 return true; 12501 } 12502 return false; 12503 } 12504 12505 /** 12506 * Used during creation of InstallArgs 12507 * 12508 * @param installFlags package installation flags 12509 * @return true if should be installed as forward locked 12510 */ 12511 private static boolean installForwardLocked(int installFlags) { 12512 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12513 } 12514 12515 private InstallArgs createInstallArgs(InstallParams params) { 12516 if (params.move != null) { 12517 return new MoveInstallArgs(params); 12518 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12519 return new AsecInstallArgs(params); 12520 } else { 12521 return new FileInstallArgs(params); 12522 } 12523 } 12524 12525 /** 12526 * Create args that describe an existing installed package. Typically used 12527 * when cleaning up old installs, or used as a move source. 12528 */ 12529 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12530 String resourcePath, String[] instructionSets) { 12531 final boolean isInAsec; 12532 if (installOnExternalAsec(installFlags)) { 12533 /* Apps on SD card are always in ASEC containers. */ 12534 isInAsec = true; 12535 } else if (installForwardLocked(installFlags) 12536 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12537 /* 12538 * Forward-locked apps are only in ASEC containers if they're the 12539 * new style 12540 */ 12541 isInAsec = true; 12542 } else { 12543 isInAsec = false; 12544 } 12545 12546 if (isInAsec) { 12547 return new AsecInstallArgs(codePath, instructionSets, 12548 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12549 } else { 12550 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12551 } 12552 } 12553 12554 static abstract class InstallArgs { 12555 /** @see InstallParams#origin */ 12556 final OriginInfo origin; 12557 /** @see InstallParams#move */ 12558 final MoveInfo move; 12559 12560 final IPackageInstallObserver2 observer; 12561 // Always refers to PackageManager flags only 12562 final int installFlags; 12563 final String installerPackageName; 12564 final String volumeUuid; 12565 final UserHandle user; 12566 final String abiOverride; 12567 final String[] installGrantPermissions; 12568 /** If non-null, drop an async trace when the install completes */ 12569 final String traceMethod; 12570 final int traceCookie; 12571 12572 // The list of instruction sets supported by this app. This is currently 12573 // only used during the rmdex() phase to clean up resources. We can get rid of this 12574 // if we move dex files under the common app path. 12575 /* nullable */ String[] instructionSets; 12576 12577 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12578 int installFlags, String installerPackageName, String volumeUuid, 12579 UserHandle user, String[] instructionSets, 12580 String abiOverride, String[] installGrantPermissions, 12581 String traceMethod, int traceCookie) { 12582 this.origin = origin; 12583 this.move = move; 12584 this.installFlags = installFlags; 12585 this.observer = observer; 12586 this.installerPackageName = installerPackageName; 12587 this.volumeUuid = volumeUuid; 12588 this.user = user; 12589 this.instructionSets = instructionSets; 12590 this.abiOverride = abiOverride; 12591 this.installGrantPermissions = installGrantPermissions; 12592 this.traceMethod = traceMethod; 12593 this.traceCookie = traceCookie; 12594 } 12595 12596 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12597 abstract int doPreInstall(int status); 12598 12599 /** 12600 * Rename package into final resting place. All paths on the given 12601 * scanned package should be updated to reflect the rename. 12602 */ 12603 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12604 abstract int doPostInstall(int status, int uid); 12605 12606 /** @see PackageSettingBase#codePathString */ 12607 abstract String getCodePath(); 12608 /** @see PackageSettingBase#resourcePathString */ 12609 abstract String getResourcePath(); 12610 12611 // Need installer lock especially for dex file removal. 12612 abstract void cleanUpResourcesLI(); 12613 abstract boolean doPostDeleteLI(boolean delete); 12614 12615 /** 12616 * Called before the source arguments are copied. This is used mostly 12617 * for MoveParams when it needs to read the source file to put it in the 12618 * destination. 12619 */ 12620 int doPreCopy() { 12621 return PackageManager.INSTALL_SUCCEEDED; 12622 } 12623 12624 /** 12625 * Called after the source arguments are copied. This is used mostly for 12626 * MoveParams when it needs to read the source file to put it in the 12627 * destination. 12628 */ 12629 int doPostCopy(int uid) { 12630 return PackageManager.INSTALL_SUCCEEDED; 12631 } 12632 12633 protected boolean isFwdLocked() { 12634 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12635 } 12636 12637 protected boolean isExternalAsec() { 12638 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12639 } 12640 12641 protected boolean isEphemeral() { 12642 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12643 } 12644 12645 UserHandle getUser() { 12646 return user; 12647 } 12648 } 12649 12650 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12651 if (!allCodePaths.isEmpty()) { 12652 if (instructionSets == null) { 12653 throw new IllegalStateException("instructionSet == null"); 12654 } 12655 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12656 for (String codePath : allCodePaths) { 12657 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12658 try { 12659 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12660 } catch (InstallerException ignored) { 12661 } 12662 } 12663 } 12664 } 12665 } 12666 12667 /** 12668 * Logic to handle installation of non-ASEC applications, including copying 12669 * and renaming logic. 12670 */ 12671 class FileInstallArgs extends InstallArgs { 12672 private File codeFile; 12673 private File resourceFile; 12674 12675 // Example topology: 12676 // /data/app/com.example/base.apk 12677 // /data/app/com.example/split_foo.apk 12678 // /data/app/com.example/lib/arm/libfoo.so 12679 // /data/app/com.example/lib/arm64/libfoo.so 12680 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12681 12682 /** New install */ 12683 FileInstallArgs(InstallParams params) { 12684 super(params.origin, params.move, params.observer, params.installFlags, 12685 params.installerPackageName, params.volumeUuid, 12686 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12687 params.grantedRuntimePermissions, 12688 params.traceMethod, params.traceCookie); 12689 if (isFwdLocked()) { 12690 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12691 } 12692 } 12693 12694 /** Existing install */ 12695 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12696 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12697 null, null, null, 0); 12698 this.codeFile = (codePath != null) ? new File(codePath) : null; 12699 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12700 } 12701 12702 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12703 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12704 try { 12705 return doCopyApk(imcs, temp); 12706 } finally { 12707 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12708 } 12709 } 12710 12711 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12712 if (origin.staged) { 12713 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12714 codeFile = origin.file; 12715 resourceFile = origin.file; 12716 return PackageManager.INSTALL_SUCCEEDED; 12717 } 12718 12719 try { 12720 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12721 final File tempDir = 12722 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12723 codeFile = tempDir; 12724 resourceFile = tempDir; 12725 } catch (IOException e) { 12726 Slog.w(TAG, "Failed to create copy file: " + e); 12727 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12728 } 12729 12730 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12731 @Override 12732 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12733 if (!FileUtils.isValidExtFilename(name)) { 12734 throw new IllegalArgumentException("Invalid filename: " + name); 12735 } 12736 try { 12737 final File file = new File(codeFile, name); 12738 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12739 O_RDWR | O_CREAT, 0644); 12740 Os.chmod(file.getAbsolutePath(), 0644); 12741 return new ParcelFileDescriptor(fd); 12742 } catch (ErrnoException e) { 12743 throw new RemoteException("Failed to open: " + e.getMessage()); 12744 } 12745 } 12746 }; 12747 12748 int ret = PackageManager.INSTALL_SUCCEEDED; 12749 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12750 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12751 Slog.e(TAG, "Failed to copy package"); 12752 return ret; 12753 } 12754 12755 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12756 NativeLibraryHelper.Handle handle = null; 12757 try { 12758 handle = NativeLibraryHelper.Handle.create(codeFile); 12759 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12760 abiOverride); 12761 } catch (IOException e) { 12762 Slog.e(TAG, "Copying native libraries failed", e); 12763 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12764 } finally { 12765 IoUtils.closeQuietly(handle); 12766 } 12767 12768 return ret; 12769 } 12770 12771 int doPreInstall(int status) { 12772 if (status != PackageManager.INSTALL_SUCCEEDED) { 12773 cleanUp(); 12774 } 12775 return status; 12776 } 12777 12778 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12779 if (status != PackageManager.INSTALL_SUCCEEDED) { 12780 cleanUp(); 12781 return false; 12782 } 12783 12784 final File targetDir = codeFile.getParentFile(); 12785 final File beforeCodeFile = codeFile; 12786 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12787 12788 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12789 try { 12790 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12791 } catch (ErrnoException e) { 12792 Slog.w(TAG, "Failed to rename", e); 12793 return false; 12794 } 12795 12796 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12797 Slog.w(TAG, "Failed to restorecon"); 12798 return false; 12799 } 12800 12801 // Reflect the rename internally 12802 codeFile = afterCodeFile; 12803 resourceFile = afterCodeFile; 12804 12805 // Reflect the rename in scanned details 12806 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12807 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12808 afterCodeFile, pkg.baseCodePath)); 12809 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12810 afterCodeFile, pkg.splitCodePaths)); 12811 12812 // Reflect the rename in app info 12813 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12814 pkg.setApplicationInfoCodePath(pkg.codePath); 12815 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12816 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12817 pkg.setApplicationInfoResourcePath(pkg.codePath); 12818 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12819 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12820 12821 return true; 12822 } 12823 12824 int doPostInstall(int status, int uid) { 12825 if (status != PackageManager.INSTALL_SUCCEEDED) { 12826 cleanUp(); 12827 } 12828 return status; 12829 } 12830 12831 @Override 12832 String getCodePath() { 12833 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12834 } 12835 12836 @Override 12837 String getResourcePath() { 12838 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12839 } 12840 12841 private boolean cleanUp() { 12842 if (codeFile == null || !codeFile.exists()) { 12843 return false; 12844 } 12845 12846 removeCodePathLI(codeFile); 12847 12848 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12849 resourceFile.delete(); 12850 } 12851 12852 return true; 12853 } 12854 12855 void cleanUpResourcesLI() { 12856 // Try enumerating all code paths before deleting 12857 List<String> allCodePaths = Collections.EMPTY_LIST; 12858 if (codeFile != null && codeFile.exists()) { 12859 try { 12860 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12861 allCodePaths = pkg.getAllCodePaths(); 12862 } catch (PackageParserException e) { 12863 // Ignored; we tried our best 12864 } 12865 } 12866 12867 cleanUp(); 12868 removeDexFiles(allCodePaths, instructionSets); 12869 } 12870 12871 boolean doPostDeleteLI(boolean delete) { 12872 // XXX err, shouldn't we respect the delete flag? 12873 cleanUpResourcesLI(); 12874 return true; 12875 } 12876 } 12877 12878 private boolean isAsecExternal(String cid) { 12879 final String asecPath = PackageHelper.getSdFilesystem(cid); 12880 return !asecPath.startsWith(mAsecInternalPath); 12881 } 12882 12883 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12884 PackageManagerException { 12885 if (copyRet < 0) { 12886 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12887 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12888 throw new PackageManagerException(copyRet, message); 12889 } 12890 } 12891 } 12892 12893 /** 12894 * Extract the MountService "container ID" from the full code path of an 12895 * .apk. 12896 */ 12897 static String cidFromCodePath(String fullCodePath) { 12898 int eidx = fullCodePath.lastIndexOf("/"); 12899 String subStr1 = fullCodePath.substring(0, eidx); 12900 int sidx = subStr1.lastIndexOf("/"); 12901 return subStr1.substring(sidx+1, eidx); 12902 } 12903 12904 /** 12905 * Logic to handle installation of ASEC applications, including copying and 12906 * renaming logic. 12907 */ 12908 class AsecInstallArgs extends InstallArgs { 12909 static final String RES_FILE_NAME = "pkg.apk"; 12910 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12911 12912 String cid; 12913 String packagePath; 12914 String resourcePath; 12915 12916 /** New install */ 12917 AsecInstallArgs(InstallParams params) { 12918 super(params.origin, params.move, params.observer, params.installFlags, 12919 params.installerPackageName, params.volumeUuid, 12920 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12921 params.grantedRuntimePermissions, 12922 params.traceMethod, params.traceCookie); 12923 } 12924 12925 /** Existing install */ 12926 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12927 boolean isExternal, boolean isForwardLocked) { 12928 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12929 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12930 instructionSets, null, null, null, 0); 12931 // Hackily pretend we're still looking at a full code path 12932 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12933 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12934 } 12935 12936 // Extract cid from fullCodePath 12937 int eidx = fullCodePath.lastIndexOf("/"); 12938 String subStr1 = fullCodePath.substring(0, eidx); 12939 int sidx = subStr1.lastIndexOf("/"); 12940 cid = subStr1.substring(sidx+1, eidx); 12941 setMountPath(subStr1); 12942 } 12943 12944 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12945 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12946 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12947 instructionSets, null, null, null, 0); 12948 this.cid = cid; 12949 setMountPath(PackageHelper.getSdDir(cid)); 12950 } 12951 12952 void createCopyFile() { 12953 cid = mInstallerService.allocateExternalStageCidLegacy(); 12954 } 12955 12956 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12957 if (origin.staged && origin.cid != null) { 12958 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12959 cid = origin.cid; 12960 setMountPath(PackageHelper.getSdDir(cid)); 12961 return PackageManager.INSTALL_SUCCEEDED; 12962 } 12963 12964 if (temp) { 12965 createCopyFile(); 12966 } else { 12967 /* 12968 * Pre-emptively destroy the container since it's destroyed if 12969 * copying fails due to it existing anyway. 12970 */ 12971 PackageHelper.destroySdDir(cid); 12972 } 12973 12974 final String newMountPath = imcs.copyPackageToContainer( 12975 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12976 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12977 12978 if (newMountPath != null) { 12979 setMountPath(newMountPath); 12980 return PackageManager.INSTALL_SUCCEEDED; 12981 } else { 12982 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12983 } 12984 } 12985 12986 @Override 12987 String getCodePath() { 12988 return packagePath; 12989 } 12990 12991 @Override 12992 String getResourcePath() { 12993 return resourcePath; 12994 } 12995 12996 int doPreInstall(int status) { 12997 if (status != PackageManager.INSTALL_SUCCEEDED) { 12998 // Destroy container 12999 PackageHelper.destroySdDir(cid); 13000 } else { 13001 boolean mounted = PackageHelper.isContainerMounted(cid); 13002 if (!mounted) { 13003 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13004 Process.SYSTEM_UID); 13005 if (newMountPath != null) { 13006 setMountPath(newMountPath); 13007 } else { 13008 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13009 } 13010 } 13011 } 13012 return status; 13013 } 13014 13015 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13016 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13017 String newMountPath = null; 13018 if (PackageHelper.isContainerMounted(cid)) { 13019 // Unmount the container 13020 if (!PackageHelper.unMountSdDir(cid)) { 13021 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13022 return false; 13023 } 13024 } 13025 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13026 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13027 " which might be stale. Will try to clean up."); 13028 // Clean up the stale container and proceed to recreate. 13029 if (!PackageHelper.destroySdDir(newCacheId)) { 13030 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13031 return false; 13032 } 13033 // Successfully cleaned up stale container. Try to rename again. 13034 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13035 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13036 + " inspite of cleaning it up."); 13037 return false; 13038 } 13039 } 13040 if (!PackageHelper.isContainerMounted(newCacheId)) { 13041 Slog.w(TAG, "Mounting container " + newCacheId); 13042 newMountPath = PackageHelper.mountSdDir(newCacheId, 13043 getEncryptKey(), Process.SYSTEM_UID); 13044 } else { 13045 newMountPath = PackageHelper.getSdDir(newCacheId); 13046 } 13047 if (newMountPath == null) { 13048 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13049 return false; 13050 } 13051 Log.i(TAG, "Succesfully renamed " + cid + 13052 " to " + newCacheId + 13053 " at new path: " + newMountPath); 13054 cid = newCacheId; 13055 13056 final File beforeCodeFile = new File(packagePath); 13057 setMountPath(newMountPath); 13058 final File afterCodeFile = new File(packagePath); 13059 13060 // Reflect the rename in scanned details 13061 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13062 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13063 afterCodeFile, pkg.baseCodePath)); 13064 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13065 afterCodeFile, pkg.splitCodePaths)); 13066 13067 // Reflect the rename in app info 13068 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13069 pkg.setApplicationInfoCodePath(pkg.codePath); 13070 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13071 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13072 pkg.setApplicationInfoResourcePath(pkg.codePath); 13073 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13074 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13075 13076 return true; 13077 } 13078 13079 private void setMountPath(String mountPath) { 13080 final File mountFile = new File(mountPath); 13081 13082 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13083 if (monolithicFile.exists()) { 13084 packagePath = monolithicFile.getAbsolutePath(); 13085 if (isFwdLocked()) { 13086 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13087 } else { 13088 resourcePath = packagePath; 13089 } 13090 } else { 13091 packagePath = mountFile.getAbsolutePath(); 13092 resourcePath = packagePath; 13093 } 13094 } 13095 13096 int doPostInstall(int status, int uid) { 13097 if (status != PackageManager.INSTALL_SUCCEEDED) { 13098 cleanUp(); 13099 } else { 13100 final int groupOwner; 13101 final String protectedFile; 13102 if (isFwdLocked()) { 13103 groupOwner = UserHandle.getSharedAppGid(uid); 13104 protectedFile = RES_FILE_NAME; 13105 } else { 13106 groupOwner = -1; 13107 protectedFile = null; 13108 } 13109 13110 if (uid < Process.FIRST_APPLICATION_UID 13111 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13112 Slog.e(TAG, "Failed to finalize " + cid); 13113 PackageHelper.destroySdDir(cid); 13114 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13115 } 13116 13117 boolean mounted = PackageHelper.isContainerMounted(cid); 13118 if (!mounted) { 13119 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13120 } 13121 } 13122 return status; 13123 } 13124 13125 private void cleanUp() { 13126 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13127 13128 // Destroy secure container 13129 PackageHelper.destroySdDir(cid); 13130 } 13131 13132 private List<String> getAllCodePaths() { 13133 final File codeFile = new File(getCodePath()); 13134 if (codeFile != null && codeFile.exists()) { 13135 try { 13136 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13137 return pkg.getAllCodePaths(); 13138 } catch (PackageParserException e) { 13139 // Ignored; we tried our best 13140 } 13141 } 13142 return Collections.EMPTY_LIST; 13143 } 13144 13145 void cleanUpResourcesLI() { 13146 // Enumerate all code paths before deleting 13147 cleanUpResourcesLI(getAllCodePaths()); 13148 } 13149 13150 private void cleanUpResourcesLI(List<String> allCodePaths) { 13151 cleanUp(); 13152 removeDexFiles(allCodePaths, instructionSets); 13153 } 13154 13155 String getPackageName() { 13156 return getAsecPackageName(cid); 13157 } 13158 13159 boolean doPostDeleteLI(boolean delete) { 13160 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13161 final List<String> allCodePaths = getAllCodePaths(); 13162 boolean mounted = PackageHelper.isContainerMounted(cid); 13163 if (mounted) { 13164 // Unmount first 13165 if (PackageHelper.unMountSdDir(cid)) { 13166 mounted = false; 13167 } 13168 } 13169 if (!mounted && delete) { 13170 cleanUpResourcesLI(allCodePaths); 13171 } 13172 return !mounted; 13173 } 13174 13175 @Override 13176 int doPreCopy() { 13177 if (isFwdLocked()) { 13178 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13179 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13180 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13181 } 13182 } 13183 13184 return PackageManager.INSTALL_SUCCEEDED; 13185 } 13186 13187 @Override 13188 int doPostCopy(int uid) { 13189 if (isFwdLocked()) { 13190 if (uid < Process.FIRST_APPLICATION_UID 13191 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13192 RES_FILE_NAME)) { 13193 Slog.e(TAG, "Failed to finalize " + cid); 13194 PackageHelper.destroySdDir(cid); 13195 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13196 } 13197 } 13198 13199 return PackageManager.INSTALL_SUCCEEDED; 13200 } 13201 } 13202 13203 /** 13204 * Logic to handle movement of existing installed applications. 13205 */ 13206 class MoveInstallArgs extends InstallArgs { 13207 private File codeFile; 13208 private File resourceFile; 13209 13210 /** New install */ 13211 MoveInstallArgs(InstallParams params) { 13212 super(params.origin, params.move, params.observer, params.installFlags, 13213 params.installerPackageName, params.volumeUuid, 13214 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13215 params.grantedRuntimePermissions, 13216 params.traceMethod, params.traceCookie); 13217 } 13218 13219 int copyApk(IMediaContainerService imcs, boolean temp) { 13220 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13221 + move.fromUuid + " to " + move.toUuid); 13222 synchronized (mInstaller) { 13223 try { 13224 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13225 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13226 } catch (InstallerException e) { 13227 Slog.w(TAG, "Failed to move app", e); 13228 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13229 } 13230 } 13231 13232 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13233 resourceFile = codeFile; 13234 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13235 13236 return PackageManager.INSTALL_SUCCEEDED; 13237 } 13238 13239 int doPreInstall(int status) { 13240 if (status != PackageManager.INSTALL_SUCCEEDED) { 13241 cleanUp(move.toUuid); 13242 } 13243 return status; 13244 } 13245 13246 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13247 if (status != PackageManager.INSTALL_SUCCEEDED) { 13248 cleanUp(move.toUuid); 13249 return false; 13250 } 13251 13252 // Reflect the move in app info 13253 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13254 pkg.setApplicationInfoCodePath(pkg.codePath); 13255 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13256 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13257 pkg.setApplicationInfoResourcePath(pkg.codePath); 13258 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13259 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13260 13261 return true; 13262 } 13263 13264 int doPostInstall(int status, int uid) { 13265 if (status == PackageManager.INSTALL_SUCCEEDED) { 13266 cleanUp(move.fromUuid); 13267 } else { 13268 cleanUp(move.toUuid); 13269 } 13270 return status; 13271 } 13272 13273 @Override 13274 String getCodePath() { 13275 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13276 } 13277 13278 @Override 13279 String getResourcePath() { 13280 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13281 } 13282 13283 private boolean cleanUp(String volumeUuid) { 13284 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13285 move.dataAppName); 13286 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13287 synchronized (mInstallLock) { 13288 // Clean up both app data and code 13289 removeDataDirsLI(volumeUuid, move.packageName); 13290 removeCodePathLI(codeFile); 13291 } 13292 return true; 13293 } 13294 13295 void cleanUpResourcesLI() { 13296 throw new UnsupportedOperationException(); 13297 } 13298 13299 boolean doPostDeleteLI(boolean delete) { 13300 throw new UnsupportedOperationException(); 13301 } 13302 } 13303 13304 static String getAsecPackageName(String packageCid) { 13305 int idx = packageCid.lastIndexOf("-"); 13306 if (idx == -1) { 13307 return packageCid; 13308 } 13309 return packageCid.substring(0, idx); 13310 } 13311 13312 // Utility method used to create code paths based on package name and available index. 13313 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13314 String idxStr = ""; 13315 int idx = 1; 13316 // Fall back to default value of idx=1 if prefix is not 13317 // part of oldCodePath 13318 if (oldCodePath != null) { 13319 String subStr = oldCodePath; 13320 // Drop the suffix right away 13321 if (suffix != null && subStr.endsWith(suffix)) { 13322 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13323 } 13324 // If oldCodePath already contains prefix find out the 13325 // ending index to either increment or decrement. 13326 int sidx = subStr.lastIndexOf(prefix); 13327 if (sidx != -1) { 13328 subStr = subStr.substring(sidx + prefix.length()); 13329 if (subStr != null) { 13330 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13331 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13332 } 13333 try { 13334 idx = Integer.parseInt(subStr); 13335 if (idx <= 1) { 13336 idx++; 13337 } else { 13338 idx--; 13339 } 13340 } catch(NumberFormatException e) { 13341 } 13342 } 13343 } 13344 } 13345 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13346 return prefix + idxStr; 13347 } 13348 13349 private File getNextCodePath(File targetDir, String packageName) { 13350 int suffix = 1; 13351 File result; 13352 do { 13353 result = new File(targetDir, packageName + "-" + suffix); 13354 suffix++; 13355 } while (result.exists()); 13356 return result; 13357 } 13358 13359 // Utility method that returns the relative package path with respect 13360 // to the installation directory. Like say for /data/data/com.test-1.apk 13361 // string com.test-1 is returned. 13362 static String deriveCodePathName(String codePath) { 13363 if (codePath == null) { 13364 return null; 13365 } 13366 final File codeFile = new File(codePath); 13367 final String name = codeFile.getName(); 13368 if (codeFile.isDirectory()) { 13369 return name; 13370 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13371 final int lastDot = name.lastIndexOf('.'); 13372 return name.substring(0, lastDot); 13373 } else { 13374 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13375 return null; 13376 } 13377 } 13378 13379 static class PackageInstalledInfo { 13380 String name; 13381 int uid; 13382 // The set of users that originally had this package installed. 13383 int[] origUsers; 13384 // The set of users that now have this package installed. 13385 int[] newUsers; 13386 PackageParser.Package pkg; 13387 int returnCode; 13388 String returnMsg; 13389 PackageRemovedInfo removedInfo; 13390 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13391 13392 public void setError(int code, String msg) { 13393 setReturnCode(code); 13394 setReturnMessage(msg); 13395 Slog.w(TAG, msg); 13396 } 13397 13398 public void setError(String msg, PackageParserException e) { 13399 setReturnCode(e.error); 13400 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13401 Slog.w(TAG, msg, e); 13402 } 13403 13404 public void setError(String msg, PackageManagerException e) { 13405 returnCode = e.error; 13406 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13407 Slog.w(TAG, msg, e); 13408 } 13409 13410 public void setReturnCode(int returnCode) { 13411 this.returnCode = returnCode; 13412 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13413 for (int i = 0; i < childCount; i++) { 13414 addedChildPackages.valueAt(i).returnCode = returnCode; 13415 } 13416 } 13417 13418 private void setReturnMessage(String returnMsg) { 13419 this.returnMsg = returnMsg; 13420 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13421 for (int i = 0; i < childCount; i++) { 13422 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13423 } 13424 } 13425 13426 // In some error cases we want to convey more info back to the observer 13427 String origPackage; 13428 String origPermission; 13429 } 13430 13431 /* 13432 * Install a non-existing package. 13433 */ 13434 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13435 UserHandle user, String installerPackageName, String volumeUuid, 13436 PackageInstalledInfo res) { 13437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13438 13439 // Remember this for later, in case we need to rollback this install 13440 String pkgName = pkg.packageName; 13441 13442 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13443 13444 synchronized(mPackages) { 13445 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13446 // A package with the same name is already installed, though 13447 // it has been renamed to an older name. The package we 13448 // are trying to install should be installed as an update to 13449 // the existing one, but that has not been requested, so bail. 13450 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13451 + " without first uninstalling package running as " 13452 + mSettings.mRenamedPackages.get(pkgName)); 13453 return; 13454 } 13455 if (mPackages.containsKey(pkgName)) { 13456 // Don't allow installation over an existing package with the same name. 13457 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13458 + " without first uninstalling."); 13459 return; 13460 } 13461 } 13462 13463 try { 13464 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13465 System.currentTimeMillis(), user); 13466 13467 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13468 13469 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13470 prepareAppDataAfterInstall(newPackage); 13471 13472 } else { 13473 // Remove package from internal structures, but keep around any 13474 // data that might have already existed 13475 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13476 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13477 } 13478 } catch (PackageManagerException e) { 13479 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13480 } 13481 13482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13483 } 13484 13485 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13486 // Can't rotate keys during boot or if sharedUser. 13487 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13488 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13489 return false; 13490 } 13491 // app is using upgradeKeySets; make sure all are valid 13492 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13493 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13494 for (int i = 0; i < upgradeKeySets.length; i++) { 13495 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13496 Slog.wtf(TAG, "Package " 13497 + (oldPs.name != null ? oldPs.name : "<null>") 13498 + " contains upgrade-key-set reference to unknown key-set: " 13499 + upgradeKeySets[i] 13500 + " reverting to signatures check."); 13501 return false; 13502 } 13503 } 13504 return true; 13505 } 13506 13507 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13508 // Upgrade keysets are being used. Determine if new package has a superset of the 13509 // required keys. 13510 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13511 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13512 for (int i = 0; i < upgradeKeySets.length; i++) { 13513 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13514 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13515 return true; 13516 } 13517 } 13518 return false; 13519 } 13520 13521 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13522 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13523 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13524 13525 final PackageParser.Package oldPackage; 13526 final String pkgName = pkg.packageName; 13527 final int[] allUsers; 13528 final boolean weFroze; 13529 13530 // First find the old package info and check signatures 13531 synchronized(mPackages) { 13532 oldPackage = mPackages.get(pkgName); 13533 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13534 if (isEphemeral && !oldIsEphemeral) { 13535 // can't downgrade from full to ephemeral 13536 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13537 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13538 return; 13539 } 13540 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13541 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13542 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13543 if (!checkUpgradeKeySetLP(ps, pkg)) { 13544 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13545 "New package not signed by keys specified by upgrade-keysets: " 13546 + pkgName); 13547 return; 13548 } 13549 } else { 13550 // default to original signature matching 13551 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13552 != PackageManager.SIGNATURE_MATCH) { 13553 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13554 "New package has a different signature: " + pkgName); 13555 return; 13556 } 13557 } 13558 13559 // In case of rollback, remember per-user/profile install state 13560 allUsers = sUserManager.getUserIds(); 13561 13562 // Mark the app as frozen to prevent launching during the upgrade 13563 // process, and then kill all running instances 13564 if (!ps.frozen) { 13565 ps.frozen = true; 13566 weFroze = true; 13567 } else { 13568 weFroze = false; 13569 } 13570 } 13571 13572 try { 13573 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13574 installerPackageName, res); 13575 } finally { 13576 // Regardless of success or failure of upgrade steps above, always 13577 // unfreeze the package if we froze it 13578 if (weFroze) { 13579 unfreezePackage(pkgName); 13580 } 13581 } 13582 } 13583 13584 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13585 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13586 String installerPackageName, PackageInstalledInfo res) { 13587 // Update what is removed 13588 res.removedInfo = new PackageRemovedInfo(); 13589 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13590 res.removedInfo.removedPackage = oldPackage.packageName; 13591 res.removedInfo.isUpdate = true; 13592 final int childCount = (oldPackage.childPackages != null) 13593 ? oldPackage.childPackages.size() : 0; 13594 for (int i = 0; i < childCount; i++) { 13595 boolean childPackageUpdated = false; 13596 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13597 if (res.addedChildPackages != null) { 13598 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13599 if (childRes != null) { 13600 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13601 childRes.removedInfo.removedPackage = childPkg.packageName; 13602 childRes.removedInfo.isUpdate = true; 13603 childPackageUpdated = true; 13604 } 13605 } 13606 if (!childPackageUpdated) { 13607 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13608 childRemovedRes.removedPackage = childPkg.packageName; 13609 childRemovedRes.isUpdate = false; 13610 childRemovedRes.dataRemoved = true; 13611 synchronized (mPackages) { 13612 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13613 if (childPs != null) { 13614 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13615 } 13616 } 13617 if (res.removedInfo.removedChildPackages == null) { 13618 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13619 } 13620 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13621 } 13622 } 13623 13624 boolean sysPkg = (isSystemApp(oldPackage)); 13625 if (sysPkg) { 13626 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13627 user, allUsers, installerPackageName, res); 13628 } else { 13629 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13630 user, allUsers, installerPackageName, res); 13631 } 13632 } 13633 13634 public List<String> getPreviousCodePaths(String packageName) { 13635 final PackageSetting ps = mSettings.mPackages.get(packageName); 13636 final List<String> result = new ArrayList<String>(); 13637 if (ps != null && ps.oldCodePaths != null) { 13638 result.addAll(ps.oldCodePaths); 13639 } 13640 return result; 13641 } 13642 13643 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13644 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13645 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13646 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13647 + deletedPackage); 13648 13649 String pkgName = deletedPackage.packageName; 13650 boolean deletedPkg = true; 13651 boolean addedPkg = false; 13652 boolean updatedSettings = false; 13653 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13654 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13655 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13656 13657 final long origUpdateTime = (pkg.mExtras != null) 13658 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13659 13660 // First delete the existing package while retaining the data directory 13661 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13662 res.removedInfo, true, pkg)) { 13663 // If the existing package wasn't successfully deleted 13664 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13665 deletedPkg = false; 13666 } else { 13667 // Successfully deleted the old package; proceed with replace. 13668 13669 // If deleted package lived in a container, give users a chance to 13670 // relinquish resources before killing. 13671 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13672 if (DEBUG_INSTALL) { 13673 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13674 } 13675 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13676 final ArrayList<String> pkgList = new ArrayList<String>(1); 13677 pkgList.add(deletedPackage.applicationInfo.packageName); 13678 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13679 } 13680 13681 deleteCodeCacheDirsLI(pkg); 13682 deleteProfilesLI(pkg, /*destroy*/ false); 13683 13684 try { 13685 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13686 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13687 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13688 13689 // Update the in-memory copy of the previous code paths. 13690 PackageSetting ps = mSettings.mPackages.get(pkgName); 13691 if (!killApp) { 13692 if (ps.oldCodePaths == null) { 13693 ps.oldCodePaths = new ArraySet<>(); 13694 } 13695 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13696 if (deletedPackage.splitCodePaths != null) { 13697 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13698 } 13699 } else { 13700 ps.oldCodePaths = null; 13701 } 13702 if (ps.childPackageNames != null) { 13703 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13704 final String childPkgName = ps.childPackageNames.get(i); 13705 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13706 childPs.oldCodePaths = ps.oldCodePaths; 13707 } 13708 } 13709 prepareAppDataAfterInstall(newPackage); 13710 addedPkg = true; 13711 } catch (PackageManagerException e) { 13712 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13713 } 13714 } 13715 13716 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13717 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13718 13719 // Revert all internal state mutations and added folders for the failed install 13720 if (addedPkg) { 13721 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13722 res.removedInfo, true, null); 13723 } 13724 13725 // Restore the old package 13726 if (deletedPkg) { 13727 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13728 File restoreFile = new File(deletedPackage.codePath); 13729 // Parse old package 13730 boolean oldExternal = isExternal(deletedPackage); 13731 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13732 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13733 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13734 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13735 try { 13736 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13737 null); 13738 } catch (PackageManagerException e) { 13739 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13740 + e.getMessage()); 13741 return; 13742 } 13743 13744 synchronized (mPackages) { 13745 // Ensure the installer package name up to date 13746 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13747 13748 // Update permissions for restored package 13749 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13750 13751 mSettings.writeLPr(); 13752 } 13753 13754 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13755 } 13756 } else { 13757 synchronized (mPackages) { 13758 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13759 if (ps != null) { 13760 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13761 if (res.removedInfo.removedChildPackages != null) { 13762 final int childCount = res.removedInfo.removedChildPackages.size(); 13763 // Iterate in reverse as we may modify the collection 13764 for (int i = childCount - 1; i >= 0; i--) { 13765 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13766 if (res.addedChildPackages.containsKey(childPackageName)) { 13767 res.removedInfo.removedChildPackages.removeAt(i); 13768 } else { 13769 PackageRemovedInfo childInfo = res.removedInfo 13770 .removedChildPackages.valueAt(i); 13771 childInfo.removedForAllUsers = mPackages.get( 13772 childInfo.removedPackage) == null; 13773 } 13774 } 13775 } 13776 } 13777 } 13778 } 13779 } 13780 13781 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13782 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13783 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13784 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13785 + ", old=" + deletedPackage); 13786 13787 final boolean disabledSystem; 13788 13789 // Set the system/privileged flags as needed 13790 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13791 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13792 != 0) { 13793 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13794 } 13795 13796 // Kill package processes including services, providers, etc. 13797 killPackage(deletedPackage, "replace sys pkg"); 13798 13799 // Remove existing system package 13800 removePackageLI(deletedPackage, true); 13801 13802 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13803 if (!disabledSystem) { 13804 // We didn't need to disable the .apk as a current system package, 13805 // which means we are replacing another update that is already 13806 // installed. We need to make sure to delete the older one's .apk. 13807 res.removedInfo.args = createInstallArgsForExisting(0, 13808 deletedPackage.applicationInfo.getCodePath(), 13809 deletedPackage.applicationInfo.getResourcePath(), 13810 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13811 } else { 13812 res.removedInfo.args = null; 13813 } 13814 13815 // Successfully disabled the old package. Now proceed with re-installation 13816 deleteCodeCacheDirsLI(pkg); 13817 deleteProfilesLI(pkg, /*destroy*/ false); 13818 13819 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13820 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13821 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13822 13823 PackageParser.Package newPackage = null; 13824 try { 13825 // Add the package to the internal data structures 13826 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13827 13828 // Set the update and install times 13829 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13830 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13831 System.currentTimeMillis()); 13832 13833 // Check for shared user id changes 13834 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13835 deletedPackage, newPackage); 13836 if (invalidPackageName != null) { 13837 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13838 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13839 + " to " + invalidPackageName); 13840 } 13841 13842 // Update the package dynamic state if succeeded 13843 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13844 // Now that the install succeeded make sure we remove data 13845 // directories for any child package the update removed. 13846 final int deletedChildCount = (deletedPackage.childPackages != null) 13847 ? deletedPackage.childPackages.size() : 0; 13848 final int newChildCount = (newPackage.childPackages != null) 13849 ? newPackage.childPackages.size() : 0; 13850 for (int i = 0; i < deletedChildCount; i++) { 13851 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13852 boolean childPackageDeleted = true; 13853 for (int j = 0; j < newChildCount; j++) { 13854 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13855 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13856 childPackageDeleted = false; 13857 break; 13858 } 13859 } 13860 if (childPackageDeleted) { 13861 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13862 deletedChildPkg.packageName); 13863 if (ps != null && res.removedInfo.removedChildPackages != null) { 13864 PackageRemovedInfo removedChildRes = res.removedInfo 13865 .removedChildPackages.get(deletedChildPkg.packageName); 13866 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13867 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13868 } 13869 } 13870 } 13871 13872 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13873 prepareAppDataAfterInstall(newPackage); 13874 } 13875 } catch (PackageManagerException e) { 13876 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13877 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13878 } 13879 13880 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13881 // Re installation failed. Restore old information 13882 // Remove new pkg information 13883 if (newPackage != null) { 13884 removeInstalledPackageLI(newPackage, true); 13885 } 13886 // Add back the old system package 13887 try { 13888 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13889 } catch (PackageManagerException e) { 13890 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13891 } 13892 13893 synchronized (mPackages) { 13894 if (disabledSystem) { 13895 enableSystemPackageLPw(deletedPackage); 13896 } 13897 13898 // Ensure the installer package name up to date 13899 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13900 13901 // Update permissions for restored package 13902 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13903 13904 mSettings.writeLPr(); 13905 } 13906 13907 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13908 + " after failed upgrade"); 13909 } 13910 } 13911 13912 /** 13913 * Checks whether the parent or any of the child packages have a change shared 13914 * user. For a package to be a valid update the shred users of the parent and 13915 * the children should match. We may later support changing child shared users. 13916 * @param oldPkg The updated package. 13917 * @param newPkg The update package. 13918 * @return The shared user that change between the versions. 13919 */ 13920 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13921 PackageParser.Package newPkg) { 13922 // Check parent shared user 13923 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13924 return newPkg.packageName; 13925 } 13926 // Check child shared users 13927 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13928 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13929 for (int i = 0; i < newChildCount; i++) { 13930 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13931 // If this child was present, did it have the same shared user? 13932 for (int j = 0; j < oldChildCount; j++) { 13933 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13934 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13935 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13936 return newChildPkg.packageName; 13937 } 13938 } 13939 } 13940 return null; 13941 } 13942 13943 private void removeNativeBinariesLI(PackageSetting ps) { 13944 // Remove the lib path for the parent package 13945 if (ps != null) { 13946 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13947 // Remove the lib path for the child packages 13948 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13949 for (int i = 0; i < childCount; i++) { 13950 PackageSetting childPs = null; 13951 synchronized (mPackages) { 13952 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13953 } 13954 if (childPs != null) { 13955 NativeLibraryHelper.removeNativeBinariesLI(childPs 13956 .legacyNativeLibraryPathString); 13957 } 13958 } 13959 } 13960 } 13961 13962 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13963 // Enable the parent package 13964 mSettings.enableSystemPackageLPw(pkg.packageName); 13965 // Enable the child packages 13966 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13967 for (int i = 0; i < childCount; i++) { 13968 PackageParser.Package childPkg = pkg.childPackages.get(i); 13969 mSettings.enableSystemPackageLPw(childPkg.packageName); 13970 } 13971 } 13972 13973 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13974 PackageParser.Package newPkg) { 13975 // Disable the parent package (parent always replaced) 13976 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13977 // Disable the child packages 13978 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13979 for (int i = 0; i < childCount; i++) { 13980 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13981 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13982 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13983 } 13984 return disabled; 13985 } 13986 13987 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13988 String installerPackageName) { 13989 // Enable the parent package 13990 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13991 // Enable the child packages 13992 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13993 for (int i = 0; i < childCount; i++) { 13994 PackageParser.Package childPkg = pkg.childPackages.get(i); 13995 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13996 } 13997 } 13998 13999 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14000 // Collect all used permissions in the UID 14001 ArraySet<String> usedPermissions = new ArraySet<>(); 14002 final int packageCount = su.packages.size(); 14003 for (int i = 0; i < packageCount; i++) { 14004 PackageSetting ps = su.packages.valueAt(i); 14005 if (ps.pkg == null) { 14006 continue; 14007 } 14008 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14009 for (int j = 0; j < requestedPermCount; j++) { 14010 String permission = ps.pkg.requestedPermissions.get(j); 14011 BasePermission bp = mSettings.mPermissions.get(permission); 14012 if (bp != null) { 14013 usedPermissions.add(permission); 14014 } 14015 } 14016 } 14017 14018 PermissionsState permissionsState = su.getPermissionsState(); 14019 // Prune install permissions 14020 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14021 final int installPermCount = installPermStates.size(); 14022 for (int i = installPermCount - 1; i >= 0; i--) { 14023 PermissionState permissionState = installPermStates.get(i); 14024 if (!usedPermissions.contains(permissionState.getName())) { 14025 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14026 if (bp != null) { 14027 permissionsState.revokeInstallPermission(bp); 14028 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14029 PackageManager.MASK_PERMISSION_FLAGS, 0); 14030 } 14031 } 14032 } 14033 14034 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14035 14036 // Prune runtime permissions 14037 for (int userId : allUserIds) { 14038 List<PermissionState> runtimePermStates = permissionsState 14039 .getRuntimePermissionStates(userId); 14040 final int runtimePermCount = runtimePermStates.size(); 14041 for (int i = runtimePermCount - 1; i >= 0; i--) { 14042 PermissionState permissionState = runtimePermStates.get(i); 14043 if (!usedPermissions.contains(permissionState.getName())) { 14044 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14045 if (bp != null) { 14046 permissionsState.revokeRuntimePermission(bp, userId); 14047 permissionsState.updatePermissionFlags(bp, userId, 14048 PackageManager.MASK_PERMISSION_FLAGS, 0); 14049 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14050 runtimePermissionChangedUserIds, userId); 14051 } 14052 } 14053 } 14054 } 14055 14056 return runtimePermissionChangedUserIds; 14057 } 14058 14059 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14060 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14061 // Update the parent package setting 14062 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14063 res, user); 14064 // Update the child packages setting 14065 final int childCount = (newPackage.childPackages != null) 14066 ? newPackage.childPackages.size() : 0; 14067 for (int i = 0; i < childCount; i++) { 14068 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14069 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14070 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14071 childRes.origUsers, childRes, user); 14072 } 14073 } 14074 14075 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14076 String installerPackageName, int[] allUsers, int[] installedForUsers, 14077 PackageInstalledInfo res, UserHandle user) { 14078 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14079 14080 String pkgName = newPackage.packageName; 14081 synchronized (mPackages) { 14082 //write settings. the installStatus will be incomplete at this stage. 14083 //note that the new package setting would have already been 14084 //added to mPackages. It hasn't been persisted yet. 14085 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14086 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14087 mSettings.writeLPr(); 14088 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14089 } 14090 14091 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14092 synchronized (mPackages) { 14093 updatePermissionsLPw(newPackage.packageName, newPackage, 14094 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14095 ? UPDATE_PERMISSIONS_ALL : 0)); 14096 // For system-bundled packages, we assume that installing an upgraded version 14097 // of the package implies that the user actually wants to run that new code, 14098 // so we enable the package. 14099 PackageSetting ps = mSettings.mPackages.get(pkgName); 14100 final int userId = user.getIdentifier(); 14101 if (ps != null) { 14102 if (isSystemApp(newPackage)) { 14103 if (DEBUG_INSTALL) { 14104 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14105 } 14106 // Enable system package for requested users 14107 if (res.origUsers != null) { 14108 for (int origUserId : res.origUsers) { 14109 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14110 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14111 origUserId, installerPackageName); 14112 } 14113 } 14114 } 14115 // Also convey the prior install/uninstall state 14116 if (allUsers != null && installedForUsers != null) { 14117 for (int currentUserId : allUsers) { 14118 final boolean installed = ArrayUtils.contains( 14119 installedForUsers, currentUserId); 14120 if (DEBUG_INSTALL) { 14121 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14122 } 14123 ps.setInstalled(installed, currentUserId); 14124 } 14125 // these install state changes will be persisted in the 14126 // upcoming call to mSettings.writeLPr(). 14127 } 14128 } 14129 // It's implied that when a user requests installation, they want the app to be 14130 // installed and enabled. 14131 if (userId != UserHandle.USER_ALL) { 14132 ps.setInstalled(true, userId); 14133 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14134 } 14135 } 14136 res.name = pkgName; 14137 res.uid = newPackage.applicationInfo.uid; 14138 res.pkg = newPackage; 14139 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14140 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14141 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14142 //to update install status 14143 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14144 mSettings.writeLPr(); 14145 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14146 } 14147 14148 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14149 } 14150 14151 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14152 try { 14153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14154 installPackageLI(args, res); 14155 } finally { 14156 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14157 } 14158 } 14159 14160 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14161 final int installFlags = args.installFlags; 14162 final String installerPackageName = args.installerPackageName; 14163 final String volumeUuid = args.volumeUuid; 14164 final File tmpPackageFile = new File(args.getCodePath()); 14165 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14166 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14167 || (args.volumeUuid != null)); 14168 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14169 boolean replace = false; 14170 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14171 if (args.move != null) { 14172 // moving a complete application; perform an initial scan on the new install location 14173 scanFlags |= SCAN_INITIAL; 14174 } 14175 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14176 scanFlags |= SCAN_DONT_KILL_APP; 14177 } 14178 14179 // Result object to be returned 14180 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14181 14182 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14183 14184 // Sanity check 14185 if (ephemeral && (forwardLocked || onExternal)) { 14186 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14187 + " external=" + onExternal); 14188 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14189 return; 14190 } 14191 14192 // Retrieve PackageSettings and parse package 14193 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14194 | PackageParser.PARSE_ENFORCE_CODE 14195 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14196 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14197 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14198 PackageParser pp = new PackageParser(); 14199 pp.setSeparateProcesses(mSeparateProcesses); 14200 pp.setDisplayMetrics(mMetrics); 14201 14202 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14203 final PackageParser.Package pkg; 14204 try { 14205 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14206 } catch (PackageParserException e) { 14207 res.setError("Failed parse during installPackageLI", e); 14208 return; 14209 } finally { 14210 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14211 } 14212 14213 // If we are installing a clustered package add results for the children 14214 if (pkg.childPackages != null) { 14215 synchronized (mPackages) { 14216 final int childCount = pkg.childPackages.size(); 14217 for (int i = 0; i < childCount; i++) { 14218 PackageParser.Package childPkg = pkg.childPackages.get(i); 14219 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14220 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14221 childRes.pkg = childPkg; 14222 childRes.name = childPkg.packageName; 14223 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14224 if (childPs != null) { 14225 childRes.origUsers = childPs.queryInstalledUsers( 14226 sUserManager.getUserIds(), true); 14227 } 14228 if ((mPackages.containsKey(childPkg.packageName))) { 14229 childRes.removedInfo = new PackageRemovedInfo(); 14230 childRes.removedInfo.removedPackage = childPkg.packageName; 14231 } 14232 if (res.addedChildPackages == null) { 14233 res.addedChildPackages = new ArrayMap<>(); 14234 } 14235 res.addedChildPackages.put(childPkg.packageName, childRes); 14236 } 14237 } 14238 } 14239 14240 // If package doesn't declare API override, mark that we have an install 14241 // time CPU ABI override. 14242 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14243 pkg.cpuAbiOverride = args.abiOverride; 14244 } 14245 14246 String pkgName = res.name = pkg.packageName; 14247 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14248 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14249 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14250 return; 14251 } 14252 } 14253 14254 try { 14255 PackageParser.collectCertificates(pkg, parseFlags); 14256 } catch (PackageParserException e) { 14257 res.setError("Failed collect during installPackageLI", e); 14258 return; 14259 } 14260 14261 // Get rid of all references to package scan path via parser. 14262 pp = null; 14263 String oldCodePath = null; 14264 boolean systemApp = false; 14265 synchronized (mPackages) { 14266 // Check if installing already existing package 14267 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14268 String oldName = mSettings.mRenamedPackages.get(pkgName); 14269 if (pkg.mOriginalPackages != null 14270 && pkg.mOriginalPackages.contains(oldName) 14271 && mPackages.containsKey(oldName)) { 14272 // This package is derived from an original package, 14273 // and this device has been updating from that original 14274 // name. We must continue using the original name, so 14275 // rename the new package here. 14276 pkg.setPackageName(oldName); 14277 pkgName = pkg.packageName; 14278 replace = true; 14279 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14280 + oldName + " pkgName=" + pkgName); 14281 } else if (mPackages.containsKey(pkgName)) { 14282 // This package, under its official name, already exists 14283 // on the device; we should replace it. 14284 replace = true; 14285 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14286 } 14287 14288 // Child packages are installed through the parent package 14289 if (pkg.parentPackage != null) { 14290 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14291 "Package " + pkg.packageName + " is child of package " 14292 + pkg.parentPackage.parentPackage + ". Child packages " 14293 + "can be updated only through the parent package."); 14294 return; 14295 } 14296 14297 if (replace) { 14298 // Prevent apps opting out from runtime permissions 14299 PackageParser.Package oldPackage = mPackages.get(pkgName); 14300 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14301 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14302 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14303 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14304 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14305 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14306 + " doesn't support runtime permissions but the old" 14307 + " target SDK " + oldTargetSdk + " does."); 14308 return; 14309 } 14310 14311 // Prevent installing of child packages 14312 if (oldPackage.parentPackage != null) { 14313 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14314 "Package " + pkg.packageName + " is child of package " 14315 + oldPackage.parentPackage + ". Child packages " 14316 + "can be updated only through the parent package."); 14317 return; 14318 } 14319 } 14320 } 14321 14322 PackageSetting ps = mSettings.mPackages.get(pkgName); 14323 if (ps != null) { 14324 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14325 14326 // Quick sanity check that we're signed correctly if updating; 14327 // we'll check this again later when scanning, but we want to 14328 // bail early here before tripping over redefined permissions. 14329 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14330 if (!checkUpgradeKeySetLP(ps, pkg)) { 14331 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14332 + pkg.packageName + " upgrade keys do not match the " 14333 + "previously installed version"); 14334 return; 14335 } 14336 } else { 14337 try { 14338 verifySignaturesLP(ps, pkg); 14339 } catch (PackageManagerException e) { 14340 res.setError(e.error, e.getMessage()); 14341 return; 14342 } 14343 } 14344 14345 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14346 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14347 systemApp = (ps.pkg.applicationInfo.flags & 14348 ApplicationInfo.FLAG_SYSTEM) != 0; 14349 } 14350 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14351 } 14352 14353 // Check whether the newly-scanned package wants to define an already-defined perm 14354 int N = pkg.permissions.size(); 14355 for (int i = N-1; i >= 0; i--) { 14356 PackageParser.Permission perm = pkg.permissions.get(i); 14357 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14358 if (bp != null) { 14359 // If the defining package is signed with our cert, it's okay. This 14360 // also includes the "updating the same package" case, of course. 14361 // "updating same package" could also involve key-rotation. 14362 final boolean sigsOk; 14363 if (bp.sourcePackage.equals(pkg.packageName) 14364 && (bp.packageSetting instanceof PackageSetting) 14365 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14366 scanFlags))) { 14367 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14368 } else { 14369 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14370 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14371 } 14372 if (!sigsOk) { 14373 // If the owning package is the system itself, we log but allow 14374 // install to proceed; we fail the install on all other permission 14375 // redefinitions. 14376 if (!bp.sourcePackage.equals("android")) { 14377 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14378 + pkg.packageName + " attempting to redeclare permission " 14379 + perm.info.name + " already owned by " + bp.sourcePackage); 14380 res.origPermission = perm.info.name; 14381 res.origPackage = bp.sourcePackage; 14382 return; 14383 } else { 14384 Slog.w(TAG, "Package " + pkg.packageName 14385 + " attempting to redeclare system permission " 14386 + perm.info.name + "; ignoring new declaration"); 14387 pkg.permissions.remove(i); 14388 } 14389 } 14390 } 14391 } 14392 } 14393 14394 if (systemApp) { 14395 if (onExternal) { 14396 // Abort update; system app can't be replaced with app on sdcard 14397 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14398 "Cannot install updates to system apps on sdcard"); 14399 return; 14400 } else if (ephemeral) { 14401 // Abort update; system app can't be replaced with an ephemeral app 14402 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14403 "Cannot update a system app with an ephemeral app"); 14404 return; 14405 } 14406 } 14407 14408 if (args.move != null) { 14409 // We did an in-place move, so dex is ready to roll 14410 scanFlags |= SCAN_NO_DEX; 14411 scanFlags |= SCAN_MOVE; 14412 14413 synchronized (mPackages) { 14414 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14415 if (ps == null) { 14416 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14417 "Missing settings for moved package " + pkgName); 14418 } 14419 14420 // We moved the entire application as-is, so bring over the 14421 // previously derived ABI information. 14422 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14423 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14424 } 14425 14426 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14427 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14428 scanFlags |= SCAN_NO_DEX; 14429 14430 try { 14431 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14432 args.abiOverride : pkg.cpuAbiOverride); 14433 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14434 true /* extract libs */); 14435 } catch (PackageManagerException pme) { 14436 Slog.e(TAG, "Error deriving application ABI", pme); 14437 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14438 return; 14439 } 14440 14441 14442 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14443 // Do not run PackageDexOptimizer through the local performDexOpt 14444 // method because `pkg` is not in `mPackages` yet. 14445 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14446 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14447 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14448 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14449 String msg = "Extracking package failed for " + pkgName; 14450 res.setError(INSTALL_FAILED_DEXOPT, msg); 14451 return; 14452 } 14453 } 14454 14455 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14456 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14457 return; 14458 } 14459 14460 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14461 14462 if (replace) { 14463 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14464 installerPackageName, res); 14465 } else { 14466 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14467 args.user, installerPackageName, volumeUuid, res); 14468 } 14469 synchronized (mPackages) { 14470 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14471 if (ps != null) { 14472 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14473 } 14474 14475 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14476 for (int i = 0; i < childCount; i++) { 14477 PackageParser.Package childPkg = pkg.childPackages.get(i); 14478 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14479 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14480 if (childPs != null) { 14481 childRes.newUsers = childPs.queryInstalledUsers( 14482 sUserManager.getUserIds(), true); 14483 } 14484 } 14485 } 14486 } 14487 14488 private void startIntentFilterVerifications(int userId, boolean replacing, 14489 PackageParser.Package pkg) { 14490 if (mIntentFilterVerifierComponent == null) { 14491 Slog.w(TAG, "No IntentFilter verification will not be done as " 14492 + "there is no IntentFilterVerifier available!"); 14493 return; 14494 } 14495 14496 final int verifierUid = getPackageUid( 14497 mIntentFilterVerifierComponent.getPackageName(), 14498 MATCH_DEBUG_TRIAGED_MISSING, 14499 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14500 14501 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14502 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14503 mHandler.sendMessage(msg); 14504 14505 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14506 for (int i = 0; i < childCount; i++) { 14507 PackageParser.Package childPkg = pkg.childPackages.get(i); 14508 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14509 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14510 mHandler.sendMessage(msg); 14511 } 14512 } 14513 14514 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14515 PackageParser.Package pkg) { 14516 int size = pkg.activities.size(); 14517 if (size == 0) { 14518 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14519 "No activity, so no need to verify any IntentFilter!"); 14520 return; 14521 } 14522 14523 final boolean hasDomainURLs = hasDomainURLs(pkg); 14524 if (!hasDomainURLs) { 14525 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14526 "No domain URLs, so no need to verify any IntentFilter!"); 14527 return; 14528 } 14529 14530 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14531 + " if any IntentFilter from the " + size 14532 + " Activities needs verification ..."); 14533 14534 int count = 0; 14535 final String packageName = pkg.packageName; 14536 14537 synchronized (mPackages) { 14538 // If this is a new install and we see that we've already run verification for this 14539 // package, we have nothing to do: it means the state was restored from backup. 14540 if (!replacing) { 14541 IntentFilterVerificationInfo ivi = 14542 mSettings.getIntentFilterVerificationLPr(packageName); 14543 if (ivi != null) { 14544 if (DEBUG_DOMAIN_VERIFICATION) { 14545 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14546 + ivi.getStatusString()); 14547 } 14548 return; 14549 } 14550 } 14551 14552 // If any filters need to be verified, then all need to be. 14553 boolean needToVerify = false; 14554 for (PackageParser.Activity a : pkg.activities) { 14555 for (ActivityIntentInfo filter : a.intents) { 14556 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14557 if (DEBUG_DOMAIN_VERIFICATION) { 14558 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14559 } 14560 needToVerify = true; 14561 break; 14562 } 14563 } 14564 } 14565 14566 if (needToVerify) { 14567 final int verificationId = mIntentFilterVerificationToken++; 14568 for (PackageParser.Activity a : pkg.activities) { 14569 for (ActivityIntentInfo filter : a.intents) { 14570 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14571 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14572 "Verification needed for IntentFilter:" + filter.toString()); 14573 mIntentFilterVerifier.addOneIntentFilterVerification( 14574 verifierUid, userId, verificationId, filter, packageName); 14575 count++; 14576 } 14577 } 14578 } 14579 } 14580 } 14581 14582 if (count > 0) { 14583 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14584 + " IntentFilter verification" + (count > 1 ? "s" : "") 14585 + " for userId:" + userId); 14586 mIntentFilterVerifier.startVerifications(userId); 14587 } else { 14588 if (DEBUG_DOMAIN_VERIFICATION) { 14589 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14590 } 14591 } 14592 } 14593 14594 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14595 final ComponentName cn = filter.activity.getComponentName(); 14596 final String packageName = cn.getPackageName(); 14597 14598 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14599 packageName); 14600 if (ivi == null) { 14601 return true; 14602 } 14603 int status = ivi.getStatus(); 14604 switch (status) { 14605 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14606 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14607 return true; 14608 14609 default: 14610 // Nothing to do 14611 return false; 14612 } 14613 } 14614 14615 private static boolean isMultiArch(ApplicationInfo info) { 14616 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14617 } 14618 14619 private static boolean isExternal(PackageParser.Package pkg) { 14620 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14621 } 14622 14623 private static boolean isExternal(PackageSetting ps) { 14624 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14625 } 14626 14627 private static boolean isEphemeral(PackageParser.Package pkg) { 14628 return pkg.applicationInfo.isEphemeralApp(); 14629 } 14630 14631 private static boolean isEphemeral(PackageSetting ps) { 14632 return ps.pkg != null && isEphemeral(ps.pkg); 14633 } 14634 14635 private static boolean isSystemApp(PackageParser.Package pkg) { 14636 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14637 } 14638 14639 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14640 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14641 } 14642 14643 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14644 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14645 } 14646 14647 private static boolean isSystemApp(PackageSetting ps) { 14648 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14649 } 14650 14651 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14652 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14653 } 14654 14655 private int packageFlagsToInstallFlags(PackageSetting ps) { 14656 int installFlags = 0; 14657 if (isEphemeral(ps)) { 14658 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14659 } 14660 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14661 // This existing package was an external ASEC install when we have 14662 // the external flag without a UUID 14663 installFlags |= PackageManager.INSTALL_EXTERNAL; 14664 } 14665 if (ps.isForwardLocked()) { 14666 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14667 } 14668 return installFlags; 14669 } 14670 14671 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14672 if (isExternal(pkg)) { 14673 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14674 return StorageManager.UUID_PRIMARY_PHYSICAL; 14675 } else { 14676 return pkg.volumeUuid; 14677 } 14678 } else { 14679 return StorageManager.UUID_PRIVATE_INTERNAL; 14680 } 14681 } 14682 14683 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14684 if (isExternal(pkg)) { 14685 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14686 return mSettings.getExternalVersion(); 14687 } else { 14688 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14689 } 14690 } else { 14691 return mSettings.getInternalVersion(); 14692 } 14693 } 14694 14695 private void deleteTempPackageFiles() { 14696 final FilenameFilter filter = new FilenameFilter() { 14697 public boolean accept(File dir, String name) { 14698 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14699 } 14700 }; 14701 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14702 file.delete(); 14703 } 14704 } 14705 14706 @Override 14707 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14708 int flags) { 14709 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14710 flags); 14711 } 14712 14713 @Override 14714 public void deletePackage(final String packageName, 14715 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14716 mContext.enforceCallingOrSelfPermission( 14717 android.Manifest.permission.DELETE_PACKAGES, null); 14718 Preconditions.checkNotNull(packageName); 14719 Preconditions.checkNotNull(observer); 14720 final int uid = Binder.getCallingUid(); 14721 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14722 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14723 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14724 mContext.enforceCallingOrSelfPermission( 14725 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14726 "deletePackage for user " + userId); 14727 } 14728 14729 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14730 try { 14731 observer.onPackageDeleted(packageName, 14732 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14733 } catch (RemoteException re) { 14734 } 14735 return; 14736 } 14737 14738 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14739 try { 14740 observer.onPackageDeleted(packageName, 14741 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14742 } catch (RemoteException re) { 14743 } 14744 return; 14745 } 14746 14747 if (DEBUG_REMOVE) { 14748 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14749 + " deleteAllUsers: " + deleteAllUsers ); 14750 } 14751 // Queue up an async operation since the package deletion may take a little while. 14752 mHandler.post(new Runnable() { 14753 public void run() { 14754 mHandler.removeCallbacks(this); 14755 int returnCode; 14756 if (!deleteAllUsers) { 14757 returnCode = deletePackageX(packageName, userId, flags); 14758 } else { 14759 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14760 // If nobody is blocking uninstall, proceed with delete for all users 14761 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14762 returnCode = deletePackageX(packageName, userId, flags); 14763 } else { 14764 // Otherwise uninstall individually for users with blockUninstalls=false 14765 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14766 for (int userId : users) { 14767 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14768 returnCode = deletePackageX(packageName, userId, userFlags); 14769 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14770 Slog.w(TAG, "Package delete failed for user " + userId 14771 + ", returnCode " + returnCode); 14772 } 14773 } 14774 } 14775 // The app has only been marked uninstalled for certain users. 14776 // We still need to report that delete was blocked 14777 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14778 } 14779 } 14780 try { 14781 observer.onPackageDeleted(packageName, returnCode, null); 14782 } catch (RemoteException e) { 14783 Log.i(TAG, "Observer no longer exists."); 14784 } //end catch 14785 } //end run 14786 }); 14787 } 14788 14789 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14790 int[] result = EMPTY_INT_ARRAY; 14791 for (int userId : userIds) { 14792 if (getBlockUninstallForUser(packageName, userId)) { 14793 result = ArrayUtils.appendInt(result, userId); 14794 } 14795 } 14796 return result; 14797 } 14798 14799 @Override 14800 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14801 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14802 } 14803 14804 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14805 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14806 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14807 try { 14808 if (dpm != null) { 14809 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14810 /* callingUserOnly =*/ false); 14811 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14812 : deviceOwnerComponentName.getPackageName(); 14813 // Does the package contains the device owner? 14814 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14815 // this check is probably not needed, since DO should be registered as a device 14816 // admin on some user too. (Original bug for this: b/17657954) 14817 if (packageName.equals(deviceOwnerPackageName)) { 14818 return true; 14819 } 14820 // Does it contain a device admin for any user? 14821 int[] users; 14822 if (userId == UserHandle.USER_ALL) { 14823 users = sUserManager.getUserIds(); 14824 } else { 14825 users = new int[]{userId}; 14826 } 14827 for (int i = 0; i < users.length; ++i) { 14828 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14829 return true; 14830 } 14831 } 14832 } 14833 } catch (RemoteException e) { 14834 } 14835 return false; 14836 } 14837 14838 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14839 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14840 } 14841 14842 /** 14843 * This method is an internal method that could be get invoked either 14844 * to delete an installed package or to clean up a failed installation. 14845 * After deleting an installed package, a broadcast is sent to notify any 14846 * listeners that the package has been installed. For cleaning up a failed 14847 * installation, the broadcast is not necessary since the package's 14848 * installation wouldn't have sent the initial broadcast either 14849 * The key steps in deleting a package are 14850 * deleting the package information in internal structures like mPackages, 14851 * deleting the packages base directories through installd 14852 * updating mSettings to reflect current status 14853 * persisting settings for later use 14854 * sending a broadcast if necessary 14855 */ 14856 private int deletePackageX(String packageName, int userId, int flags) { 14857 final PackageRemovedInfo info = new PackageRemovedInfo(); 14858 final boolean res; 14859 14860 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14861 ? UserHandle.ALL : new UserHandle(userId); 14862 14863 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14864 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14865 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14866 } 14867 14868 PackageSetting uninstalledPs = null; 14869 14870 // for the uninstall-updates case and restricted profiles, remember the per- 14871 // user handle installed state 14872 int[] allUsers; 14873 synchronized (mPackages) { 14874 uninstalledPs = mSettings.mPackages.get(packageName); 14875 if (uninstalledPs == null) { 14876 Slog.w(TAG, "Not removing non-existent package " + packageName); 14877 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14878 } 14879 allUsers = sUserManager.getUserIds(); 14880 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14881 } 14882 14883 synchronized (mInstallLock) { 14884 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14885 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14886 flags | REMOVE_CHATTY, info, true, null); 14887 synchronized (mPackages) { 14888 if (res) { 14889 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14890 } 14891 } 14892 } 14893 14894 if (res) { 14895 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14896 info.sendPackageRemovedBroadcasts(killApp); 14897 info.sendSystemPackageUpdatedBroadcasts(); 14898 info.sendSystemPackageAppearedBroadcasts(); 14899 } 14900 // Force a gc here. 14901 Runtime.getRuntime().gc(); 14902 // Delete the resources here after sending the broadcast to let 14903 // other processes clean up before deleting resources. 14904 if (info.args != null) { 14905 synchronized (mInstallLock) { 14906 info.args.doPostDeleteLI(true); 14907 } 14908 } 14909 14910 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14911 } 14912 14913 class PackageRemovedInfo { 14914 String removedPackage; 14915 int uid = -1; 14916 int removedAppId = -1; 14917 int[] origUsers; 14918 int[] removedUsers = null; 14919 boolean isRemovedPackageSystemUpdate = false; 14920 boolean isUpdate; 14921 boolean dataRemoved; 14922 boolean removedForAllUsers; 14923 // Clean up resources deleted packages. 14924 InstallArgs args = null; 14925 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14926 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14927 14928 void sendPackageRemovedBroadcasts(boolean killApp) { 14929 sendPackageRemovedBroadcastInternal(killApp); 14930 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14931 for (int i = 0; i < childCount; i++) { 14932 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14933 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14934 } 14935 } 14936 14937 void sendSystemPackageUpdatedBroadcasts() { 14938 if (isRemovedPackageSystemUpdate) { 14939 sendSystemPackageUpdatedBroadcastsInternal(); 14940 final int childCount = (removedChildPackages != null) 14941 ? removedChildPackages.size() : 0; 14942 for (int i = 0; i < childCount; i++) { 14943 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14944 if (childInfo.isRemovedPackageSystemUpdate) { 14945 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14946 } 14947 } 14948 } 14949 } 14950 14951 void sendSystemPackageAppearedBroadcasts() { 14952 final int packageCount = (appearedChildPackages != null) 14953 ? appearedChildPackages.size() : 0; 14954 for (int i = 0; i < packageCount; i++) { 14955 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14956 for (int userId : installedInfo.newUsers) { 14957 sendPackageAddedForUser(installedInfo.name, true, 14958 UserHandle.getAppId(installedInfo.uid), userId); 14959 } 14960 } 14961 } 14962 14963 private void sendSystemPackageUpdatedBroadcastsInternal() { 14964 Bundle extras = new Bundle(2); 14965 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14966 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14967 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14968 extras, 0, null, null, null); 14969 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14970 extras, 0, null, null, null); 14971 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14972 null, 0, removedPackage, null, null); 14973 } 14974 14975 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14976 Bundle extras = new Bundle(2); 14977 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14978 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14979 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14980 if (isUpdate || isRemovedPackageSystemUpdate) { 14981 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14982 } 14983 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14984 if (removedPackage != null) { 14985 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14986 extras, 0, null, null, removedUsers); 14987 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14988 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14989 removedPackage, extras, 0, null, null, removedUsers); 14990 } 14991 } 14992 if (removedAppId >= 0) { 14993 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14994 removedUsers); 14995 } 14996 } 14997 } 14998 14999 /* 15000 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15001 * flag is not set, the data directory is removed as well. 15002 * make sure this flag is set for partially installed apps. If not its meaningless to 15003 * delete a partially installed application. 15004 */ 15005 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 15006 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15007 String packageName = ps.name; 15008 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15009 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 15010 // Retrieve object to delete permissions for shared user later on 15011 final PackageSetting deletedPs; 15012 // reader 15013 synchronized (mPackages) { 15014 deletedPs = mSettings.mPackages.get(packageName); 15015 if (outInfo != null) { 15016 outInfo.removedPackage = packageName; 15017 outInfo.removedUsers = deletedPs != null 15018 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15019 : null; 15020 } 15021 } 15022 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15023 removeDataDirsLI(ps.volumeUuid, packageName); 15024 if (outInfo != null) { 15025 outInfo.dataRemoved = true; 15026 } 15027 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15028 } 15029 // writer 15030 synchronized (mPackages) { 15031 if (deletedPs != null) { 15032 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15033 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15034 clearDefaultBrowserIfNeeded(packageName); 15035 if (outInfo != null) { 15036 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15037 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15038 } 15039 updatePermissionsLPw(deletedPs.name, null, 0); 15040 if (deletedPs.sharedUser != null) { 15041 // Remove permissions associated with package. Since runtime 15042 // permissions are per user we have to kill the removed package 15043 // or packages running under the shared user of the removed 15044 // package if revoking the permissions requested only by the removed 15045 // package is successful and this causes a change in gids. 15046 for (int userId : UserManagerService.getInstance().getUserIds()) { 15047 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15048 userId); 15049 if (userIdToKill == UserHandle.USER_ALL 15050 || userIdToKill >= UserHandle.USER_SYSTEM) { 15051 // If gids changed for this user, kill all affected packages. 15052 mHandler.post(new Runnable() { 15053 @Override 15054 public void run() { 15055 // This has to happen with no lock held. 15056 killApplication(deletedPs.name, deletedPs.appId, 15057 KILL_APP_REASON_GIDS_CHANGED); 15058 } 15059 }); 15060 break; 15061 } 15062 } 15063 } 15064 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15065 } 15066 // make sure to preserve per-user disabled state if this removal was just 15067 // a downgrade of a system app to the factory package 15068 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15069 if (DEBUG_REMOVE) { 15070 Slog.d(TAG, "Propagating install state across downgrade"); 15071 } 15072 for (int userId : allUserHandles) { 15073 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15074 if (DEBUG_REMOVE) { 15075 Slog.d(TAG, " user " + userId + " => " + installed); 15076 } 15077 ps.setInstalled(installed, userId); 15078 } 15079 } 15080 } 15081 // can downgrade to reader 15082 if (writeSettings) { 15083 // Save settings now 15084 mSettings.writeLPr(); 15085 } 15086 } 15087 if (outInfo != null) { 15088 // A user ID was deleted here. Go through all users and remove it 15089 // from KeyStore. 15090 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15091 } 15092 } 15093 15094 static boolean locationIsPrivileged(File path) { 15095 try { 15096 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15097 .getCanonicalPath(); 15098 return path.getCanonicalPath().startsWith(privilegedAppDir); 15099 } catch (IOException e) { 15100 Slog.e(TAG, "Unable to access code path " + path); 15101 } 15102 return false; 15103 } 15104 15105 /* 15106 * Tries to delete system package. 15107 */ 15108 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 15109 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15110 boolean writeSettings) { 15111 if (deletedPs.parentPackageName != null) { 15112 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15113 return false; 15114 } 15115 15116 final boolean applyUserRestrictions 15117 = (allUserHandles != null) && (outInfo.origUsers != null); 15118 final PackageSetting disabledPs; 15119 // Confirm if the system package has been updated 15120 // An updated system app can be deleted. This will also have to restore 15121 // the system pkg from system partition 15122 // reader 15123 synchronized (mPackages) { 15124 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15125 } 15126 15127 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15128 + " disabledPs=" + disabledPs); 15129 15130 if (disabledPs == null) { 15131 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15132 return false; 15133 } else if (DEBUG_REMOVE) { 15134 Slog.d(TAG, "Deleting system pkg from data partition"); 15135 } 15136 15137 if (DEBUG_REMOVE) { 15138 if (applyUserRestrictions) { 15139 Slog.d(TAG, "Remembering install states:"); 15140 for (int userId : allUserHandles) { 15141 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15142 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15143 } 15144 } 15145 } 15146 15147 // Delete the updated package 15148 outInfo.isRemovedPackageSystemUpdate = true; 15149 if (outInfo.removedChildPackages != null) { 15150 final int childCount = (deletedPs.childPackageNames != null) 15151 ? deletedPs.childPackageNames.size() : 0; 15152 for (int i = 0; i < childCount; i++) { 15153 String childPackageName = deletedPs.childPackageNames.get(i); 15154 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15155 .contains(childPackageName)) { 15156 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15157 childPackageName); 15158 if (childInfo != null) { 15159 childInfo.isRemovedPackageSystemUpdate = true; 15160 } 15161 } 15162 } 15163 } 15164 15165 if (disabledPs.versionCode < deletedPs.versionCode) { 15166 // Delete data for downgrades 15167 flags &= ~PackageManager.DELETE_KEEP_DATA; 15168 } else { 15169 // Preserve data by setting flag 15170 flags |= PackageManager.DELETE_KEEP_DATA; 15171 } 15172 15173 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 15174 outInfo, writeSettings, disabledPs.pkg); 15175 if (!ret) { 15176 return false; 15177 } 15178 15179 // writer 15180 synchronized (mPackages) { 15181 // Reinstate the old system package 15182 enableSystemPackageLPw(disabledPs.pkg); 15183 // Remove any native libraries from the upgraded package. 15184 removeNativeBinariesLI(deletedPs); 15185 } 15186 15187 // Install the system package 15188 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15189 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15190 if (locationIsPrivileged(disabledPs.codePath)) { 15191 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15192 } 15193 15194 final PackageParser.Package newPkg; 15195 try { 15196 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15197 } catch (PackageManagerException e) { 15198 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15199 + e.getMessage()); 15200 return false; 15201 } 15202 15203 prepareAppDataAfterInstall(newPkg); 15204 15205 // writer 15206 synchronized (mPackages) { 15207 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15208 15209 // Propagate the permissions state as we do not want to drop on the floor 15210 // runtime permissions. The update permissions method below will take 15211 // care of removing obsolete permissions and grant install permissions. 15212 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15213 updatePermissionsLPw(newPkg.packageName, newPkg, 15214 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15215 15216 if (applyUserRestrictions) { 15217 if (DEBUG_REMOVE) { 15218 Slog.d(TAG, "Propagating install state across reinstall"); 15219 } 15220 for (int userId : allUserHandles) { 15221 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15222 if (DEBUG_REMOVE) { 15223 Slog.d(TAG, " user " + userId + " => " + installed); 15224 } 15225 ps.setInstalled(installed, userId); 15226 15227 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15228 } 15229 // Regardless of writeSettings we need to ensure that this restriction 15230 // state propagation is persisted 15231 mSettings.writeAllUsersPackageRestrictionsLPr(); 15232 } 15233 // can downgrade to reader here 15234 if (writeSettings) { 15235 mSettings.writeLPr(); 15236 } 15237 } 15238 return true; 15239 } 15240 15241 private boolean deleteInstalledPackageLI(PackageSetting ps, 15242 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15243 PackageRemovedInfo outInfo, boolean writeSettings, 15244 PackageParser.Package replacingPackage) { 15245 synchronized (mPackages) { 15246 if (outInfo != null) { 15247 outInfo.uid = ps.appId; 15248 } 15249 15250 if (outInfo != null && outInfo.removedChildPackages != null) { 15251 final int childCount = (ps.childPackageNames != null) 15252 ? ps.childPackageNames.size() : 0; 15253 for (int i = 0; i < childCount; i++) { 15254 String childPackageName = ps.childPackageNames.get(i); 15255 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15256 if (childPs == null) { 15257 return false; 15258 } 15259 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15260 childPackageName); 15261 if (childInfo != null) { 15262 childInfo.uid = childPs.appId; 15263 } 15264 } 15265 } 15266 } 15267 15268 // Delete package data from internal structures and also remove data if flag is set 15269 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 15270 15271 // Delete the child packages data 15272 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15273 for (int i = 0; i < childCount; i++) { 15274 PackageSetting childPs; 15275 synchronized (mPackages) { 15276 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15277 } 15278 if (childPs != null) { 15279 PackageRemovedInfo childOutInfo = (outInfo != null 15280 && outInfo.removedChildPackages != null) 15281 ? outInfo.removedChildPackages.get(childPs.name) : null; 15282 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15283 && (replacingPackage != null 15284 && !replacingPackage.hasChildPackage(childPs.name)) 15285 ? flags & ~DELETE_KEEP_DATA : flags; 15286 removePackageDataLI(childPs, allUserHandles, childOutInfo, 15287 deleteFlags, writeSettings); 15288 } 15289 } 15290 15291 // Delete application code and resources only for parent packages 15292 if (ps.parentPackageName == null) { 15293 if (deleteCodeAndResources && (outInfo != null)) { 15294 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15295 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15296 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15297 } 15298 } 15299 15300 return true; 15301 } 15302 15303 @Override 15304 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15305 int userId) { 15306 mContext.enforceCallingOrSelfPermission( 15307 android.Manifest.permission.DELETE_PACKAGES, null); 15308 synchronized (mPackages) { 15309 PackageSetting ps = mSettings.mPackages.get(packageName); 15310 if (ps == null) { 15311 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15312 return false; 15313 } 15314 if (!ps.getInstalled(userId)) { 15315 // Can't block uninstall for an app that is not installed or enabled. 15316 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15317 return false; 15318 } 15319 ps.setBlockUninstall(blockUninstall, userId); 15320 mSettings.writePackageRestrictionsLPr(userId); 15321 } 15322 return true; 15323 } 15324 15325 @Override 15326 public boolean getBlockUninstallForUser(String packageName, int userId) { 15327 synchronized (mPackages) { 15328 PackageSetting ps = mSettings.mPackages.get(packageName); 15329 if (ps == null) { 15330 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15331 return false; 15332 } 15333 return ps.getBlockUninstall(userId); 15334 } 15335 } 15336 15337 @Override 15338 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15339 int callingUid = Binder.getCallingUid(); 15340 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15341 throw new SecurityException( 15342 "setRequiredForSystemUser can only be run by the system or root"); 15343 } 15344 synchronized (mPackages) { 15345 PackageSetting ps = mSettings.mPackages.get(packageName); 15346 if (ps == null) { 15347 Log.w(TAG, "Package doesn't exist: " + packageName); 15348 return false; 15349 } 15350 if (systemUserApp) { 15351 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15352 } else { 15353 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15354 } 15355 mSettings.writeLPr(); 15356 } 15357 return true; 15358 } 15359 15360 /* 15361 * This method handles package deletion in general 15362 */ 15363 private boolean deletePackageLI(String packageName, UserHandle user, 15364 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15365 PackageRemovedInfo outInfo, boolean writeSettings, 15366 PackageParser.Package replacingPackage) { 15367 if (packageName == null) { 15368 Slog.w(TAG, "Attempt to delete null packageName."); 15369 return false; 15370 } 15371 15372 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15373 15374 PackageSetting ps; 15375 15376 synchronized (mPackages) { 15377 ps = mSettings.mPackages.get(packageName); 15378 if (ps == null) { 15379 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15380 return false; 15381 } 15382 15383 if (ps.parentPackageName != null && (!isSystemApp(ps) 15384 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15385 if (DEBUG_REMOVE) { 15386 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15387 + ((user == null) ? UserHandle.USER_ALL : user)); 15388 } 15389 final int removedUserId = (user != null) ? user.getIdentifier() 15390 : UserHandle.USER_ALL; 15391 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15392 return false; 15393 } 15394 markPackageUninstalledForUserLPw(ps, user); 15395 scheduleWritePackageRestrictionsLocked(user); 15396 return true; 15397 } 15398 } 15399 15400 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15401 && user.getIdentifier() != UserHandle.USER_ALL)) { 15402 // The caller is asking that the package only be deleted for a single 15403 // user. To do this, we just mark its uninstalled state and delete 15404 // its data. If this is a system app, we only allow this to happen if 15405 // they have set the special DELETE_SYSTEM_APP which requests different 15406 // semantics than normal for uninstalling system apps. 15407 markPackageUninstalledForUserLPw(ps, user); 15408 15409 if (!isSystemApp(ps)) { 15410 // Do not uninstall the APK if an app should be cached 15411 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15412 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15413 // Other user still have this package installed, so all 15414 // we need to do is clear this user's data and save that 15415 // it is uninstalled. 15416 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15417 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15418 return false; 15419 } 15420 scheduleWritePackageRestrictionsLocked(user); 15421 return true; 15422 } else { 15423 // We need to set it back to 'installed' so the uninstall 15424 // broadcasts will be sent correctly. 15425 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15426 ps.setInstalled(true, user.getIdentifier()); 15427 } 15428 } else { 15429 // This is a system app, so we assume that the 15430 // other users still have this package installed, so all 15431 // we need to do is clear this user's data and save that 15432 // it is uninstalled. 15433 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15434 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15435 return false; 15436 } 15437 scheduleWritePackageRestrictionsLocked(user); 15438 return true; 15439 } 15440 } 15441 15442 // If we are deleting a composite package for all users, keep track 15443 // of result for each child. 15444 if (ps.childPackageNames != null && outInfo != null) { 15445 synchronized (mPackages) { 15446 final int childCount = ps.childPackageNames.size(); 15447 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15448 for (int i = 0; i < childCount; i++) { 15449 String childPackageName = ps.childPackageNames.get(i); 15450 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15451 childInfo.removedPackage = childPackageName; 15452 outInfo.removedChildPackages.put(childPackageName, childInfo); 15453 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15454 if (childPs != null) { 15455 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15456 } 15457 } 15458 } 15459 } 15460 15461 boolean ret = false; 15462 if (isSystemApp(ps)) { 15463 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15464 // When an updated system application is deleted we delete the existing resources 15465 // as well and fall back to existing code in system partition 15466 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15467 } else { 15468 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15469 // Kill application pre-emptively especially for apps on sd. 15470 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15471 if (killApp) { 15472 killApplication(packageName, ps.appId, "uninstall pkg"); 15473 } 15474 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15475 outInfo, writeSettings, replacingPackage); 15476 } 15477 15478 // Take a note whether we deleted the package for all users 15479 if (outInfo != null) { 15480 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15481 if (outInfo.removedChildPackages != null) { 15482 synchronized (mPackages) { 15483 final int childCount = outInfo.removedChildPackages.size(); 15484 for (int i = 0; i < childCount; i++) { 15485 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15486 if (childInfo != null) { 15487 childInfo.removedForAllUsers = mPackages.get( 15488 childInfo.removedPackage) == null; 15489 } 15490 } 15491 } 15492 } 15493 // If we uninstalled an update to a system app there may be some 15494 // child packages that appeared as they are declared in the system 15495 // app but were not declared in the update. 15496 if (isSystemApp(ps)) { 15497 synchronized (mPackages) { 15498 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15499 final int childCount = (updatedPs.childPackageNames != null) 15500 ? updatedPs.childPackageNames.size() : 0; 15501 for (int i = 0; i < childCount; i++) { 15502 String childPackageName = updatedPs.childPackageNames.get(i); 15503 if (outInfo.removedChildPackages == null 15504 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15505 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15506 if (childPs == null) { 15507 continue; 15508 } 15509 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15510 installRes.name = childPackageName; 15511 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15512 installRes.pkg = mPackages.get(childPackageName); 15513 installRes.uid = childPs.pkg.applicationInfo.uid; 15514 if (outInfo.appearedChildPackages == null) { 15515 outInfo.appearedChildPackages = new ArrayMap<>(); 15516 } 15517 outInfo.appearedChildPackages.put(childPackageName, installRes); 15518 } 15519 } 15520 } 15521 } 15522 } 15523 15524 return ret; 15525 } 15526 15527 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15528 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15529 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15530 for (int nextUserId : userIds) { 15531 if (DEBUG_REMOVE) { 15532 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15533 } 15534 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15535 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15536 false /*hidden*/, false /*suspended*/, null, null, null, 15537 false /*blockUninstall*/, 15538 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15539 } 15540 } 15541 15542 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15543 PackageRemovedInfo outInfo) { 15544 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15545 : new int[] {userId}; 15546 for (int nextUserId : userIds) { 15547 if (DEBUG_REMOVE) { 15548 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15549 + nextUserId); 15550 } 15551 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15552 try { 15553 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15554 } catch (InstallerException e) { 15555 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15556 return false; 15557 } 15558 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15559 schedulePackageCleaning(ps.name, nextUserId, false); 15560 synchronized (mPackages) { 15561 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15562 scheduleWritePackageRestrictionsLocked(nextUserId); 15563 } 15564 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15565 } 15566 } 15567 15568 if (outInfo != null) { 15569 outInfo.removedPackage = ps.name; 15570 outInfo.removedAppId = ps.appId; 15571 outInfo.removedUsers = userIds; 15572 } 15573 15574 return true; 15575 } 15576 15577 private final class ClearStorageConnection implements ServiceConnection { 15578 IMediaContainerService mContainerService; 15579 15580 @Override 15581 public void onServiceConnected(ComponentName name, IBinder service) { 15582 synchronized (this) { 15583 mContainerService = IMediaContainerService.Stub.asInterface(service); 15584 notifyAll(); 15585 } 15586 } 15587 15588 @Override 15589 public void onServiceDisconnected(ComponentName name) { 15590 } 15591 } 15592 15593 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15594 final boolean mounted; 15595 if (Environment.isExternalStorageEmulated()) { 15596 mounted = true; 15597 } else { 15598 final String status = Environment.getExternalStorageState(); 15599 15600 mounted = status.equals(Environment.MEDIA_MOUNTED) 15601 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15602 } 15603 15604 if (!mounted) { 15605 return; 15606 } 15607 15608 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15609 int[] users; 15610 if (userId == UserHandle.USER_ALL) { 15611 users = sUserManager.getUserIds(); 15612 } else { 15613 users = new int[] { userId }; 15614 } 15615 final ClearStorageConnection conn = new ClearStorageConnection(); 15616 if (mContext.bindServiceAsUser( 15617 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15618 try { 15619 for (int curUser : users) { 15620 long timeout = SystemClock.uptimeMillis() + 5000; 15621 synchronized (conn) { 15622 long now = SystemClock.uptimeMillis(); 15623 while (conn.mContainerService == null && now < timeout) { 15624 try { 15625 conn.wait(timeout - now); 15626 } catch (InterruptedException e) { 15627 } 15628 } 15629 } 15630 if (conn.mContainerService == null) { 15631 return; 15632 } 15633 15634 final UserEnvironment userEnv = new UserEnvironment(curUser); 15635 clearDirectory(conn.mContainerService, 15636 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15637 if (allData) { 15638 clearDirectory(conn.mContainerService, 15639 userEnv.buildExternalStorageAppDataDirs(packageName)); 15640 clearDirectory(conn.mContainerService, 15641 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15642 } 15643 } 15644 } finally { 15645 mContext.unbindService(conn); 15646 } 15647 } 15648 } 15649 15650 @Override 15651 public void clearApplicationProfileData(String packageName) { 15652 enforceSystemOrRoot("Only the system can clear all profile data"); 15653 try { 15654 mInstaller.clearAppProfiles(packageName); 15655 } catch (InstallerException ex) { 15656 Log.e(TAG, "Could not clear profile data of package " + packageName); 15657 } 15658 } 15659 15660 @Override 15661 public void clearApplicationUserData(final String packageName, 15662 final IPackageDataObserver observer, final int userId) { 15663 mContext.enforceCallingOrSelfPermission( 15664 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15665 15666 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15667 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15668 15669 final DevicePolicyManagerInternal dpmi = LocalServices 15670 .getService(DevicePolicyManagerInternal.class); 15671 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15672 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15673 } 15674 // Queue up an async operation since the package deletion may take a little while. 15675 mHandler.post(new Runnable() { 15676 public void run() { 15677 mHandler.removeCallbacks(this); 15678 final boolean succeeded; 15679 synchronized (mInstallLock) { 15680 succeeded = clearApplicationUserDataLI(packageName, userId); 15681 } 15682 clearExternalStorageDataSync(packageName, userId, true); 15683 if (succeeded) { 15684 // invoke DeviceStorageMonitor's update method to clear any notifications 15685 DeviceStorageMonitorInternal dsm = LocalServices 15686 .getService(DeviceStorageMonitorInternal.class); 15687 if (dsm != null) { 15688 dsm.checkMemory(); 15689 } 15690 } 15691 if(observer != null) { 15692 try { 15693 observer.onRemoveCompleted(packageName, succeeded); 15694 } catch (RemoteException e) { 15695 Log.i(TAG, "Observer no longer exists."); 15696 } 15697 } //end if observer 15698 } //end run 15699 }); 15700 } 15701 15702 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15703 if (packageName == null) { 15704 Slog.w(TAG, "Attempt to delete null packageName."); 15705 return false; 15706 } 15707 15708 // Try finding details about the requested package 15709 PackageParser.Package pkg; 15710 synchronized (mPackages) { 15711 pkg = mPackages.get(packageName); 15712 if (pkg == null) { 15713 final PackageSetting ps = mSettings.mPackages.get(packageName); 15714 if (ps != null) { 15715 pkg = ps.pkg; 15716 } 15717 } 15718 15719 if (pkg == null) { 15720 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15721 return false; 15722 } 15723 15724 PackageSetting ps = (PackageSetting) pkg.mExtras; 15725 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15726 } 15727 15728 // Always delete data directories for package, even if we found no other 15729 // record of app. This helps users recover from UID mismatches without 15730 // resorting to a full data wipe. 15731 // TODO: triage flags as part of 26466827 15732 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15733 try { 15734 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15735 } catch (InstallerException e) { 15736 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15737 return false; 15738 } 15739 15740 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15741 removeKeystoreDataIfNeeded(userId, appId); 15742 15743 // Create a native library symlink only if we have native libraries 15744 // and if the native libraries are 32 bit libraries. We do not provide 15745 // this symlink for 64 bit libraries. 15746 if (pkg.applicationInfo.primaryCpuAbi != null && 15747 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15748 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15749 try { 15750 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15751 nativeLibPath, userId); 15752 } catch (InstallerException e) { 15753 Slog.w(TAG, "Failed linking native library dir", e); 15754 return false; 15755 } 15756 } 15757 15758 return true; 15759 } 15760 15761 /** 15762 * Reverts user permission state changes (permissions and flags) in 15763 * all packages for a given user. 15764 * 15765 * @param userId The device user for which to do a reset. 15766 */ 15767 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15768 final int packageCount = mPackages.size(); 15769 for (int i = 0; i < packageCount; i++) { 15770 PackageParser.Package pkg = mPackages.valueAt(i); 15771 PackageSetting ps = (PackageSetting) pkg.mExtras; 15772 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15773 } 15774 } 15775 15776 /** 15777 * Reverts user permission state changes (permissions and flags). 15778 * 15779 * @param ps The package for which to reset. 15780 * @param userId The device user for which to do a reset. 15781 */ 15782 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15783 final PackageSetting ps, final int userId) { 15784 if (ps.pkg == null) { 15785 return; 15786 } 15787 15788 // These are flags that can change base on user actions. 15789 final int userSettableMask = FLAG_PERMISSION_USER_SET 15790 | FLAG_PERMISSION_USER_FIXED 15791 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15792 | FLAG_PERMISSION_REVIEW_REQUIRED; 15793 15794 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15795 | FLAG_PERMISSION_POLICY_FIXED; 15796 15797 boolean writeInstallPermissions = false; 15798 boolean writeRuntimePermissions = false; 15799 15800 final int permissionCount = ps.pkg.requestedPermissions.size(); 15801 for (int i = 0; i < permissionCount; i++) { 15802 String permission = ps.pkg.requestedPermissions.get(i); 15803 15804 BasePermission bp = mSettings.mPermissions.get(permission); 15805 if (bp == null) { 15806 continue; 15807 } 15808 15809 // If shared user we just reset the state to which only this app contributed. 15810 if (ps.sharedUser != null) { 15811 boolean used = false; 15812 final int packageCount = ps.sharedUser.packages.size(); 15813 for (int j = 0; j < packageCount; j++) { 15814 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15815 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15816 && pkg.pkg.requestedPermissions.contains(permission)) { 15817 used = true; 15818 break; 15819 } 15820 } 15821 if (used) { 15822 continue; 15823 } 15824 } 15825 15826 PermissionsState permissionsState = ps.getPermissionsState(); 15827 15828 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15829 15830 // Always clear the user settable flags. 15831 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15832 bp.name) != null; 15833 // If permission review is enabled and this is a legacy app, mark the 15834 // permission as requiring a review as this is the initial state. 15835 int flags = 0; 15836 if (Build.PERMISSIONS_REVIEW_REQUIRED 15837 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15838 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15839 } 15840 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15841 if (hasInstallState) { 15842 writeInstallPermissions = true; 15843 } else { 15844 writeRuntimePermissions = true; 15845 } 15846 } 15847 15848 // Below is only runtime permission handling. 15849 if (!bp.isRuntime()) { 15850 continue; 15851 } 15852 15853 // Never clobber system or policy. 15854 if ((oldFlags & policyOrSystemFlags) != 0) { 15855 continue; 15856 } 15857 15858 // If this permission was granted by default, make sure it is. 15859 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15860 if (permissionsState.grantRuntimePermission(bp, userId) 15861 != PERMISSION_OPERATION_FAILURE) { 15862 writeRuntimePermissions = true; 15863 } 15864 // If permission review is enabled the permissions for a legacy apps 15865 // are represented as constantly granted runtime ones, so don't revoke. 15866 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15867 // Otherwise, reset the permission. 15868 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15869 switch (revokeResult) { 15870 case PERMISSION_OPERATION_SUCCESS: 15871 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15872 writeRuntimePermissions = true; 15873 final int appId = ps.appId; 15874 mHandler.post(new Runnable() { 15875 @Override 15876 public void run() { 15877 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15878 } 15879 }); 15880 } break; 15881 } 15882 } 15883 } 15884 15885 // Synchronously write as we are taking permissions away. 15886 if (writeRuntimePermissions) { 15887 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15888 } 15889 15890 // Synchronously write as we are taking permissions away. 15891 if (writeInstallPermissions) { 15892 mSettings.writeLPr(); 15893 } 15894 } 15895 15896 /** 15897 * Remove entries from the keystore daemon. Will only remove it if the 15898 * {@code appId} is valid. 15899 */ 15900 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15901 if (appId < 0) { 15902 return; 15903 } 15904 15905 final KeyStore keyStore = KeyStore.getInstance(); 15906 if (keyStore != null) { 15907 if (userId == UserHandle.USER_ALL) { 15908 for (final int individual : sUserManager.getUserIds()) { 15909 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15910 } 15911 } else { 15912 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15913 } 15914 } else { 15915 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15916 } 15917 } 15918 15919 @Override 15920 public void deleteApplicationCacheFiles(final String packageName, 15921 final IPackageDataObserver observer) { 15922 mContext.enforceCallingOrSelfPermission( 15923 android.Manifest.permission.DELETE_CACHE_FILES, null); 15924 // Queue up an async operation since the package deletion may take a little while. 15925 final int userId = UserHandle.getCallingUserId(); 15926 mHandler.post(new Runnable() { 15927 public void run() { 15928 mHandler.removeCallbacks(this); 15929 final boolean succeded; 15930 synchronized (mInstallLock) { 15931 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15932 } 15933 clearExternalStorageDataSync(packageName, userId, false); 15934 if (observer != null) { 15935 try { 15936 observer.onRemoveCompleted(packageName, succeded); 15937 } catch (RemoteException e) { 15938 Log.i(TAG, "Observer no longer exists."); 15939 } 15940 } //end if observer 15941 } //end run 15942 }); 15943 } 15944 15945 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15946 if (packageName == null) { 15947 Slog.w(TAG, "Attempt to delete null packageName."); 15948 return false; 15949 } 15950 PackageParser.Package p; 15951 synchronized (mPackages) { 15952 p = mPackages.get(packageName); 15953 } 15954 if (p == null) { 15955 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15956 return false; 15957 } 15958 final ApplicationInfo applicationInfo = p.applicationInfo; 15959 if (applicationInfo == null) { 15960 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15961 return false; 15962 } 15963 // TODO: triage flags as part of 26466827 15964 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15965 try { 15966 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15967 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15968 } catch (InstallerException e) { 15969 Slog.w(TAG, "Couldn't remove cache files for package " 15970 + packageName + " u" + userId, e); 15971 return false; 15972 } 15973 return true; 15974 } 15975 15976 @Override 15977 public void getPackageSizeInfo(final String packageName, int userHandle, 15978 final IPackageStatsObserver observer) { 15979 mContext.enforceCallingOrSelfPermission( 15980 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15981 if (packageName == null) { 15982 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15983 } 15984 15985 PackageStats stats = new PackageStats(packageName, userHandle); 15986 15987 /* 15988 * Queue up an async operation since the package measurement may take a 15989 * little while. 15990 */ 15991 Message msg = mHandler.obtainMessage(INIT_COPY); 15992 msg.obj = new MeasureParams(stats, observer); 15993 mHandler.sendMessage(msg); 15994 } 15995 15996 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15997 PackageStats pStats) { 15998 if (packageName == null) { 15999 Slog.w(TAG, "Attempt to get size of null packageName."); 16000 return false; 16001 } 16002 PackageParser.Package p; 16003 boolean dataOnly = false; 16004 String libDirRoot = null; 16005 String asecPath = null; 16006 PackageSetting ps = null; 16007 synchronized (mPackages) { 16008 p = mPackages.get(packageName); 16009 ps = mSettings.mPackages.get(packageName); 16010 if(p == null) { 16011 dataOnly = true; 16012 if((ps == null) || (ps.pkg == null)) { 16013 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 16014 return false; 16015 } 16016 p = ps.pkg; 16017 } 16018 if (ps != null) { 16019 libDirRoot = ps.legacyNativeLibraryPathString; 16020 } 16021 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 16022 final long token = Binder.clearCallingIdentity(); 16023 try { 16024 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 16025 if (secureContainerId != null) { 16026 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 16027 } 16028 } finally { 16029 Binder.restoreCallingIdentity(token); 16030 } 16031 } 16032 } 16033 String publicSrcDir = null; 16034 if(!dataOnly) { 16035 final ApplicationInfo applicationInfo = p.applicationInfo; 16036 if (applicationInfo == null) { 16037 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 16038 return false; 16039 } 16040 if (p.isForwardLocked()) { 16041 publicSrcDir = applicationInfo.getBaseResourcePath(); 16042 } 16043 } 16044 // TODO: extend to measure size of split APKs 16045 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 16046 // not just the first level. 16047 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 16048 // just the primary. 16049 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 16050 16051 String apkPath; 16052 File packageDir = new File(p.codePath); 16053 16054 if (packageDir.isDirectory() && p.canHaveOatDir()) { 16055 apkPath = packageDir.getAbsolutePath(); 16056 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 16057 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 16058 libDirRoot = null; 16059 } 16060 } else { 16061 apkPath = p.baseCodePath; 16062 } 16063 16064 // TODO: triage flags as part of 26466827 16065 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 16066 try { 16067 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 16068 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 16069 } catch (InstallerException e) { 16070 return false; 16071 } 16072 16073 // Fix-up for forward-locked applications in ASEC containers. 16074 if (!isExternal(p)) { 16075 pStats.codeSize += pStats.externalCodeSize; 16076 pStats.externalCodeSize = 0L; 16077 } 16078 16079 return true; 16080 } 16081 16082 private int getUidTargetSdkVersionLockedLPr(int uid) { 16083 Object obj = mSettings.getUserIdLPr(uid); 16084 if (obj instanceof SharedUserSetting) { 16085 final SharedUserSetting sus = (SharedUserSetting) obj; 16086 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16087 final Iterator<PackageSetting> it = sus.packages.iterator(); 16088 while (it.hasNext()) { 16089 final PackageSetting ps = it.next(); 16090 if (ps.pkg != null) { 16091 int v = ps.pkg.applicationInfo.targetSdkVersion; 16092 if (v < vers) vers = v; 16093 } 16094 } 16095 return vers; 16096 } else if (obj instanceof PackageSetting) { 16097 final PackageSetting ps = (PackageSetting) obj; 16098 if (ps.pkg != null) { 16099 return ps.pkg.applicationInfo.targetSdkVersion; 16100 } 16101 } 16102 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16103 } 16104 16105 @Override 16106 public void addPreferredActivity(IntentFilter filter, int match, 16107 ComponentName[] set, ComponentName activity, int userId) { 16108 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16109 "Adding preferred"); 16110 } 16111 16112 private void addPreferredActivityInternal(IntentFilter filter, int match, 16113 ComponentName[] set, ComponentName activity, boolean always, int userId, 16114 String opname) { 16115 // writer 16116 int callingUid = Binder.getCallingUid(); 16117 enforceCrossUserPermission(callingUid, userId, 16118 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16119 if (filter.countActions() == 0) { 16120 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16121 return; 16122 } 16123 synchronized (mPackages) { 16124 if (mContext.checkCallingOrSelfPermission( 16125 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16126 != PackageManager.PERMISSION_GRANTED) { 16127 if (getUidTargetSdkVersionLockedLPr(callingUid) 16128 < Build.VERSION_CODES.FROYO) { 16129 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16130 + callingUid); 16131 return; 16132 } 16133 mContext.enforceCallingOrSelfPermission( 16134 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16135 } 16136 16137 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16138 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16139 + userId + ":"); 16140 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16141 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16142 scheduleWritePackageRestrictionsLocked(userId); 16143 } 16144 } 16145 16146 @Override 16147 public void replacePreferredActivity(IntentFilter filter, int match, 16148 ComponentName[] set, ComponentName activity, int userId) { 16149 if (filter.countActions() != 1) { 16150 throw new IllegalArgumentException( 16151 "replacePreferredActivity expects filter to have only 1 action."); 16152 } 16153 if (filter.countDataAuthorities() != 0 16154 || filter.countDataPaths() != 0 16155 || filter.countDataSchemes() > 1 16156 || filter.countDataTypes() != 0) { 16157 throw new IllegalArgumentException( 16158 "replacePreferredActivity expects filter to have no data authorities, " + 16159 "paths, or types; and at most one scheme."); 16160 } 16161 16162 final int callingUid = Binder.getCallingUid(); 16163 enforceCrossUserPermission(callingUid, userId, 16164 true /* requireFullPermission */, false /* checkShell */, 16165 "replace preferred activity"); 16166 synchronized (mPackages) { 16167 if (mContext.checkCallingOrSelfPermission( 16168 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16169 != PackageManager.PERMISSION_GRANTED) { 16170 if (getUidTargetSdkVersionLockedLPr(callingUid) 16171 < Build.VERSION_CODES.FROYO) { 16172 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16173 + Binder.getCallingUid()); 16174 return; 16175 } 16176 mContext.enforceCallingOrSelfPermission( 16177 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16178 } 16179 16180 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16181 if (pir != null) { 16182 // Get all of the existing entries that exactly match this filter. 16183 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16184 if (existing != null && existing.size() == 1) { 16185 PreferredActivity cur = existing.get(0); 16186 if (DEBUG_PREFERRED) { 16187 Slog.i(TAG, "Checking replace of preferred:"); 16188 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16189 if (!cur.mPref.mAlways) { 16190 Slog.i(TAG, " -- CUR; not mAlways!"); 16191 } else { 16192 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16193 Slog.i(TAG, " -- CUR: mSet=" 16194 + Arrays.toString(cur.mPref.mSetComponents)); 16195 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16196 Slog.i(TAG, " -- NEW: mMatch=" 16197 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16198 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16199 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16200 } 16201 } 16202 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16203 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16204 && cur.mPref.sameSet(set)) { 16205 // Setting the preferred activity to what it happens to be already 16206 if (DEBUG_PREFERRED) { 16207 Slog.i(TAG, "Replacing with same preferred activity " 16208 + cur.mPref.mShortComponent + " for user " 16209 + userId + ":"); 16210 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16211 } 16212 return; 16213 } 16214 } 16215 16216 if (existing != null) { 16217 if (DEBUG_PREFERRED) { 16218 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16219 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16220 } 16221 for (int i = 0; i < existing.size(); i++) { 16222 PreferredActivity pa = existing.get(i); 16223 if (DEBUG_PREFERRED) { 16224 Slog.i(TAG, "Removing existing preferred activity " 16225 + pa.mPref.mComponent + ":"); 16226 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16227 } 16228 pir.removeFilter(pa); 16229 } 16230 } 16231 } 16232 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16233 "Replacing preferred"); 16234 } 16235 } 16236 16237 @Override 16238 public void clearPackagePreferredActivities(String packageName) { 16239 final int uid = Binder.getCallingUid(); 16240 // writer 16241 synchronized (mPackages) { 16242 PackageParser.Package pkg = mPackages.get(packageName); 16243 if (pkg == null || pkg.applicationInfo.uid != uid) { 16244 if (mContext.checkCallingOrSelfPermission( 16245 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16246 != PackageManager.PERMISSION_GRANTED) { 16247 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16248 < Build.VERSION_CODES.FROYO) { 16249 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16250 + Binder.getCallingUid()); 16251 return; 16252 } 16253 mContext.enforceCallingOrSelfPermission( 16254 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16255 } 16256 } 16257 16258 int user = UserHandle.getCallingUserId(); 16259 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16260 scheduleWritePackageRestrictionsLocked(user); 16261 } 16262 } 16263 } 16264 16265 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16266 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16267 ArrayList<PreferredActivity> removed = null; 16268 boolean changed = false; 16269 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16270 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16271 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16272 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16273 continue; 16274 } 16275 Iterator<PreferredActivity> it = pir.filterIterator(); 16276 while (it.hasNext()) { 16277 PreferredActivity pa = it.next(); 16278 // Mark entry for removal only if it matches the package name 16279 // and the entry is of type "always". 16280 if (packageName == null || 16281 (pa.mPref.mComponent.getPackageName().equals(packageName) 16282 && pa.mPref.mAlways)) { 16283 if (removed == null) { 16284 removed = new ArrayList<PreferredActivity>(); 16285 } 16286 removed.add(pa); 16287 } 16288 } 16289 if (removed != null) { 16290 for (int j=0; j<removed.size(); j++) { 16291 PreferredActivity pa = removed.get(j); 16292 pir.removeFilter(pa); 16293 } 16294 changed = true; 16295 } 16296 } 16297 return changed; 16298 } 16299 16300 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16301 private void clearIntentFilterVerificationsLPw(int userId) { 16302 final int packageCount = mPackages.size(); 16303 for (int i = 0; i < packageCount; i++) { 16304 PackageParser.Package pkg = mPackages.valueAt(i); 16305 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16306 } 16307 } 16308 16309 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16310 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16311 if (userId == UserHandle.USER_ALL) { 16312 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16313 sUserManager.getUserIds())) { 16314 for (int oneUserId : sUserManager.getUserIds()) { 16315 scheduleWritePackageRestrictionsLocked(oneUserId); 16316 } 16317 } 16318 } else { 16319 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16320 scheduleWritePackageRestrictionsLocked(userId); 16321 } 16322 } 16323 } 16324 16325 void clearDefaultBrowserIfNeeded(String packageName) { 16326 for (int oneUserId : sUserManager.getUserIds()) { 16327 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16328 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16329 if (packageName.equals(defaultBrowserPackageName)) { 16330 setDefaultBrowserPackageName(null, oneUserId); 16331 } 16332 } 16333 } 16334 16335 @Override 16336 public void resetApplicationPreferences(int userId) { 16337 mContext.enforceCallingOrSelfPermission( 16338 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16339 // writer 16340 synchronized (mPackages) { 16341 final long identity = Binder.clearCallingIdentity(); 16342 try { 16343 clearPackagePreferredActivitiesLPw(null, userId); 16344 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16345 // TODO: We have to reset the default SMS and Phone. This requires 16346 // significant refactoring to keep all default apps in the package 16347 // manager (cleaner but more work) or have the services provide 16348 // callbacks to the package manager to request a default app reset. 16349 applyFactoryDefaultBrowserLPw(userId); 16350 clearIntentFilterVerificationsLPw(userId); 16351 primeDomainVerificationsLPw(userId); 16352 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16353 scheduleWritePackageRestrictionsLocked(userId); 16354 } finally { 16355 Binder.restoreCallingIdentity(identity); 16356 } 16357 } 16358 } 16359 16360 @Override 16361 public int getPreferredActivities(List<IntentFilter> outFilters, 16362 List<ComponentName> outActivities, String packageName) { 16363 16364 int num = 0; 16365 final int userId = UserHandle.getCallingUserId(); 16366 // reader 16367 synchronized (mPackages) { 16368 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16369 if (pir != null) { 16370 final Iterator<PreferredActivity> it = pir.filterIterator(); 16371 while (it.hasNext()) { 16372 final PreferredActivity pa = it.next(); 16373 if (packageName == null 16374 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16375 && pa.mPref.mAlways)) { 16376 if (outFilters != null) { 16377 outFilters.add(new IntentFilter(pa)); 16378 } 16379 if (outActivities != null) { 16380 outActivities.add(pa.mPref.mComponent); 16381 } 16382 } 16383 } 16384 } 16385 } 16386 16387 return num; 16388 } 16389 16390 @Override 16391 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16392 int userId) { 16393 int callingUid = Binder.getCallingUid(); 16394 if (callingUid != Process.SYSTEM_UID) { 16395 throw new SecurityException( 16396 "addPersistentPreferredActivity can only be run by the system"); 16397 } 16398 if (filter.countActions() == 0) { 16399 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16400 return; 16401 } 16402 synchronized (mPackages) { 16403 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16404 ":"); 16405 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16406 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16407 new PersistentPreferredActivity(filter, activity)); 16408 scheduleWritePackageRestrictionsLocked(userId); 16409 } 16410 } 16411 16412 @Override 16413 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16414 int callingUid = Binder.getCallingUid(); 16415 if (callingUid != Process.SYSTEM_UID) { 16416 throw new SecurityException( 16417 "clearPackagePersistentPreferredActivities can only be run by the system"); 16418 } 16419 ArrayList<PersistentPreferredActivity> removed = null; 16420 boolean changed = false; 16421 synchronized (mPackages) { 16422 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16423 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16424 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16425 .valueAt(i); 16426 if (userId != thisUserId) { 16427 continue; 16428 } 16429 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16430 while (it.hasNext()) { 16431 PersistentPreferredActivity ppa = it.next(); 16432 // Mark entry for removal only if it matches the package name. 16433 if (ppa.mComponent.getPackageName().equals(packageName)) { 16434 if (removed == null) { 16435 removed = new ArrayList<PersistentPreferredActivity>(); 16436 } 16437 removed.add(ppa); 16438 } 16439 } 16440 if (removed != null) { 16441 for (int j=0; j<removed.size(); j++) { 16442 PersistentPreferredActivity ppa = removed.get(j); 16443 ppir.removeFilter(ppa); 16444 } 16445 changed = true; 16446 } 16447 } 16448 16449 if (changed) { 16450 scheduleWritePackageRestrictionsLocked(userId); 16451 } 16452 } 16453 } 16454 16455 /** 16456 * Common machinery for picking apart a restored XML blob and passing 16457 * it to a caller-supplied functor to be applied to the running system. 16458 */ 16459 private void restoreFromXml(XmlPullParser parser, int userId, 16460 String expectedStartTag, BlobXmlRestorer functor) 16461 throws IOException, XmlPullParserException { 16462 int type; 16463 while ((type = parser.next()) != XmlPullParser.START_TAG 16464 && type != XmlPullParser.END_DOCUMENT) { 16465 } 16466 if (type != XmlPullParser.START_TAG) { 16467 // oops didn't find a start tag?! 16468 if (DEBUG_BACKUP) { 16469 Slog.e(TAG, "Didn't find start tag during restore"); 16470 } 16471 return; 16472 } 16473Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16474 // this is supposed to be TAG_PREFERRED_BACKUP 16475 if (!expectedStartTag.equals(parser.getName())) { 16476 if (DEBUG_BACKUP) { 16477 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16478 } 16479 return; 16480 } 16481 16482 // skip interfering stuff, then we're aligned with the backing implementation 16483 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16484Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16485 functor.apply(parser, userId); 16486 } 16487 16488 private interface BlobXmlRestorer { 16489 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16490 } 16491 16492 /** 16493 * Non-Binder method, support for the backup/restore mechanism: write the 16494 * full set of preferred activities in its canonical XML format. Returns the 16495 * XML output as a byte array, or null if there is none. 16496 */ 16497 @Override 16498 public byte[] getPreferredActivityBackup(int userId) { 16499 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16500 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16501 } 16502 16503 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16504 try { 16505 final XmlSerializer serializer = new FastXmlSerializer(); 16506 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16507 serializer.startDocument(null, true); 16508 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16509 16510 synchronized (mPackages) { 16511 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16512 } 16513 16514 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16515 serializer.endDocument(); 16516 serializer.flush(); 16517 } catch (Exception e) { 16518 if (DEBUG_BACKUP) { 16519 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16520 } 16521 return null; 16522 } 16523 16524 return dataStream.toByteArray(); 16525 } 16526 16527 @Override 16528 public void restorePreferredActivities(byte[] backup, int userId) { 16529 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16530 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16531 } 16532 16533 try { 16534 final XmlPullParser parser = Xml.newPullParser(); 16535 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16536 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16537 new BlobXmlRestorer() { 16538 @Override 16539 public void apply(XmlPullParser parser, int userId) 16540 throws XmlPullParserException, IOException { 16541 synchronized (mPackages) { 16542 mSettings.readPreferredActivitiesLPw(parser, userId); 16543 } 16544 } 16545 } ); 16546 } catch (Exception e) { 16547 if (DEBUG_BACKUP) { 16548 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16549 } 16550 } 16551 } 16552 16553 /** 16554 * Non-Binder method, support for the backup/restore mechanism: write the 16555 * default browser (etc) settings in its canonical XML format. Returns the default 16556 * browser XML representation as a byte array, or null if there is none. 16557 */ 16558 @Override 16559 public byte[] getDefaultAppsBackup(int userId) { 16560 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16561 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16562 } 16563 16564 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16565 try { 16566 final XmlSerializer serializer = new FastXmlSerializer(); 16567 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16568 serializer.startDocument(null, true); 16569 serializer.startTag(null, TAG_DEFAULT_APPS); 16570 16571 synchronized (mPackages) { 16572 mSettings.writeDefaultAppsLPr(serializer, userId); 16573 } 16574 16575 serializer.endTag(null, TAG_DEFAULT_APPS); 16576 serializer.endDocument(); 16577 serializer.flush(); 16578 } catch (Exception e) { 16579 if (DEBUG_BACKUP) { 16580 Slog.e(TAG, "Unable to write default apps for backup", e); 16581 } 16582 return null; 16583 } 16584 16585 return dataStream.toByteArray(); 16586 } 16587 16588 @Override 16589 public void restoreDefaultApps(byte[] backup, int userId) { 16590 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16591 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16592 } 16593 16594 try { 16595 final XmlPullParser parser = Xml.newPullParser(); 16596 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16597 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16598 new BlobXmlRestorer() { 16599 @Override 16600 public void apply(XmlPullParser parser, int userId) 16601 throws XmlPullParserException, IOException { 16602 synchronized (mPackages) { 16603 mSettings.readDefaultAppsLPw(parser, userId); 16604 } 16605 } 16606 } ); 16607 } catch (Exception e) { 16608 if (DEBUG_BACKUP) { 16609 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16610 } 16611 } 16612 } 16613 16614 @Override 16615 public byte[] getIntentFilterVerificationBackup(int userId) { 16616 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16617 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16618 } 16619 16620 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16621 try { 16622 final XmlSerializer serializer = new FastXmlSerializer(); 16623 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16624 serializer.startDocument(null, true); 16625 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16626 16627 synchronized (mPackages) { 16628 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16629 } 16630 16631 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16632 serializer.endDocument(); 16633 serializer.flush(); 16634 } catch (Exception e) { 16635 if (DEBUG_BACKUP) { 16636 Slog.e(TAG, "Unable to write default apps for backup", e); 16637 } 16638 return null; 16639 } 16640 16641 return dataStream.toByteArray(); 16642 } 16643 16644 @Override 16645 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16646 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16647 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16648 } 16649 16650 try { 16651 final XmlPullParser parser = Xml.newPullParser(); 16652 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16653 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16654 new BlobXmlRestorer() { 16655 @Override 16656 public void apply(XmlPullParser parser, int userId) 16657 throws XmlPullParserException, IOException { 16658 synchronized (mPackages) { 16659 mSettings.readAllDomainVerificationsLPr(parser, userId); 16660 mSettings.writeLPr(); 16661 } 16662 } 16663 } ); 16664 } catch (Exception e) { 16665 if (DEBUG_BACKUP) { 16666 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16667 } 16668 } 16669 } 16670 16671 @Override 16672 public byte[] getPermissionGrantBackup(int userId) { 16673 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16674 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16675 } 16676 16677 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16678 try { 16679 final XmlSerializer serializer = new FastXmlSerializer(); 16680 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16681 serializer.startDocument(null, true); 16682 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16683 16684 synchronized (mPackages) { 16685 serializeRuntimePermissionGrantsLPr(serializer, userId); 16686 } 16687 16688 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16689 serializer.endDocument(); 16690 serializer.flush(); 16691 } catch (Exception e) { 16692 if (DEBUG_BACKUP) { 16693 Slog.e(TAG, "Unable to write default apps for backup", e); 16694 } 16695 return null; 16696 } 16697 16698 return dataStream.toByteArray(); 16699 } 16700 16701 @Override 16702 public void restorePermissionGrants(byte[] backup, int userId) { 16703 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16704 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16705 } 16706 16707 try { 16708 final XmlPullParser parser = Xml.newPullParser(); 16709 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16710 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16711 new BlobXmlRestorer() { 16712 @Override 16713 public void apply(XmlPullParser parser, int userId) 16714 throws XmlPullParserException, IOException { 16715 synchronized (mPackages) { 16716 processRestoredPermissionGrantsLPr(parser, userId); 16717 } 16718 } 16719 } ); 16720 } catch (Exception e) { 16721 if (DEBUG_BACKUP) { 16722 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16723 } 16724 } 16725 } 16726 16727 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16728 throws IOException { 16729 serializer.startTag(null, TAG_ALL_GRANTS); 16730 16731 final int N = mSettings.mPackages.size(); 16732 for (int i = 0; i < N; i++) { 16733 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16734 boolean pkgGrantsKnown = false; 16735 16736 PermissionsState packagePerms = ps.getPermissionsState(); 16737 16738 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16739 final int grantFlags = state.getFlags(); 16740 // only look at grants that are not system/policy fixed 16741 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16742 final boolean isGranted = state.isGranted(); 16743 // And only back up the user-twiddled state bits 16744 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16745 final String packageName = mSettings.mPackages.keyAt(i); 16746 if (!pkgGrantsKnown) { 16747 serializer.startTag(null, TAG_GRANT); 16748 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16749 pkgGrantsKnown = true; 16750 } 16751 16752 final boolean userSet = 16753 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16754 final boolean userFixed = 16755 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16756 final boolean revoke = 16757 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16758 16759 serializer.startTag(null, TAG_PERMISSION); 16760 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16761 if (isGranted) { 16762 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16763 } 16764 if (userSet) { 16765 serializer.attribute(null, ATTR_USER_SET, "true"); 16766 } 16767 if (userFixed) { 16768 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16769 } 16770 if (revoke) { 16771 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16772 } 16773 serializer.endTag(null, TAG_PERMISSION); 16774 } 16775 } 16776 } 16777 16778 if (pkgGrantsKnown) { 16779 serializer.endTag(null, TAG_GRANT); 16780 } 16781 } 16782 16783 serializer.endTag(null, TAG_ALL_GRANTS); 16784 } 16785 16786 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16787 throws XmlPullParserException, IOException { 16788 String pkgName = null; 16789 int outerDepth = parser.getDepth(); 16790 int type; 16791 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16792 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16793 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16794 continue; 16795 } 16796 16797 final String tagName = parser.getName(); 16798 if (tagName.equals(TAG_GRANT)) { 16799 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16800 if (DEBUG_BACKUP) { 16801 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16802 } 16803 } else if (tagName.equals(TAG_PERMISSION)) { 16804 16805 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16806 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16807 16808 int newFlagSet = 0; 16809 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16810 newFlagSet |= FLAG_PERMISSION_USER_SET; 16811 } 16812 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16813 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16814 } 16815 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16816 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16817 } 16818 if (DEBUG_BACKUP) { 16819 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16820 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16821 } 16822 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16823 if (ps != null) { 16824 // Already installed so we apply the grant immediately 16825 if (DEBUG_BACKUP) { 16826 Slog.v(TAG, " + already installed; applying"); 16827 } 16828 PermissionsState perms = ps.getPermissionsState(); 16829 BasePermission bp = mSettings.mPermissions.get(permName); 16830 if (bp != null) { 16831 if (isGranted) { 16832 perms.grantRuntimePermission(bp, userId); 16833 } 16834 if (newFlagSet != 0) { 16835 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16836 } 16837 } 16838 } else { 16839 // Need to wait for post-restore install to apply the grant 16840 if (DEBUG_BACKUP) { 16841 Slog.v(TAG, " - not yet installed; saving for later"); 16842 } 16843 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16844 isGranted, newFlagSet, userId); 16845 } 16846 } else { 16847 PackageManagerService.reportSettingsProblem(Log.WARN, 16848 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16849 XmlUtils.skipCurrentTag(parser); 16850 } 16851 } 16852 16853 scheduleWriteSettingsLocked(); 16854 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16855 } 16856 16857 @Override 16858 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16859 int sourceUserId, int targetUserId, int flags) { 16860 mContext.enforceCallingOrSelfPermission( 16861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16862 int callingUid = Binder.getCallingUid(); 16863 enforceOwnerRights(ownerPackage, callingUid); 16864 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16865 if (intentFilter.countActions() == 0) { 16866 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16867 return; 16868 } 16869 synchronized (mPackages) { 16870 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16871 ownerPackage, targetUserId, flags); 16872 CrossProfileIntentResolver resolver = 16873 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16874 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16875 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16876 if (existing != null) { 16877 int size = existing.size(); 16878 for (int i = 0; i < size; i++) { 16879 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16880 return; 16881 } 16882 } 16883 } 16884 resolver.addFilter(newFilter); 16885 scheduleWritePackageRestrictionsLocked(sourceUserId); 16886 } 16887 } 16888 16889 @Override 16890 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16891 mContext.enforceCallingOrSelfPermission( 16892 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16893 int callingUid = Binder.getCallingUid(); 16894 enforceOwnerRights(ownerPackage, callingUid); 16895 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16896 synchronized (mPackages) { 16897 CrossProfileIntentResolver resolver = 16898 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16899 ArraySet<CrossProfileIntentFilter> set = 16900 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16901 for (CrossProfileIntentFilter filter : set) { 16902 if (filter.getOwnerPackage().equals(ownerPackage)) { 16903 resolver.removeFilter(filter); 16904 } 16905 } 16906 scheduleWritePackageRestrictionsLocked(sourceUserId); 16907 } 16908 } 16909 16910 // Enforcing that callingUid is owning pkg on userId 16911 private void enforceOwnerRights(String pkg, int callingUid) { 16912 // The system owns everything. 16913 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16914 return; 16915 } 16916 int callingUserId = UserHandle.getUserId(callingUid); 16917 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16918 if (pi == null) { 16919 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16920 + callingUserId); 16921 } 16922 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16923 throw new SecurityException("Calling uid " + callingUid 16924 + " does not own package " + pkg); 16925 } 16926 } 16927 16928 @Override 16929 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16930 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16931 } 16932 16933 private Intent getHomeIntent() { 16934 Intent intent = new Intent(Intent.ACTION_MAIN); 16935 intent.addCategory(Intent.CATEGORY_HOME); 16936 return intent; 16937 } 16938 16939 private IntentFilter getHomeFilter() { 16940 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16941 filter.addCategory(Intent.CATEGORY_HOME); 16942 filter.addCategory(Intent.CATEGORY_DEFAULT); 16943 return filter; 16944 } 16945 16946 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16947 int userId) { 16948 Intent intent = getHomeIntent(); 16949 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16950 PackageManager.GET_META_DATA, userId); 16951 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16952 true, false, false, userId); 16953 16954 allHomeCandidates.clear(); 16955 if (list != null) { 16956 for (ResolveInfo ri : list) { 16957 allHomeCandidates.add(ri); 16958 } 16959 } 16960 return (preferred == null || preferred.activityInfo == null) 16961 ? null 16962 : new ComponentName(preferred.activityInfo.packageName, 16963 preferred.activityInfo.name); 16964 } 16965 16966 @Override 16967 public void setHomeActivity(ComponentName comp, int userId) { 16968 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16969 getHomeActivitiesAsUser(homeActivities, userId); 16970 16971 boolean found = false; 16972 16973 final int size = homeActivities.size(); 16974 final ComponentName[] set = new ComponentName[size]; 16975 for (int i = 0; i < size; i++) { 16976 final ResolveInfo candidate = homeActivities.get(i); 16977 final ActivityInfo info = candidate.activityInfo; 16978 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16979 set[i] = activityName; 16980 if (!found && activityName.equals(comp)) { 16981 found = true; 16982 } 16983 } 16984 if (!found) { 16985 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16986 + userId); 16987 } 16988 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16989 set, comp, userId); 16990 } 16991 16992 private @Nullable String getSetupWizardPackageName() { 16993 final Intent intent = new Intent(Intent.ACTION_MAIN); 16994 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 16995 16996 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 16997 MATCH_SYSTEM_ONLY | MATCH_DISABLED_COMPONENTS, UserHandle.myUserId()); 16998 if (matches.size() == 1) { 16999 return matches.get(0).getComponentInfo().packageName; 17000 } else { 17001 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17002 + ": matches=" + matches); 17003 return null; 17004 } 17005 } 17006 17007 @Override 17008 public void setApplicationEnabledSetting(String appPackageName, 17009 int newState, int flags, int userId, String callingPackage) { 17010 if (!sUserManager.exists(userId)) return; 17011 if (callingPackage == null) { 17012 callingPackage = Integer.toString(Binder.getCallingUid()); 17013 } 17014 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17015 } 17016 17017 @Override 17018 public void setComponentEnabledSetting(ComponentName componentName, 17019 int newState, int flags, int userId) { 17020 if (!sUserManager.exists(userId)) return; 17021 setEnabledSetting(componentName.getPackageName(), 17022 componentName.getClassName(), newState, flags, userId, null); 17023 } 17024 17025 private void setEnabledSetting(final String packageName, String className, int newState, 17026 final int flags, int userId, String callingPackage) { 17027 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17028 || newState == COMPONENT_ENABLED_STATE_ENABLED 17029 || newState == COMPONENT_ENABLED_STATE_DISABLED 17030 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17031 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17032 throw new IllegalArgumentException("Invalid new component state: " 17033 + newState); 17034 } 17035 PackageSetting pkgSetting; 17036 final int uid = Binder.getCallingUid(); 17037 final int permission = mContext.checkCallingOrSelfPermission( 17038 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17039 enforceCrossUserPermission(uid, userId, 17040 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17041 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17042 boolean sendNow = false; 17043 boolean isApp = (className == null); 17044 String componentName = isApp ? packageName : className; 17045 int packageUid = -1; 17046 ArrayList<String> components; 17047 17048 // writer 17049 synchronized (mPackages) { 17050 pkgSetting = mSettings.mPackages.get(packageName); 17051 if (pkgSetting == null) { 17052 if (className == null) { 17053 throw new IllegalArgumentException("Unknown package: " + packageName); 17054 } 17055 throw new IllegalArgumentException( 17056 "Unknown component: " + packageName + "/" + className); 17057 } 17058 // Allow root and verify that userId is not being specified by a different user 17059 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17060 throw new SecurityException( 17061 "Permission Denial: attempt to change component state from pid=" 17062 + Binder.getCallingPid() 17063 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17064 } 17065 if (className == null) { 17066 // We're dealing with an application/package level state change 17067 if (pkgSetting.getEnabled(userId) == newState) { 17068 // Nothing to do 17069 return; 17070 } 17071 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17072 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17073 // Don't care about who enables an app. 17074 callingPackage = null; 17075 } 17076 pkgSetting.setEnabled(newState, userId, callingPackage); 17077 // pkgSetting.pkg.mSetEnabled = newState; 17078 } else { 17079 // We're dealing with a component level state change 17080 // First, verify that this is a valid class name. 17081 PackageParser.Package pkg = pkgSetting.pkg; 17082 if (pkg == null || !pkg.hasComponentClassName(className)) { 17083 if (pkg != null && 17084 pkg.applicationInfo.targetSdkVersion >= 17085 Build.VERSION_CODES.JELLY_BEAN) { 17086 throw new IllegalArgumentException("Component class " + className 17087 + " does not exist in " + packageName); 17088 } else { 17089 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17090 + className + " does not exist in " + packageName); 17091 } 17092 } 17093 switch (newState) { 17094 case COMPONENT_ENABLED_STATE_ENABLED: 17095 if (!pkgSetting.enableComponentLPw(className, userId)) { 17096 return; 17097 } 17098 break; 17099 case COMPONENT_ENABLED_STATE_DISABLED: 17100 if (!pkgSetting.disableComponentLPw(className, userId)) { 17101 return; 17102 } 17103 break; 17104 case COMPONENT_ENABLED_STATE_DEFAULT: 17105 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17106 return; 17107 } 17108 break; 17109 default: 17110 Slog.e(TAG, "Invalid new component state: " + newState); 17111 return; 17112 } 17113 } 17114 scheduleWritePackageRestrictionsLocked(userId); 17115 components = mPendingBroadcasts.get(userId, packageName); 17116 final boolean newPackage = components == null; 17117 if (newPackage) { 17118 components = new ArrayList<String>(); 17119 } 17120 if (!components.contains(componentName)) { 17121 components.add(componentName); 17122 } 17123 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17124 sendNow = true; 17125 // Purge entry from pending broadcast list if another one exists already 17126 // since we are sending one right away. 17127 mPendingBroadcasts.remove(userId, packageName); 17128 } else { 17129 if (newPackage) { 17130 mPendingBroadcasts.put(userId, packageName, components); 17131 } 17132 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17133 // Schedule a message 17134 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17135 } 17136 } 17137 } 17138 17139 long callingId = Binder.clearCallingIdentity(); 17140 try { 17141 if (sendNow) { 17142 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17143 sendPackageChangedBroadcast(packageName, 17144 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17145 } 17146 } finally { 17147 Binder.restoreCallingIdentity(callingId); 17148 } 17149 } 17150 17151 @Override 17152 public void flushPackageRestrictionsAsUser(int userId) { 17153 if (!sUserManager.exists(userId)) { 17154 return; 17155 } 17156 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17157 false /* checkShell */, "flushPackageRestrictions"); 17158 synchronized (mPackages) { 17159 mSettings.writePackageRestrictionsLPr(userId); 17160 mDirtyUsers.remove(userId); 17161 if (mDirtyUsers.isEmpty()) { 17162 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17163 } 17164 } 17165 } 17166 17167 private void sendPackageChangedBroadcast(String packageName, 17168 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17169 if (DEBUG_INSTALL) 17170 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17171 + componentNames); 17172 Bundle extras = new Bundle(4); 17173 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17174 String nameList[] = new String[componentNames.size()]; 17175 componentNames.toArray(nameList); 17176 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17177 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17178 extras.putInt(Intent.EXTRA_UID, packageUid); 17179 // If this is not reporting a change of the overall package, then only send it 17180 // to registered receivers. We don't want to launch a swath of apps for every 17181 // little component state change. 17182 final int flags = !componentNames.contains(packageName) 17183 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17184 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17185 new int[] {UserHandle.getUserId(packageUid)}); 17186 } 17187 17188 @Override 17189 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17190 if (!sUserManager.exists(userId)) return; 17191 final int uid = Binder.getCallingUid(); 17192 final int permission = mContext.checkCallingOrSelfPermission( 17193 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17194 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17195 enforceCrossUserPermission(uid, userId, 17196 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17197 // writer 17198 synchronized (mPackages) { 17199 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17200 allowedByPermission, uid, userId)) { 17201 scheduleWritePackageRestrictionsLocked(userId); 17202 } 17203 } 17204 } 17205 17206 @Override 17207 public String getInstallerPackageName(String packageName) { 17208 // reader 17209 synchronized (mPackages) { 17210 return mSettings.getInstallerPackageNameLPr(packageName); 17211 } 17212 } 17213 17214 @Override 17215 public int getApplicationEnabledSetting(String packageName, int userId) { 17216 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17217 int uid = Binder.getCallingUid(); 17218 enforceCrossUserPermission(uid, userId, 17219 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17220 // reader 17221 synchronized (mPackages) { 17222 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17223 } 17224 } 17225 17226 @Override 17227 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17228 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17229 int uid = Binder.getCallingUid(); 17230 enforceCrossUserPermission(uid, userId, 17231 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17232 // reader 17233 synchronized (mPackages) { 17234 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17235 } 17236 } 17237 17238 @Override 17239 public void enterSafeMode() { 17240 enforceSystemOrRoot("Only the system can request entering safe mode"); 17241 17242 if (!mSystemReady) { 17243 mSafeMode = true; 17244 } 17245 } 17246 17247 @Override 17248 public void systemReady() { 17249 mSystemReady = true; 17250 17251 // Read the compatibilty setting when the system is ready. 17252 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17253 mContext.getContentResolver(), 17254 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17255 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17256 if (DEBUG_SETTINGS) { 17257 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17258 } 17259 17260 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17261 17262 synchronized (mPackages) { 17263 // Verify that all of the preferred activity components actually 17264 // exist. It is possible for applications to be updated and at 17265 // that point remove a previously declared activity component that 17266 // had been set as a preferred activity. We try to clean this up 17267 // the next time we encounter that preferred activity, but it is 17268 // possible for the user flow to never be able to return to that 17269 // situation so here we do a sanity check to make sure we haven't 17270 // left any junk around. 17271 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17272 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17273 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17274 removed.clear(); 17275 for (PreferredActivity pa : pir.filterSet()) { 17276 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17277 removed.add(pa); 17278 } 17279 } 17280 if (removed.size() > 0) { 17281 for (int r=0; r<removed.size(); r++) { 17282 PreferredActivity pa = removed.get(r); 17283 Slog.w(TAG, "Removing dangling preferred activity: " 17284 + pa.mPref.mComponent); 17285 pir.removeFilter(pa); 17286 } 17287 mSettings.writePackageRestrictionsLPr( 17288 mSettings.mPreferredActivities.keyAt(i)); 17289 } 17290 } 17291 17292 for (int userId : UserManagerService.getInstance().getUserIds()) { 17293 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17294 grantPermissionsUserIds = ArrayUtils.appendInt( 17295 grantPermissionsUserIds, userId); 17296 } 17297 } 17298 } 17299 sUserManager.systemReady(); 17300 17301 // If we upgraded grant all default permissions before kicking off. 17302 for (int userId : grantPermissionsUserIds) { 17303 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17304 } 17305 17306 // Kick off any messages waiting for system ready 17307 if (mPostSystemReadyMessages != null) { 17308 for (Message msg : mPostSystemReadyMessages) { 17309 msg.sendToTarget(); 17310 } 17311 mPostSystemReadyMessages = null; 17312 } 17313 17314 // Watch for external volumes that come and go over time 17315 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17316 storage.registerListener(mStorageListener); 17317 17318 mInstallerService.systemReady(); 17319 mPackageDexOptimizer.systemReady(); 17320 17321 MountServiceInternal mountServiceInternal = LocalServices.getService( 17322 MountServiceInternal.class); 17323 mountServiceInternal.addExternalStoragePolicy( 17324 new MountServiceInternal.ExternalStorageMountPolicy() { 17325 @Override 17326 public int getMountMode(int uid, String packageName) { 17327 if (Process.isIsolated(uid)) { 17328 return Zygote.MOUNT_EXTERNAL_NONE; 17329 } 17330 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17331 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17332 } 17333 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17334 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17335 } 17336 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17337 return Zygote.MOUNT_EXTERNAL_READ; 17338 } 17339 return Zygote.MOUNT_EXTERNAL_WRITE; 17340 } 17341 17342 @Override 17343 public boolean hasExternalStorage(int uid, String packageName) { 17344 return true; 17345 } 17346 }); 17347 } 17348 17349 @Override 17350 public boolean isSafeMode() { 17351 return mSafeMode; 17352 } 17353 17354 @Override 17355 public boolean hasSystemUidErrors() { 17356 return mHasSystemUidErrors; 17357 } 17358 17359 static String arrayToString(int[] array) { 17360 StringBuffer buf = new StringBuffer(128); 17361 buf.append('['); 17362 if (array != null) { 17363 for (int i=0; i<array.length; i++) { 17364 if (i > 0) buf.append(", "); 17365 buf.append(array[i]); 17366 } 17367 } 17368 buf.append(']'); 17369 return buf.toString(); 17370 } 17371 17372 static class DumpState { 17373 public static final int DUMP_LIBS = 1 << 0; 17374 public static final int DUMP_FEATURES = 1 << 1; 17375 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17376 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17377 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17378 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17379 public static final int DUMP_PERMISSIONS = 1 << 6; 17380 public static final int DUMP_PACKAGES = 1 << 7; 17381 public static final int DUMP_SHARED_USERS = 1 << 8; 17382 public static final int DUMP_MESSAGES = 1 << 9; 17383 public static final int DUMP_PROVIDERS = 1 << 10; 17384 public static final int DUMP_VERIFIERS = 1 << 11; 17385 public static final int DUMP_PREFERRED = 1 << 12; 17386 public static final int DUMP_PREFERRED_XML = 1 << 13; 17387 public static final int DUMP_KEYSETS = 1 << 14; 17388 public static final int DUMP_VERSION = 1 << 15; 17389 public static final int DUMP_INSTALLS = 1 << 16; 17390 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17391 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17392 17393 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17394 17395 private int mTypes; 17396 17397 private int mOptions; 17398 17399 private boolean mTitlePrinted; 17400 17401 private SharedUserSetting mSharedUser; 17402 17403 public boolean isDumping(int type) { 17404 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17405 return true; 17406 } 17407 17408 return (mTypes & type) != 0; 17409 } 17410 17411 public void setDump(int type) { 17412 mTypes |= type; 17413 } 17414 17415 public boolean isOptionEnabled(int option) { 17416 return (mOptions & option) != 0; 17417 } 17418 17419 public void setOptionEnabled(int option) { 17420 mOptions |= option; 17421 } 17422 17423 public boolean onTitlePrinted() { 17424 final boolean printed = mTitlePrinted; 17425 mTitlePrinted = true; 17426 return printed; 17427 } 17428 17429 public boolean getTitlePrinted() { 17430 return mTitlePrinted; 17431 } 17432 17433 public void setTitlePrinted(boolean enabled) { 17434 mTitlePrinted = enabled; 17435 } 17436 17437 public SharedUserSetting getSharedUser() { 17438 return mSharedUser; 17439 } 17440 17441 public void setSharedUser(SharedUserSetting user) { 17442 mSharedUser = user; 17443 } 17444 } 17445 17446 @Override 17447 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17448 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17449 (new PackageManagerShellCommand(this)).exec( 17450 this, in, out, err, args, resultReceiver); 17451 } 17452 17453 @Override 17454 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17455 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17456 != PackageManager.PERMISSION_GRANTED) { 17457 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17458 + Binder.getCallingPid() 17459 + ", uid=" + Binder.getCallingUid() 17460 + " without permission " 17461 + android.Manifest.permission.DUMP); 17462 return; 17463 } 17464 17465 DumpState dumpState = new DumpState(); 17466 boolean fullPreferred = false; 17467 boolean checkin = false; 17468 17469 String packageName = null; 17470 ArraySet<String> permissionNames = null; 17471 17472 int opti = 0; 17473 while (opti < args.length) { 17474 String opt = args[opti]; 17475 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17476 break; 17477 } 17478 opti++; 17479 17480 if ("-a".equals(opt)) { 17481 // Right now we only know how to print all. 17482 } else if ("-h".equals(opt)) { 17483 pw.println("Package manager dump options:"); 17484 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17485 pw.println(" --checkin: dump for a checkin"); 17486 pw.println(" -f: print details of intent filters"); 17487 pw.println(" -h: print this help"); 17488 pw.println(" cmd may be one of:"); 17489 pw.println(" l[ibraries]: list known shared libraries"); 17490 pw.println(" f[eatures]: list device features"); 17491 pw.println(" k[eysets]: print known keysets"); 17492 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17493 pw.println(" perm[issions]: dump permissions"); 17494 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17495 pw.println(" pref[erred]: print preferred package settings"); 17496 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17497 pw.println(" prov[iders]: dump content providers"); 17498 pw.println(" p[ackages]: dump installed packages"); 17499 pw.println(" s[hared-users]: dump shared user IDs"); 17500 pw.println(" m[essages]: print collected runtime messages"); 17501 pw.println(" v[erifiers]: print package verifier info"); 17502 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17503 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17504 pw.println(" version: print database version info"); 17505 pw.println(" write: write current settings now"); 17506 pw.println(" installs: details about install sessions"); 17507 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17508 pw.println(" <package.name>: info about given package"); 17509 return; 17510 } else if ("--checkin".equals(opt)) { 17511 checkin = true; 17512 } else if ("-f".equals(opt)) { 17513 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17514 } else { 17515 pw.println("Unknown argument: " + opt + "; use -h for help"); 17516 } 17517 } 17518 17519 // Is the caller requesting to dump a particular piece of data? 17520 if (opti < args.length) { 17521 String cmd = args[opti]; 17522 opti++; 17523 // Is this a package name? 17524 if ("android".equals(cmd) || cmd.contains(".")) { 17525 packageName = cmd; 17526 // When dumping a single package, we always dump all of its 17527 // filter information since the amount of data will be reasonable. 17528 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17529 } else if ("check-permission".equals(cmd)) { 17530 if (opti >= args.length) { 17531 pw.println("Error: check-permission missing permission argument"); 17532 return; 17533 } 17534 String perm = args[opti]; 17535 opti++; 17536 if (opti >= args.length) { 17537 pw.println("Error: check-permission missing package argument"); 17538 return; 17539 } 17540 String pkg = args[opti]; 17541 opti++; 17542 int user = UserHandle.getUserId(Binder.getCallingUid()); 17543 if (opti < args.length) { 17544 try { 17545 user = Integer.parseInt(args[opti]); 17546 } catch (NumberFormatException e) { 17547 pw.println("Error: check-permission user argument is not a number: " 17548 + args[opti]); 17549 return; 17550 } 17551 } 17552 pw.println(checkPermission(perm, pkg, user)); 17553 return; 17554 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17555 dumpState.setDump(DumpState.DUMP_LIBS); 17556 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17557 dumpState.setDump(DumpState.DUMP_FEATURES); 17558 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17559 if (opti >= args.length) { 17560 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17561 | DumpState.DUMP_SERVICE_RESOLVERS 17562 | DumpState.DUMP_RECEIVER_RESOLVERS 17563 | DumpState.DUMP_CONTENT_RESOLVERS); 17564 } else { 17565 while (opti < args.length) { 17566 String name = args[opti]; 17567 if ("a".equals(name) || "activity".equals(name)) { 17568 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17569 } else if ("s".equals(name) || "service".equals(name)) { 17570 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17571 } else if ("r".equals(name) || "receiver".equals(name)) { 17572 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17573 } else if ("c".equals(name) || "content".equals(name)) { 17574 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17575 } else { 17576 pw.println("Error: unknown resolver table type: " + name); 17577 return; 17578 } 17579 opti++; 17580 } 17581 } 17582 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17583 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17584 } else if ("permission".equals(cmd)) { 17585 if (opti >= args.length) { 17586 pw.println("Error: permission requires permission name"); 17587 return; 17588 } 17589 permissionNames = new ArraySet<>(); 17590 while (opti < args.length) { 17591 permissionNames.add(args[opti]); 17592 opti++; 17593 } 17594 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17595 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17596 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17597 dumpState.setDump(DumpState.DUMP_PREFERRED); 17598 } else if ("preferred-xml".equals(cmd)) { 17599 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17600 if (opti < args.length && "--full".equals(args[opti])) { 17601 fullPreferred = true; 17602 opti++; 17603 } 17604 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17605 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17606 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17607 dumpState.setDump(DumpState.DUMP_PACKAGES); 17608 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17609 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17610 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17611 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17612 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17613 dumpState.setDump(DumpState.DUMP_MESSAGES); 17614 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17615 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17616 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17617 || "intent-filter-verifiers".equals(cmd)) { 17618 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17619 } else if ("version".equals(cmd)) { 17620 dumpState.setDump(DumpState.DUMP_VERSION); 17621 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17622 dumpState.setDump(DumpState.DUMP_KEYSETS); 17623 } else if ("installs".equals(cmd)) { 17624 dumpState.setDump(DumpState.DUMP_INSTALLS); 17625 } else if ("write".equals(cmd)) { 17626 synchronized (mPackages) { 17627 mSettings.writeLPr(); 17628 pw.println("Settings written."); 17629 return; 17630 } 17631 } 17632 } 17633 17634 if (checkin) { 17635 pw.println("vers,1"); 17636 } 17637 17638 // reader 17639 synchronized (mPackages) { 17640 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17641 if (!checkin) { 17642 if (dumpState.onTitlePrinted()) 17643 pw.println(); 17644 pw.println("Database versions:"); 17645 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17646 } 17647 } 17648 17649 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17650 if (!checkin) { 17651 if (dumpState.onTitlePrinted()) 17652 pw.println(); 17653 pw.println("Verifiers:"); 17654 pw.print(" Required: "); 17655 pw.print(mRequiredVerifierPackage); 17656 pw.print(" (uid="); 17657 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17658 UserHandle.USER_SYSTEM)); 17659 pw.println(")"); 17660 } else if (mRequiredVerifierPackage != null) { 17661 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17662 pw.print(","); 17663 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17664 UserHandle.USER_SYSTEM)); 17665 } 17666 } 17667 17668 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17669 packageName == null) { 17670 if (mIntentFilterVerifierComponent != null) { 17671 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17672 if (!checkin) { 17673 if (dumpState.onTitlePrinted()) 17674 pw.println(); 17675 pw.println("Intent Filter Verifier:"); 17676 pw.print(" Using: "); 17677 pw.print(verifierPackageName); 17678 pw.print(" (uid="); 17679 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17680 UserHandle.USER_SYSTEM)); 17681 pw.println(")"); 17682 } else if (verifierPackageName != null) { 17683 pw.print("ifv,"); pw.print(verifierPackageName); 17684 pw.print(","); 17685 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17686 UserHandle.USER_SYSTEM)); 17687 } 17688 } else { 17689 pw.println(); 17690 pw.println("No Intent Filter Verifier available!"); 17691 } 17692 } 17693 17694 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17695 boolean printedHeader = false; 17696 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17697 while (it.hasNext()) { 17698 String name = it.next(); 17699 SharedLibraryEntry ent = mSharedLibraries.get(name); 17700 if (!checkin) { 17701 if (!printedHeader) { 17702 if (dumpState.onTitlePrinted()) 17703 pw.println(); 17704 pw.println("Libraries:"); 17705 printedHeader = true; 17706 } 17707 pw.print(" "); 17708 } else { 17709 pw.print("lib,"); 17710 } 17711 pw.print(name); 17712 if (!checkin) { 17713 pw.print(" -> "); 17714 } 17715 if (ent.path != null) { 17716 if (!checkin) { 17717 pw.print("(jar) "); 17718 pw.print(ent.path); 17719 } else { 17720 pw.print(",jar,"); 17721 pw.print(ent.path); 17722 } 17723 } else { 17724 if (!checkin) { 17725 pw.print("(apk) "); 17726 pw.print(ent.apk); 17727 } else { 17728 pw.print(",apk,"); 17729 pw.print(ent.apk); 17730 } 17731 } 17732 pw.println(); 17733 } 17734 } 17735 17736 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17737 if (dumpState.onTitlePrinted()) 17738 pw.println(); 17739 if (!checkin) { 17740 pw.println("Features:"); 17741 } 17742 17743 for (FeatureInfo feat : mAvailableFeatures.values()) { 17744 if (checkin) { 17745 pw.print("feat,"); 17746 pw.print(feat.name); 17747 pw.print(","); 17748 pw.println(feat.version); 17749 } else { 17750 pw.print(" "); 17751 pw.print(feat.name); 17752 if (feat.version > 0) { 17753 pw.print(" version="); 17754 pw.print(feat.version); 17755 } 17756 pw.println(); 17757 } 17758 } 17759 } 17760 17761 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17762 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17763 : "Activity Resolver Table:", " ", packageName, 17764 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17765 dumpState.setTitlePrinted(true); 17766 } 17767 } 17768 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17769 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17770 : "Receiver Resolver Table:", " ", packageName, 17771 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17772 dumpState.setTitlePrinted(true); 17773 } 17774 } 17775 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17776 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17777 : "Service Resolver Table:", " ", packageName, 17778 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17779 dumpState.setTitlePrinted(true); 17780 } 17781 } 17782 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17783 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17784 : "Provider Resolver Table:", " ", packageName, 17785 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17786 dumpState.setTitlePrinted(true); 17787 } 17788 } 17789 17790 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17791 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17792 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17793 int user = mSettings.mPreferredActivities.keyAt(i); 17794 if (pir.dump(pw, 17795 dumpState.getTitlePrinted() 17796 ? "\nPreferred Activities User " + user + ":" 17797 : "Preferred Activities User " + user + ":", " ", 17798 packageName, true, false)) { 17799 dumpState.setTitlePrinted(true); 17800 } 17801 } 17802 } 17803 17804 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17805 pw.flush(); 17806 FileOutputStream fout = new FileOutputStream(fd); 17807 BufferedOutputStream str = new BufferedOutputStream(fout); 17808 XmlSerializer serializer = new FastXmlSerializer(); 17809 try { 17810 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17811 serializer.startDocument(null, true); 17812 serializer.setFeature( 17813 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17814 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17815 serializer.endDocument(); 17816 serializer.flush(); 17817 } catch (IllegalArgumentException e) { 17818 pw.println("Failed writing: " + e); 17819 } catch (IllegalStateException e) { 17820 pw.println("Failed writing: " + e); 17821 } catch (IOException e) { 17822 pw.println("Failed writing: " + e); 17823 } 17824 } 17825 17826 if (!checkin 17827 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17828 && packageName == null) { 17829 pw.println(); 17830 int count = mSettings.mPackages.size(); 17831 if (count == 0) { 17832 pw.println("No applications!"); 17833 pw.println(); 17834 } else { 17835 final String prefix = " "; 17836 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17837 if (allPackageSettings.size() == 0) { 17838 pw.println("No domain preferred apps!"); 17839 pw.println(); 17840 } else { 17841 pw.println("App verification status:"); 17842 pw.println(); 17843 count = 0; 17844 for (PackageSetting ps : allPackageSettings) { 17845 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17846 if (ivi == null || ivi.getPackageName() == null) continue; 17847 pw.println(prefix + "Package: " + ivi.getPackageName()); 17848 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17849 pw.println(prefix + "Status: " + ivi.getStatusString()); 17850 pw.println(); 17851 count++; 17852 } 17853 if (count == 0) { 17854 pw.println(prefix + "No app verification established."); 17855 pw.println(); 17856 } 17857 for (int userId : sUserManager.getUserIds()) { 17858 pw.println("App linkages for user " + userId + ":"); 17859 pw.println(); 17860 count = 0; 17861 for (PackageSetting ps : allPackageSettings) { 17862 final long status = ps.getDomainVerificationStatusForUser(userId); 17863 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17864 continue; 17865 } 17866 pw.println(prefix + "Package: " + ps.name); 17867 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17868 String statusStr = IntentFilterVerificationInfo. 17869 getStatusStringFromValue(status); 17870 pw.println(prefix + "Status: " + statusStr); 17871 pw.println(); 17872 count++; 17873 } 17874 if (count == 0) { 17875 pw.println(prefix + "No configured app linkages."); 17876 pw.println(); 17877 } 17878 } 17879 } 17880 } 17881 } 17882 17883 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17884 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17885 if (packageName == null && permissionNames == null) { 17886 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17887 if (iperm == 0) { 17888 if (dumpState.onTitlePrinted()) 17889 pw.println(); 17890 pw.println("AppOp Permissions:"); 17891 } 17892 pw.print(" AppOp Permission "); 17893 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17894 pw.println(":"); 17895 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17896 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17897 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17898 } 17899 } 17900 } 17901 } 17902 17903 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17904 boolean printedSomething = false; 17905 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17906 if (packageName != null && !packageName.equals(p.info.packageName)) { 17907 continue; 17908 } 17909 if (!printedSomething) { 17910 if (dumpState.onTitlePrinted()) 17911 pw.println(); 17912 pw.println("Registered ContentProviders:"); 17913 printedSomething = true; 17914 } 17915 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17916 pw.print(" "); pw.println(p.toString()); 17917 } 17918 printedSomething = false; 17919 for (Map.Entry<String, PackageParser.Provider> entry : 17920 mProvidersByAuthority.entrySet()) { 17921 PackageParser.Provider p = entry.getValue(); 17922 if (packageName != null && !packageName.equals(p.info.packageName)) { 17923 continue; 17924 } 17925 if (!printedSomething) { 17926 if (dumpState.onTitlePrinted()) 17927 pw.println(); 17928 pw.println("ContentProvider Authorities:"); 17929 printedSomething = true; 17930 } 17931 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17932 pw.print(" "); pw.println(p.toString()); 17933 if (p.info != null && p.info.applicationInfo != null) { 17934 final String appInfo = p.info.applicationInfo.toString(); 17935 pw.print(" applicationInfo="); pw.println(appInfo); 17936 } 17937 } 17938 } 17939 17940 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17941 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17942 } 17943 17944 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17945 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17946 } 17947 17948 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17949 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17950 } 17951 17952 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17953 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17954 } 17955 17956 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17957 // XXX should handle packageName != null by dumping only install data that 17958 // the given package is involved with. 17959 if (dumpState.onTitlePrinted()) pw.println(); 17960 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17961 } 17962 17963 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17964 if (dumpState.onTitlePrinted()) pw.println(); 17965 mSettings.dumpReadMessagesLPr(pw, dumpState); 17966 17967 pw.println(); 17968 pw.println("Package warning messages:"); 17969 BufferedReader in = null; 17970 String line = null; 17971 try { 17972 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17973 while ((line = in.readLine()) != null) { 17974 if (line.contains("ignored: updated version")) continue; 17975 pw.println(line); 17976 } 17977 } catch (IOException ignored) { 17978 } finally { 17979 IoUtils.closeQuietly(in); 17980 } 17981 } 17982 17983 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17984 BufferedReader in = null; 17985 String line = null; 17986 try { 17987 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17988 while ((line = in.readLine()) != null) { 17989 if (line.contains("ignored: updated version")) continue; 17990 pw.print("msg,"); 17991 pw.println(line); 17992 } 17993 } catch (IOException ignored) { 17994 } finally { 17995 IoUtils.closeQuietly(in); 17996 } 17997 } 17998 } 17999 } 18000 18001 private String dumpDomainString(String packageName) { 18002 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18003 .getList(); 18004 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18005 18006 ArraySet<String> result = new ArraySet<>(); 18007 if (iviList.size() > 0) { 18008 for (IntentFilterVerificationInfo ivi : iviList) { 18009 for (String host : ivi.getDomains()) { 18010 result.add(host); 18011 } 18012 } 18013 } 18014 if (filters != null && filters.size() > 0) { 18015 for (IntentFilter filter : filters) { 18016 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18017 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18018 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18019 result.addAll(filter.getHostsList()); 18020 } 18021 } 18022 } 18023 18024 StringBuilder sb = new StringBuilder(result.size() * 16); 18025 for (String domain : result) { 18026 if (sb.length() > 0) sb.append(" "); 18027 sb.append(domain); 18028 } 18029 return sb.toString(); 18030 } 18031 18032 // ------- apps on sdcard specific code ------- 18033 static final boolean DEBUG_SD_INSTALL = false; 18034 18035 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18036 18037 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18038 18039 private boolean mMediaMounted = false; 18040 18041 static String getEncryptKey() { 18042 try { 18043 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18044 SD_ENCRYPTION_KEYSTORE_NAME); 18045 if (sdEncKey == null) { 18046 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18047 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18048 if (sdEncKey == null) { 18049 Slog.e(TAG, "Failed to create encryption keys"); 18050 return null; 18051 } 18052 } 18053 return sdEncKey; 18054 } catch (NoSuchAlgorithmException nsae) { 18055 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18056 return null; 18057 } catch (IOException ioe) { 18058 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18059 return null; 18060 } 18061 } 18062 18063 /* 18064 * Update media status on PackageManager. 18065 */ 18066 @Override 18067 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18068 int callingUid = Binder.getCallingUid(); 18069 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18070 throw new SecurityException("Media status can only be updated by the system"); 18071 } 18072 // reader; this apparently protects mMediaMounted, but should probably 18073 // be a different lock in that case. 18074 synchronized (mPackages) { 18075 Log.i(TAG, "Updating external media status from " 18076 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18077 + (mediaStatus ? "mounted" : "unmounted")); 18078 if (DEBUG_SD_INSTALL) 18079 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18080 + ", mMediaMounted=" + mMediaMounted); 18081 if (mediaStatus == mMediaMounted) { 18082 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18083 : 0, -1); 18084 mHandler.sendMessage(msg); 18085 return; 18086 } 18087 mMediaMounted = mediaStatus; 18088 } 18089 // Queue up an async operation since the package installation may take a 18090 // little while. 18091 mHandler.post(new Runnable() { 18092 public void run() { 18093 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18094 } 18095 }); 18096 } 18097 18098 /** 18099 * Called by MountService when the initial ASECs to scan are available. 18100 * Should block until all the ASEC containers are finished being scanned. 18101 */ 18102 public void scanAvailableAsecs() { 18103 updateExternalMediaStatusInner(true, false, false); 18104 } 18105 18106 /* 18107 * Collect information of applications on external media, map them against 18108 * existing containers and update information based on current mount status. 18109 * Please note that we always have to report status if reportStatus has been 18110 * set to true especially when unloading packages. 18111 */ 18112 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18113 boolean externalStorage) { 18114 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18115 int[] uidArr = EmptyArray.INT; 18116 18117 final String[] list = PackageHelper.getSecureContainerList(); 18118 if (ArrayUtils.isEmpty(list)) { 18119 Log.i(TAG, "No secure containers found"); 18120 } else { 18121 // Process list of secure containers and categorize them 18122 // as active or stale based on their package internal state. 18123 18124 // reader 18125 synchronized (mPackages) { 18126 for (String cid : list) { 18127 // Leave stages untouched for now; installer service owns them 18128 if (PackageInstallerService.isStageName(cid)) continue; 18129 18130 if (DEBUG_SD_INSTALL) 18131 Log.i(TAG, "Processing container " + cid); 18132 String pkgName = getAsecPackageName(cid); 18133 if (pkgName == null) { 18134 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18135 continue; 18136 } 18137 if (DEBUG_SD_INSTALL) 18138 Log.i(TAG, "Looking for pkg : " + pkgName); 18139 18140 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18141 if (ps == null) { 18142 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18143 continue; 18144 } 18145 18146 /* 18147 * Skip packages that are not external if we're unmounting 18148 * external storage. 18149 */ 18150 if (externalStorage && !isMounted && !isExternal(ps)) { 18151 continue; 18152 } 18153 18154 final AsecInstallArgs args = new AsecInstallArgs(cid, 18155 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18156 // The package status is changed only if the code path 18157 // matches between settings and the container id. 18158 if (ps.codePathString != null 18159 && ps.codePathString.startsWith(args.getCodePath())) { 18160 if (DEBUG_SD_INSTALL) { 18161 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18162 + " at code path: " + ps.codePathString); 18163 } 18164 18165 // We do have a valid package installed on sdcard 18166 processCids.put(args, ps.codePathString); 18167 final int uid = ps.appId; 18168 if (uid != -1) { 18169 uidArr = ArrayUtils.appendInt(uidArr, uid); 18170 } 18171 } else { 18172 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18173 + ps.codePathString); 18174 } 18175 } 18176 } 18177 18178 Arrays.sort(uidArr); 18179 } 18180 18181 // Process packages with valid entries. 18182 if (isMounted) { 18183 if (DEBUG_SD_INSTALL) 18184 Log.i(TAG, "Loading packages"); 18185 loadMediaPackages(processCids, uidArr, externalStorage); 18186 startCleaningPackages(); 18187 mInstallerService.onSecureContainersAvailable(); 18188 } else { 18189 if (DEBUG_SD_INSTALL) 18190 Log.i(TAG, "Unloading packages"); 18191 unloadMediaPackages(processCids, uidArr, reportStatus); 18192 } 18193 } 18194 18195 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18196 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18197 final int size = infos.size(); 18198 final String[] packageNames = new String[size]; 18199 final int[] packageUids = new int[size]; 18200 for (int i = 0; i < size; i++) { 18201 final ApplicationInfo info = infos.get(i); 18202 packageNames[i] = info.packageName; 18203 packageUids[i] = info.uid; 18204 } 18205 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18206 finishedReceiver); 18207 } 18208 18209 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18210 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18211 sendResourcesChangedBroadcast(mediaStatus, replacing, 18212 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18213 } 18214 18215 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18216 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18217 int size = pkgList.length; 18218 if (size > 0) { 18219 // Send broadcasts here 18220 Bundle extras = new Bundle(); 18221 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18222 if (uidArr != null) { 18223 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18224 } 18225 if (replacing) { 18226 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18227 } 18228 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18229 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18230 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18231 } 18232 } 18233 18234 /* 18235 * Look at potentially valid container ids from processCids If package 18236 * information doesn't match the one on record or package scanning fails, 18237 * the cid is added to list of removeCids. We currently don't delete stale 18238 * containers. 18239 */ 18240 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18241 boolean externalStorage) { 18242 ArrayList<String> pkgList = new ArrayList<String>(); 18243 Set<AsecInstallArgs> keys = processCids.keySet(); 18244 18245 for (AsecInstallArgs args : keys) { 18246 String codePath = processCids.get(args); 18247 if (DEBUG_SD_INSTALL) 18248 Log.i(TAG, "Loading container : " + args.cid); 18249 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18250 try { 18251 // Make sure there are no container errors first. 18252 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18253 Slog.e(TAG, "Failed to mount cid : " + args.cid 18254 + " when installing from sdcard"); 18255 continue; 18256 } 18257 // Check code path here. 18258 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18259 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18260 + " does not match one in settings " + codePath); 18261 continue; 18262 } 18263 // Parse package 18264 int parseFlags = mDefParseFlags; 18265 if (args.isExternalAsec()) { 18266 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18267 } 18268 if (args.isFwdLocked()) { 18269 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18270 } 18271 18272 synchronized (mInstallLock) { 18273 PackageParser.Package pkg = null; 18274 try { 18275 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 18276 } catch (PackageManagerException e) { 18277 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18278 } 18279 // Scan the package 18280 if (pkg != null) { 18281 /* 18282 * TODO why is the lock being held? doPostInstall is 18283 * called in other places without the lock. This needs 18284 * to be straightened out. 18285 */ 18286 // writer 18287 synchronized (mPackages) { 18288 retCode = PackageManager.INSTALL_SUCCEEDED; 18289 pkgList.add(pkg.packageName); 18290 // Post process args 18291 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18292 pkg.applicationInfo.uid); 18293 } 18294 } else { 18295 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18296 } 18297 } 18298 18299 } finally { 18300 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18301 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18302 } 18303 } 18304 } 18305 // writer 18306 synchronized (mPackages) { 18307 // If the platform SDK has changed since the last time we booted, 18308 // we need to re-grant app permission to catch any new ones that 18309 // appear. This is really a hack, and means that apps can in some 18310 // cases get permissions that the user didn't initially explicitly 18311 // allow... it would be nice to have some better way to handle 18312 // this situation. 18313 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18314 : mSettings.getInternalVersion(); 18315 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18316 : StorageManager.UUID_PRIVATE_INTERNAL; 18317 18318 int updateFlags = UPDATE_PERMISSIONS_ALL; 18319 if (ver.sdkVersion != mSdkVersion) { 18320 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18321 + mSdkVersion + "; regranting permissions for external"); 18322 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18323 } 18324 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18325 18326 // Yay, everything is now upgraded 18327 ver.forceCurrent(); 18328 18329 // can downgrade to reader 18330 // Persist settings 18331 mSettings.writeLPr(); 18332 } 18333 // Send a broadcast to let everyone know we are done processing 18334 if (pkgList.size() > 0) { 18335 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18336 } 18337 } 18338 18339 /* 18340 * Utility method to unload a list of specified containers 18341 */ 18342 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18343 // Just unmount all valid containers. 18344 for (AsecInstallArgs arg : cidArgs) { 18345 synchronized (mInstallLock) { 18346 arg.doPostDeleteLI(false); 18347 } 18348 } 18349 } 18350 18351 /* 18352 * Unload packages mounted on external media. This involves deleting package 18353 * data from internal structures, sending broadcasts about disabled packages, 18354 * gc'ing to free up references, unmounting all secure containers 18355 * corresponding to packages on external media, and posting a 18356 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18357 * that we always have to post this message if status has been requested no 18358 * matter what. 18359 */ 18360 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18361 final boolean reportStatus) { 18362 if (DEBUG_SD_INSTALL) 18363 Log.i(TAG, "unloading media packages"); 18364 ArrayList<String> pkgList = new ArrayList<String>(); 18365 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18366 final Set<AsecInstallArgs> keys = processCids.keySet(); 18367 for (AsecInstallArgs args : keys) { 18368 String pkgName = args.getPackageName(); 18369 if (DEBUG_SD_INSTALL) 18370 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18371 // Delete package internally 18372 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18373 synchronized (mInstallLock) { 18374 boolean res = deletePackageLI(pkgName, null, false, null, 18375 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 18376 if (res) { 18377 pkgList.add(pkgName); 18378 } else { 18379 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18380 failedList.add(args); 18381 } 18382 } 18383 } 18384 18385 // reader 18386 synchronized (mPackages) { 18387 // We didn't update the settings after removing each package; 18388 // write them now for all packages. 18389 mSettings.writeLPr(); 18390 } 18391 18392 // We have to absolutely send UPDATED_MEDIA_STATUS only 18393 // after confirming that all the receivers processed the ordered 18394 // broadcast when packages get disabled, force a gc to clean things up. 18395 // and unload all the containers. 18396 if (pkgList.size() > 0) { 18397 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18398 new IIntentReceiver.Stub() { 18399 public void performReceive(Intent intent, int resultCode, String data, 18400 Bundle extras, boolean ordered, boolean sticky, 18401 int sendingUser) throws RemoteException { 18402 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18403 reportStatus ? 1 : 0, 1, keys); 18404 mHandler.sendMessage(msg); 18405 } 18406 }); 18407 } else { 18408 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18409 keys); 18410 mHandler.sendMessage(msg); 18411 } 18412 } 18413 18414 private void loadPrivatePackages(final VolumeInfo vol) { 18415 mHandler.post(new Runnable() { 18416 @Override 18417 public void run() { 18418 loadPrivatePackagesInner(vol); 18419 } 18420 }); 18421 } 18422 18423 private void loadPrivatePackagesInner(VolumeInfo vol) { 18424 final String volumeUuid = vol.fsUuid; 18425 if (TextUtils.isEmpty(volumeUuid)) { 18426 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18427 return; 18428 } 18429 18430 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18431 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18432 18433 final VersionInfo ver; 18434 final List<PackageSetting> packages; 18435 synchronized (mPackages) { 18436 ver = mSettings.findOrCreateVersion(volumeUuid); 18437 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18438 } 18439 18440 // TODO: introduce a new concept similar to "frozen" to prevent these 18441 // apps from being launched until after data has been fully reconciled 18442 for (PackageSetting ps : packages) { 18443 synchronized (mInstallLock) { 18444 final PackageParser.Package pkg; 18445 try { 18446 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18447 loaded.add(pkg.applicationInfo); 18448 18449 } catch (PackageManagerException e) { 18450 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18451 } 18452 18453 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18454 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18455 } 18456 } 18457 } 18458 18459 // Reconcile app data for all started/unlocked users 18460 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18461 final UserManager um = mContext.getSystemService(UserManager.class); 18462 for (UserInfo user : um.getUsers()) { 18463 final int flags; 18464 if (um.isUserUnlocked(user.id)) { 18465 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18466 } else if (um.isUserRunning(user.id)) { 18467 flags = StorageManager.FLAG_STORAGE_DE; 18468 } else { 18469 continue; 18470 } 18471 18472 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18473 reconcileAppsData(volumeUuid, user.id, flags); 18474 } 18475 18476 synchronized (mPackages) { 18477 int updateFlags = UPDATE_PERMISSIONS_ALL; 18478 if (ver.sdkVersion != mSdkVersion) { 18479 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18480 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18481 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18482 } 18483 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18484 18485 // Yay, everything is now upgraded 18486 ver.forceCurrent(); 18487 18488 mSettings.writeLPr(); 18489 } 18490 18491 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18492 sendResourcesChangedBroadcast(true, false, loaded, null); 18493 } 18494 18495 private void unloadPrivatePackages(final VolumeInfo vol) { 18496 mHandler.post(new Runnable() { 18497 @Override 18498 public void run() { 18499 unloadPrivatePackagesInner(vol); 18500 } 18501 }); 18502 } 18503 18504 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18505 final String volumeUuid = vol.fsUuid; 18506 if (TextUtils.isEmpty(volumeUuid)) { 18507 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18508 return; 18509 } 18510 18511 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18512 synchronized (mInstallLock) { 18513 synchronized (mPackages) { 18514 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18515 for (PackageSetting ps : packages) { 18516 if (ps.pkg == null) continue; 18517 18518 final ApplicationInfo info = ps.pkg.applicationInfo; 18519 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18520 if (deletePackageLI(ps.name, null, false, null, 18521 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18522 unloaded.add(info); 18523 } else { 18524 Slog.w(TAG, "Failed to unload " + ps.codePath); 18525 } 18526 } 18527 18528 mSettings.writeLPr(); 18529 } 18530 } 18531 18532 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18533 sendResourcesChangedBroadcast(false, false, unloaded, null); 18534 } 18535 18536 /** 18537 * Examine all users present on given mounted volume, and destroy data 18538 * belonging to users that are no longer valid, or whose user ID has been 18539 * recycled. 18540 */ 18541 private void reconcileUsers(String volumeUuid) { 18542 // TODO: also reconcile DE directories 18543 final File[] files = FileUtils 18544 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18545 for (File file : files) { 18546 if (!file.isDirectory()) continue; 18547 18548 final int userId; 18549 final UserInfo info; 18550 try { 18551 userId = Integer.parseInt(file.getName()); 18552 info = sUserManager.getUserInfo(userId); 18553 } catch (NumberFormatException e) { 18554 Slog.w(TAG, "Invalid user directory " + file); 18555 continue; 18556 } 18557 18558 boolean destroyUser = false; 18559 if (info == null) { 18560 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18561 + " because no matching user was found"); 18562 destroyUser = true; 18563 } else { 18564 try { 18565 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18566 } catch (IOException e) { 18567 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18568 + " because we failed to enforce serial number: " + e); 18569 destroyUser = true; 18570 } 18571 } 18572 18573 if (destroyUser) { 18574 synchronized (mInstallLock) { 18575 try { 18576 mInstaller.removeUserDataDirs(volumeUuid, userId); 18577 } catch (InstallerException e) { 18578 Slog.w(TAG, "Failed to clean up user dirs", e); 18579 } 18580 } 18581 } 18582 } 18583 } 18584 18585 private void assertPackageKnown(String volumeUuid, String packageName) 18586 throws PackageManagerException { 18587 synchronized (mPackages) { 18588 final PackageSetting ps = mSettings.mPackages.get(packageName); 18589 if (ps == null) { 18590 throw new PackageManagerException("Package " + packageName + " is unknown"); 18591 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18592 throw new PackageManagerException( 18593 "Package " + packageName + " found on unknown volume " + volumeUuid 18594 + "; expected volume " + ps.volumeUuid); 18595 } 18596 } 18597 } 18598 18599 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18600 throws PackageManagerException { 18601 synchronized (mPackages) { 18602 final PackageSetting ps = mSettings.mPackages.get(packageName); 18603 if (ps == null) { 18604 throw new PackageManagerException("Package " + packageName + " is unknown"); 18605 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18606 throw new PackageManagerException( 18607 "Package " + packageName + " found on unknown volume " + volumeUuid 18608 + "; expected volume " + ps.volumeUuid); 18609 } else if (!ps.getInstalled(userId)) { 18610 throw new PackageManagerException( 18611 "Package " + packageName + " not installed for user " + userId); 18612 } 18613 } 18614 } 18615 18616 /** 18617 * Examine all apps present on given mounted volume, and destroy apps that 18618 * aren't expected, either due to uninstallation or reinstallation on 18619 * another volume. 18620 */ 18621 private void reconcileApps(String volumeUuid) { 18622 final File[] files = FileUtils 18623 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18624 for (File file : files) { 18625 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18626 && !PackageInstallerService.isStageName(file.getName()); 18627 if (!isPackage) { 18628 // Ignore entries which are not packages 18629 continue; 18630 } 18631 18632 try { 18633 final PackageLite pkg = PackageParser.parsePackageLite(file, 18634 PackageParser.PARSE_MUST_BE_APK); 18635 assertPackageKnown(volumeUuid, pkg.packageName); 18636 18637 } catch (PackageParserException | PackageManagerException e) { 18638 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18639 synchronized (mInstallLock) { 18640 removeCodePathLI(file); 18641 } 18642 } 18643 } 18644 } 18645 18646 /** 18647 * Reconcile all app data for the given user. 18648 * <p> 18649 * Verifies that directories exist and that ownership and labeling is 18650 * correct for all installed apps on all mounted volumes. 18651 */ 18652 void reconcileAppsData(int userId, int flags) { 18653 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18654 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18655 final String volumeUuid = vol.getFsUuid(); 18656 reconcileAppsData(volumeUuid, userId, flags); 18657 } 18658 } 18659 18660 /** 18661 * Reconcile all app data on given mounted volume. 18662 * <p> 18663 * Destroys app data that isn't expected, either due to uninstallation or 18664 * reinstallation on another volume. 18665 * <p> 18666 * Verifies that directories exist and that ownership and labeling is 18667 * correct for all installed apps. 18668 */ 18669 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18670 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18671 + Integer.toHexString(flags)); 18672 18673 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18674 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18675 18676 boolean restoreconNeeded = false; 18677 18678 // First look for stale data that doesn't belong, and check if things 18679 // have changed since we did our last restorecon 18680 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18681 if (!isUserKeyUnlocked(userId)) { 18682 throw new RuntimeException( 18683 "Yikes, someone asked us to reconcile CE storage while " + userId 18684 + " was still locked; this would have caused massive data loss!"); 18685 } 18686 18687 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18688 18689 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18690 for (File file : files) { 18691 final String packageName = file.getName(); 18692 try { 18693 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18694 } catch (PackageManagerException e) { 18695 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18696 synchronized (mInstallLock) { 18697 destroyAppDataLI(volumeUuid, packageName, userId, 18698 StorageManager.FLAG_STORAGE_CE); 18699 } 18700 } 18701 } 18702 } 18703 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18704 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18705 18706 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18707 for (File file : files) { 18708 final String packageName = file.getName(); 18709 try { 18710 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18711 } catch (PackageManagerException e) { 18712 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18713 synchronized (mInstallLock) { 18714 destroyAppDataLI(volumeUuid, packageName, userId, 18715 StorageManager.FLAG_STORAGE_DE); 18716 } 18717 } 18718 } 18719 } 18720 18721 // Ensure that data directories are ready to roll for all packages 18722 // installed for this volume and user 18723 final List<PackageSetting> packages; 18724 synchronized (mPackages) { 18725 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18726 } 18727 int preparedCount = 0; 18728 for (PackageSetting ps : packages) { 18729 final String packageName = ps.name; 18730 if (ps.pkg == null) { 18731 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18732 // TODO: might be due to legacy ASEC apps; we should circle back 18733 // and reconcile again once they're scanned 18734 continue; 18735 } 18736 18737 if (ps.getInstalled(userId)) { 18738 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18739 18740 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18741 // We may have just shuffled around app data directories, so 18742 // prepare them one more time 18743 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18744 } 18745 18746 preparedCount++; 18747 } 18748 } 18749 18750 if (restoreconNeeded) { 18751 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18752 SELinuxMMAC.setRestoreconDone(ceDir); 18753 } 18754 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18755 SELinuxMMAC.setRestoreconDone(deDir); 18756 } 18757 } 18758 18759 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18760 + " packages; restoreconNeeded was " + restoreconNeeded); 18761 } 18762 18763 /** 18764 * Prepare app data for the given app just after it was installed or 18765 * upgraded. This method carefully only touches users that it's installed 18766 * for, and it forces a restorecon to handle any seinfo changes. 18767 * <p> 18768 * Verifies that directories exist and that ownership and labeling is 18769 * correct for all installed apps. If there is an ownership mismatch, it 18770 * will try recovering system apps by wiping data; third-party app data is 18771 * left intact. 18772 * <p> 18773 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18774 */ 18775 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18776 prepareAppDataAfterInstallInternal(pkg); 18777 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18778 for (int i = 0; i < childCount; i++) { 18779 PackageParser.Package childPackage = pkg.childPackages.get(i); 18780 prepareAppDataAfterInstallInternal(childPackage); 18781 } 18782 } 18783 18784 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18785 final PackageSetting ps; 18786 synchronized (mPackages) { 18787 ps = mSettings.mPackages.get(pkg.packageName); 18788 mSettings.writeKernelMappingLPr(ps); 18789 } 18790 18791 final UserManager um = mContext.getSystemService(UserManager.class); 18792 for (UserInfo user : um.getUsers()) { 18793 final int flags; 18794 if (um.isUserUnlocked(user.id)) { 18795 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18796 } else if (um.isUserRunning(user.id)) { 18797 flags = StorageManager.FLAG_STORAGE_DE; 18798 } else { 18799 continue; 18800 } 18801 18802 if (ps.getInstalled(user.id)) { 18803 // Whenever an app changes, force a restorecon of its data 18804 // TODO: when user data is locked, mark that we're still dirty 18805 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18806 } 18807 } 18808 } 18809 18810 /** 18811 * Prepare app data for the given app. 18812 * <p> 18813 * Verifies that directories exist and that ownership and labeling is 18814 * correct for all installed apps. If there is an ownership mismatch, this 18815 * will try recovering system apps by wiping data; third-party app data is 18816 * left intact. 18817 */ 18818 private void prepareAppData(String volumeUuid, int userId, int flags, 18819 PackageParser.Package pkg, boolean restoreconNeeded) { 18820 if (DEBUG_APP_DATA) { 18821 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18822 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18823 } 18824 18825 final String packageName = pkg.packageName; 18826 final ApplicationInfo app = pkg.applicationInfo; 18827 final int appId = UserHandle.getAppId(app.uid); 18828 18829 Preconditions.checkNotNull(app.seinfo); 18830 18831 synchronized (mInstallLock) { 18832 try { 18833 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18834 appId, app.seinfo, app.targetSdkVersion); 18835 } catch (InstallerException e) { 18836 if (app.isSystemApp()) { 18837 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18838 + ", but trying to recover: " + e); 18839 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18840 try { 18841 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18842 appId, app.seinfo, app.targetSdkVersion); 18843 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18844 } catch (InstallerException e2) { 18845 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18846 } 18847 } else { 18848 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18849 } 18850 } 18851 18852 if (restoreconNeeded) { 18853 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18854 } 18855 18856 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18857 // Create a native library symlink only if we have native libraries 18858 // and if the native libraries are 32 bit libraries. We do not provide 18859 // this symlink for 64 bit libraries. 18860 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18861 final String nativeLibPath = app.nativeLibraryDir; 18862 try { 18863 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18864 nativeLibPath, userId); 18865 } catch (InstallerException e) { 18866 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18867 } 18868 } 18869 } 18870 } 18871 } 18872 18873 /** 18874 * For system apps on non-FBE devices, this method migrates any existing 18875 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18876 * requested by the app. 18877 */ 18878 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18879 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18880 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18881 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18882 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18883 synchronized (mInstallLock) { 18884 try { 18885 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18886 } catch (InstallerException e) { 18887 logCriticalInfo(Log.WARN, 18888 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18889 } 18890 } 18891 return true; 18892 } else { 18893 return false; 18894 } 18895 } 18896 18897 private void unfreezePackage(String packageName) { 18898 synchronized (mPackages) { 18899 final PackageSetting ps = mSettings.mPackages.get(packageName); 18900 if (ps != null) { 18901 ps.frozen = false; 18902 } 18903 } 18904 } 18905 18906 @Override 18907 public int movePackage(final String packageName, final String volumeUuid) { 18908 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18909 18910 final int moveId = mNextMoveId.getAndIncrement(); 18911 mHandler.post(new Runnable() { 18912 @Override 18913 public void run() { 18914 try { 18915 movePackageInternal(packageName, volumeUuid, moveId); 18916 } catch (PackageManagerException e) { 18917 Slog.w(TAG, "Failed to move " + packageName, e); 18918 mMoveCallbacks.notifyStatusChanged(moveId, 18919 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18920 } 18921 } 18922 }); 18923 return moveId; 18924 } 18925 18926 private void movePackageInternal(final String packageName, final String volumeUuid, 18927 final int moveId) throws PackageManagerException { 18928 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18929 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18930 final PackageManager pm = mContext.getPackageManager(); 18931 18932 final boolean currentAsec; 18933 final String currentVolumeUuid; 18934 final File codeFile; 18935 final String installerPackageName; 18936 final String packageAbiOverride; 18937 final int appId; 18938 final String seinfo; 18939 final String label; 18940 final int targetSdkVersion; 18941 18942 // reader 18943 synchronized (mPackages) { 18944 final PackageParser.Package pkg = mPackages.get(packageName); 18945 final PackageSetting ps = mSettings.mPackages.get(packageName); 18946 if (pkg == null || ps == null) { 18947 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18948 } 18949 18950 if (pkg.applicationInfo.isSystemApp()) { 18951 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18952 "Cannot move system application"); 18953 } 18954 18955 if (pkg.applicationInfo.isExternalAsec()) { 18956 currentAsec = true; 18957 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18958 } else if (pkg.applicationInfo.isForwardLocked()) { 18959 currentAsec = true; 18960 currentVolumeUuid = "forward_locked"; 18961 } else { 18962 currentAsec = false; 18963 currentVolumeUuid = ps.volumeUuid; 18964 18965 final File probe = new File(pkg.codePath); 18966 final File probeOat = new File(probe, "oat"); 18967 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18968 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18969 "Move only supported for modern cluster style installs"); 18970 } 18971 } 18972 18973 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18974 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18975 "Package already moved to " + volumeUuid); 18976 } 18977 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18978 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18979 "Device admin cannot be moved"); 18980 } 18981 18982 if (ps.frozen) { 18983 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18984 "Failed to move already frozen package"); 18985 } 18986 ps.frozen = true; 18987 18988 codeFile = new File(pkg.codePath); 18989 installerPackageName = ps.installerPackageName; 18990 packageAbiOverride = ps.cpuAbiOverrideString; 18991 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18992 seinfo = pkg.applicationInfo.seinfo; 18993 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18994 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18995 } 18996 18997 // Now that we're guarded by frozen state, kill app during move 18998 final long token = Binder.clearCallingIdentity(); 18999 try { 19000 killApplication(packageName, appId, "move pkg"); 19001 } finally { 19002 Binder.restoreCallingIdentity(token); 19003 } 19004 19005 final Bundle extras = new Bundle(); 19006 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19007 extras.putString(Intent.EXTRA_TITLE, label); 19008 mMoveCallbacks.notifyCreated(moveId, extras); 19009 19010 int installFlags; 19011 final boolean moveCompleteApp; 19012 final File measurePath; 19013 19014 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19015 installFlags = INSTALL_INTERNAL; 19016 moveCompleteApp = !currentAsec; 19017 measurePath = Environment.getDataAppDirectory(volumeUuid); 19018 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19019 installFlags = INSTALL_EXTERNAL; 19020 moveCompleteApp = false; 19021 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19022 } else { 19023 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19024 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19025 || !volume.isMountedWritable()) { 19026 unfreezePackage(packageName); 19027 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19028 "Move location not mounted private volume"); 19029 } 19030 19031 Preconditions.checkState(!currentAsec); 19032 19033 installFlags = INSTALL_INTERNAL; 19034 moveCompleteApp = true; 19035 measurePath = Environment.getDataAppDirectory(volumeUuid); 19036 } 19037 19038 final PackageStats stats = new PackageStats(null, -1); 19039 synchronized (mInstaller) { 19040 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19041 unfreezePackage(packageName); 19042 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19043 "Failed to measure package size"); 19044 } 19045 } 19046 19047 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19048 + stats.dataSize); 19049 19050 final long startFreeBytes = measurePath.getFreeSpace(); 19051 final long sizeBytes; 19052 if (moveCompleteApp) { 19053 sizeBytes = stats.codeSize + stats.dataSize; 19054 } else { 19055 sizeBytes = stats.codeSize; 19056 } 19057 19058 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19059 unfreezePackage(packageName); 19060 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19061 "Not enough free space to move"); 19062 } 19063 19064 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19065 19066 final CountDownLatch installedLatch = new CountDownLatch(1); 19067 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19068 @Override 19069 public void onUserActionRequired(Intent intent) throws RemoteException { 19070 throw new IllegalStateException(); 19071 } 19072 19073 @Override 19074 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19075 Bundle extras) throws RemoteException { 19076 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19077 + PackageManager.installStatusToString(returnCode, msg)); 19078 19079 installedLatch.countDown(); 19080 19081 // Regardless of success or failure of the move operation, 19082 // always unfreeze the package 19083 unfreezePackage(packageName); 19084 19085 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19086 switch (status) { 19087 case PackageInstaller.STATUS_SUCCESS: 19088 mMoveCallbacks.notifyStatusChanged(moveId, 19089 PackageManager.MOVE_SUCCEEDED); 19090 break; 19091 case PackageInstaller.STATUS_FAILURE_STORAGE: 19092 mMoveCallbacks.notifyStatusChanged(moveId, 19093 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19094 break; 19095 default: 19096 mMoveCallbacks.notifyStatusChanged(moveId, 19097 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19098 break; 19099 } 19100 } 19101 }; 19102 19103 final MoveInfo move; 19104 if (moveCompleteApp) { 19105 // Kick off a thread to report progress estimates 19106 new Thread() { 19107 @Override 19108 public void run() { 19109 while (true) { 19110 try { 19111 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19112 break; 19113 } 19114 } catch (InterruptedException ignored) { 19115 } 19116 19117 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19118 final int progress = 10 + (int) MathUtils.constrain( 19119 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19120 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19121 } 19122 } 19123 }.start(); 19124 19125 final String dataAppName = codeFile.getName(); 19126 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19127 dataAppName, appId, seinfo, targetSdkVersion); 19128 } else { 19129 move = null; 19130 } 19131 19132 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19133 19134 final Message msg = mHandler.obtainMessage(INIT_COPY); 19135 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19136 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19137 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19138 packageAbiOverride, null); 19139 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19140 msg.obj = params; 19141 19142 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19143 System.identityHashCode(msg.obj)); 19144 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19145 System.identityHashCode(msg.obj)); 19146 19147 mHandler.sendMessage(msg); 19148 } 19149 19150 @Override 19151 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19152 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19153 19154 final int realMoveId = mNextMoveId.getAndIncrement(); 19155 final Bundle extras = new Bundle(); 19156 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19157 mMoveCallbacks.notifyCreated(realMoveId, extras); 19158 19159 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19160 @Override 19161 public void onCreated(int moveId, Bundle extras) { 19162 // Ignored 19163 } 19164 19165 @Override 19166 public void onStatusChanged(int moveId, int status, long estMillis) { 19167 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19168 } 19169 }; 19170 19171 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19172 storage.setPrimaryStorageUuid(volumeUuid, callback); 19173 return realMoveId; 19174 } 19175 19176 @Override 19177 public int getMoveStatus(int moveId) { 19178 mContext.enforceCallingOrSelfPermission( 19179 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19180 return mMoveCallbacks.mLastStatus.get(moveId); 19181 } 19182 19183 @Override 19184 public void registerMoveCallback(IPackageMoveObserver callback) { 19185 mContext.enforceCallingOrSelfPermission( 19186 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19187 mMoveCallbacks.register(callback); 19188 } 19189 19190 @Override 19191 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19192 mContext.enforceCallingOrSelfPermission( 19193 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19194 mMoveCallbacks.unregister(callback); 19195 } 19196 19197 @Override 19198 public boolean setInstallLocation(int loc) { 19199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19200 null); 19201 if (getInstallLocation() == loc) { 19202 return true; 19203 } 19204 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19205 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19206 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19207 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19208 return true; 19209 } 19210 return false; 19211 } 19212 19213 @Override 19214 public int getInstallLocation() { 19215 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19216 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19217 PackageHelper.APP_INSTALL_AUTO); 19218 } 19219 19220 /** Called by UserManagerService */ 19221 void cleanUpUser(UserManagerService userManager, int userHandle) { 19222 synchronized (mPackages) { 19223 mDirtyUsers.remove(userHandle); 19224 mUserNeedsBadging.delete(userHandle); 19225 mSettings.removeUserLPw(userHandle); 19226 mPendingBroadcasts.remove(userHandle); 19227 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19228 } 19229 synchronized (mInstallLock) { 19230 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19231 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19232 final String volumeUuid = vol.getFsUuid(); 19233 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19234 try { 19235 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19236 } catch (InstallerException e) { 19237 Slog.w(TAG, "Failed to remove user data", e); 19238 } 19239 } 19240 synchronized (mPackages) { 19241 removeUnusedPackagesLILPw(userManager, userHandle); 19242 } 19243 } 19244 } 19245 19246 /** 19247 * We're removing userHandle and would like to remove any downloaded packages 19248 * that are no longer in use by any other user. 19249 * @param userHandle the user being removed 19250 */ 19251 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19252 final boolean DEBUG_CLEAN_APKS = false; 19253 int [] users = userManager.getUserIds(); 19254 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19255 while (psit.hasNext()) { 19256 PackageSetting ps = psit.next(); 19257 if (ps.pkg == null) { 19258 continue; 19259 } 19260 final String packageName = ps.pkg.packageName; 19261 // Skip over if system app 19262 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19263 continue; 19264 } 19265 if (DEBUG_CLEAN_APKS) { 19266 Slog.i(TAG, "Checking package " + packageName); 19267 } 19268 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19269 if (keep) { 19270 if (DEBUG_CLEAN_APKS) { 19271 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19272 } 19273 } else { 19274 for (int i = 0; i < users.length; i++) { 19275 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19276 keep = true; 19277 if (DEBUG_CLEAN_APKS) { 19278 Slog.i(TAG, " Keeping package " + packageName + " for user " 19279 + users[i]); 19280 } 19281 break; 19282 } 19283 } 19284 } 19285 if (!keep) { 19286 if (DEBUG_CLEAN_APKS) { 19287 Slog.i(TAG, " Removing package " + packageName); 19288 } 19289 mHandler.post(new Runnable() { 19290 public void run() { 19291 deletePackageX(packageName, userHandle, 0); 19292 } //end run 19293 }); 19294 } 19295 } 19296 } 19297 19298 /** Called by UserManagerService */ 19299 void createNewUser(int userHandle) { 19300 synchronized (mInstallLock) { 19301 try { 19302 mInstaller.createUserConfig(userHandle); 19303 } catch (InstallerException e) { 19304 Slog.w(TAG, "Failed to create user config", e); 19305 } 19306 mSettings.createNewUserLI(this, mInstaller, userHandle); 19307 } 19308 synchronized (mPackages) { 19309 applyFactoryDefaultBrowserLPw(userHandle); 19310 primeDomainVerificationsLPw(userHandle); 19311 } 19312 } 19313 19314 void newUserCreated(final int userHandle) { 19315 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19316 // If permission review for legacy apps is required, we represent 19317 // dagerous permissions for such apps as always granted runtime 19318 // permissions to keep per user flag state whether review is needed. 19319 // Hence, if a new user is added we have to propagate dangerous 19320 // permission grants for these legacy apps. 19321 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19322 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19323 | UPDATE_PERMISSIONS_REPLACE_ALL); 19324 } 19325 } 19326 19327 @Override 19328 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19329 mContext.enforceCallingOrSelfPermission( 19330 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19331 "Only package verification agents can read the verifier device identity"); 19332 19333 synchronized (mPackages) { 19334 return mSettings.getVerifierDeviceIdentityLPw(); 19335 } 19336 } 19337 19338 @Override 19339 public void setPermissionEnforced(String permission, boolean enforced) { 19340 // TODO: Now that we no longer change GID for storage, this should to away. 19341 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19342 "setPermissionEnforced"); 19343 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19344 synchronized (mPackages) { 19345 if (mSettings.mReadExternalStorageEnforced == null 19346 || mSettings.mReadExternalStorageEnforced != enforced) { 19347 mSettings.mReadExternalStorageEnforced = enforced; 19348 mSettings.writeLPr(); 19349 } 19350 } 19351 // kill any non-foreground processes so we restart them and 19352 // grant/revoke the GID. 19353 final IActivityManager am = ActivityManagerNative.getDefault(); 19354 if (am != null) { 19355 final long token = Binder.clearCallingIdentity(); 19356 try { 19357 am.killProcessesBelowForeground("setPermissionEnforcement"); 19358 } catch (RemoteException e) { 19359 } finally { 19360 Binder.restoreCallingIdentity(token); 19361 } 19362 } 19363 } else { 19364 throw new IllegalArgumentException("No selective enforcement for " + permission); 19365 } 19366 } 19367 19368 @Override 19369 @Deprecated 19370 public boolean isPermissionEnforced(String permission) { 19371 return true; 19372 } 19373 19374 @Override 19375 public boolean isStorageLow() { 19376 final long token = Binder.clearCallingIdentity(); 19377 try { 19378 final DeviceStorageMonitorInternal 19379 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19380 if (dsm != null) { 19381 return dsm.isMemoryLow(); 19382 } else { 19383 return false; 19384 } 19385 } finally { 19386 Binder.restoreCallingIdentity(token); 19387 } 19388 } 19389 19390 @Override 19391 public IPackageInstaller getPackageInstaller() { 19392 return mInstallerService; 19393 } 19394 19395 private boolean userNeedsBadging(int userId) { 19396 int index = mUserNeedsBadging.indexOfKey(userId); 19397 if (index < 0) { 19398 final UserInfo userInfo; 19399 final long token = Binder.clearCallingIdentity(); 19400 try { 19401 userInfo = sUserManager.getUserInfo(userId); 19402 } finally { 19403 Binder.restoreCallingIdentity(token); 19404 } 19405 final boolean b; 19406 if (userInfo != null && userInfo.isManagedProfile()) { 19407 b = true; 19408 } else { 19409 b = false; 19410 } 19411 mUserNeedsBadging.put(userId, b); 19412 return b; 19413 } 19414 return mUserNeedsBadging.valueAt(index); 19415 } 19416 19417 @Override 19418 public KeySet getKeySetByAlias(String packageName, String alias) { 19419 if (packageName == null || alias == null) { 19420 return null; 19421 } 19422 synchronized(mPackages) { 19423 final PackageParser.Package pkg = mPackages.get(packageName); 19424 if (pkg == null) { 19425 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19426 throw new IllegalArgumentException("Unknown package: " + packageName); 19427 } 19428 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19429 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19430 } 19431 } 19432 19433 @Override 19434 public KeySet getSigningKeySet(String packageName) { 19435 if (packageName == null) { 19436 return null; 19437 } 19438 synchronized(mPackages) { 19439 final PackageParser.Package pkg = mPackages.get(packageName); 19440 if (pkg == null) { 19441 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19442 throw new IllegalArgumentException("Unknown package: " + packageName); 19443 } 19444 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19445 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19446 throw new SecurityException("May not access signing KeySet of other apps."); 19447 } 19448 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19449 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19450 } 19451 } 19452 19453 @Override 19454 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19455 if (packageName == null || ks == null) { 19456 return false; 19457 } 19458 synchronized(mPackages) { 19459 final PackageParser.Package pkg = mPackages.get(packageName); 19460 if (pkg == null) { 19461 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19462 throw new IllegalArgumentException("Unknown package: " + packageName); 19463 } 19464 IBinder ksh = ks.getToken(); 19465 if (ksh instanceof KeySetHandle) { 19466 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19467 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19468 } 19469 return false; 19470 } 19471 } 19472 19473 @Override 19474 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19475 if (packageName == null || ks == null) { 19476 return false; 19477 } 19478 synchronized(mPackages) { 19479 final PackageParser.Package pkg = mPackages.get(packageName); 19480 if (pkg == null) { 19481 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19482 throw new IllegalArgumentException("Unknown package: " + packageName); 19483 } 19484 IBinder ksh = ks.getToken(); 19485 if (ksh instanceof KeySetHandle) { 19486 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19487 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19488 } 19489 return false; 19490 } 19491 } 19492 19493 private void deletePackageIfUnusedLPr(final String packageName) { 19494 PackageSetting ps = mSettings.mPackages.get(packageName); 19495 if (ps == null) { 19496 return; 19497 } 19498 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19499 // TODO Implement atomic delete if package is unused 19500 // It is currently possible that the package will be deleted even if it is installed 19501 // after this method returns. 19502 mHandler.post(new Runnable() { 19503 public void run() { 19504 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19505 } 19506 }); 19507 } 19508 } 19509 19510 /** 19511 * Check and throw if the given before/after packages would be considered a 19512 * downgrade. 19513 */ 19514 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19515 throws PackageManagerException { 19516 if (after.versionCode < before.mVersionCode) { 19517 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19518 "Update version code " + after.versionCode + " is older than current " 19519 + before.mVersionCode); 19520 } else if (after.versionCode == before.mVersionCode) { 19521 if (after.baseRevisionCode < before.baseRevisionCode) { 19522 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19523 "Update base revision code " + after.baseRevisionCode 19524 + " is older than current " + before.baseRevisionCode); 19525 } 19526 19527 if (!ArrayUtils.isEmpty(after.splitNames)) { 19528 for (int i = 0; i < after.splitNames.length; i++) { 19529 final String splitName = after.splitNames[i]; 19530 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19531 if (j != -1) { 19532 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19533 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19534 "Update split " + splitName + " revision code " 19535 + after.splitRevisionCodes[i] + " is older than current " 19536 + before.splitRevisionCodes[j]); 19537 } 19538 } 19539 } 19540 } 19541 } 19542 } 19543 19544 private static class MoveCallbacks extends Handler { 19545 private static final int MSG_CREATED = 1; 19546 private static final int MSG_STATUS_CHANGED = 2; 19547 19548 private final RemoteCallbackList<IPackageMoveObserver> 19549 mCallbacks = new RemoteCallbackList<>(); 19550 19551 private final SparseIntArray mLastStatus = new SparseIntArray(); 19552 19553 public MoveCallbacks(Looper looper) { 19554 super(looper); 19555 } 19556 19557 public void register(IPackageMoveObserver callback) { 19558 mCallbacks.register(callback); 19559 } 19560 19561 public void unregister(IPackageMoveObserver callback) { 19562 mCallbacks.unregister(callback); 19563 } 19564 19565 @Override 19566 public void handleMessage(Message msg) { 19567 final SomeArgs args = (SomeArgs) msg.obj; 19568 final int n = mCallbacks.beginBroadcast(); 19569 for (int i = 0; i < n; i++) { 19570 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19571 try { 19572 invokeCallback(callback, msg.what, args); 19573 } catch (RemoteException ignored) { 19574 } 19575 } 19576 mCallbacks.finishBroadcast(); 19577 args.recycle(); 19578 } 19579 19580 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19581 throws RemoteException { 19582 switch (what) { 19583 case MSG_CREATED: { 19584 callback.onCreated(args.argi1, (Bundle) args.arg2); 19585 break; 19586 } 19587 case MSG_STATUS_CHANGED: { 19588 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19589 break; 19590 } 19591 } 19592 } 19593 19594 private void notifyCreated(int moveId, Bundle extras) { 19595 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19596 19597 final SomeArgs args = SomeArgs.obtain(); 19598 args.argi1 = moveId; 19599 args.arg2 = extras; 19600 obtainMessage(MSG_CREATED, args).sendToTarget(); 19601 } 19602 19603 private void notifyStatusChanged(int moveId, int status) { 19604 notifyStatusChanged(moveId, status, -1); 19605 } 19606 19607 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19608 Slog.v(TAG, "Move " + moveId + " status " + status); 19609 19610 final SomeArgs args = SomeArgs.obtain(); 19611 args.argi1 = moveId; 19612 args.argi2 = status; 19613 args.arg3 = estMillis; 19614 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19615 19616 synchronized (mLastStatus) { 19617 mLastStatus.put(moveId, status); 19618 } 19619 } 19620 } 19621 19622 private final static class OnPermissionChangeListeners extends Handler { 19623 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19624 19625 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19626 new RemoteCallbackList<>(); 19627 19628 public OnPermissionChangeListeners(Looper looper) { 19629 super(looper); 19630 } 19631 19632 @Override 19633 public void handleMessage(Message msg) { 19634 switch (msg.what) { 19635 case MSG_ON_PERMISSIONS_CHANGED: { 19636 final int uid = msg.arg1; 19637 handleOnPermissionsChanged(uid); 19638 } break; 19639 } 19640 } 19641 19642 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19643 mPermissionListeners.register(listener); 19644 19645 } 19646 19647 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19648 mPermissionListeners.unregister(listener); 19649 } 19650 19651 public void onPermissionsChanged(int uid) { 19652 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19653 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19654 } 19655 } 19656 19657 private void handleOnPermissionsChanged(int uid) { 19658 final int count = mPermissionListeners.beginBroadcast(); 19659 try { 19660 for (int i = 0; i < count; i++) { 19661 IOnPermissionsChangeListener callback = mPermissionListeners 19662 .getBroadcastItem(i); 19663 try { 19664 callback.onPermissionsChanged(uid); 19665 } catch (RemoteException e) { 19666 Log.e(TAG, "Permission listener is dead", e); 19667 } 19668 } 19669 } finally { 19670 mPermissionListeners.finishBroadcast(); 19671 } 19672 } 19673 } 19674 19675 private class PackageManagerInternalImpl extends PackageManagerInternal { 19676 @Override 19677 public void setLocationPackagesProvider(PackagesProvider provider) { 19678 synchronized (mPackages) { 19679 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19680 } 19681 } 19682 19683 @Override 19684 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19685 synchronized (mPackages) { 19686 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19687 } 19688 } 19689 19690 @Override 19691 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19692 synchronized (mPackages) { 19693 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19694 } 19695 } 19696 19697 @Override 19698 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19699 synchronized (mPackages) { 19700 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19701 } 19702 } 19703 19704 @Override 19705 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19706 synchronized (mPackages) { 19707 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19708 } 19709 } 19710 19711 @Override 19712 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19713 synchronized (mPackages) { 19714 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19715 } 19716 } 19717 19718 @Override 19719 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19720 synchronized (mPackages) { 19721 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19722 packageName, userId); 19723 } 19724 } 19725 19726 @Override 19727 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19728 synchronized (mPackages) { 19729 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19730 packageName, userId); 19731 } 19732 } 19733 19734 @Override 19735 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19736 synchronized (mPackages) { 19737 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19738 packageName, userId); 19739 } 19740 } 19741 19742 @Override 19743 public void setKeepUninstalledPackages(final List<String> packageList) { 19744 Preconditions.checkNotNull(packageList); 19745 List<String> removedFromList = null; 19746 synchronized (mPackages) { 19747 if (mKeepUninstalledPackages != null) { 19748 final int packagesCount = mKeepUninstalledPackages.size(); 19749 for (int i = 0; i < packagesCount; i++) { 19750 String oldPackage = mKeepUninstalledPackages.get(i); 19751 if (packageList != null && packageList.contains(oldPackage)) { 19752 continue; 19753 } 19754 if (removedFromList == null) { 19755 removedFromList = new ArrayList<>(); 19756 } 19757 removedFromList.add(oldPackage); 19758 } 19759 } 19760 mKeepUninstalledPackages = new ArrayList<>(packageList); 19761 if (removedFromList != null) { 19762 final int removedCount = removedFromList.size(); 19763 for (int i = 0; i < removedCount; i++) { 19764 deletePackageIfUnusedLPr(removedFromList.get(i)); 19765 } 19766 } 19767 } 19768 } 19769 19770 @Override 19771 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19772 synchronized (mPackages) { 19773 // If we do not support permission review, done. 19774 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19775 return false; 19776 } 19777 19778 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19779 if (packageSetting == null) { 19780 return false; 19781 } 19782 19783 // Permission review applies only to apps not supporting the new permission model. 19784 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19785 return false; 19786 } 19787 19788 // Legacy apps have the permission and get user consent on launch. 19789 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19790 return permissionsState.isPermissionReviewRequired(userId); 19791 } 19792 } 19793 19794 @Override 19795 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19796 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19797 } 19798 19799 @Override 19800 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19801 int userId) { 19802 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19803 } 19804 } 19805 19806 @Override 19807 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19808 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19809 synchronized (mPackages) { 19810 final long identity = Binder.clearCallingIdentity(); 19811 try { 19812 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19813 packageNames, userId); 19814 } finally { 19815 Binder.restoreCallingIdentity(identity); 19816 } 19817 } 19818 } 19819 19820 private static void enforceSystemOrPhoneCaller(String tag) { 19821 int callingUid = Binder.getCallingUid(); 19822 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19823 throw new SecurityException( 19824 "Cannot call " + tag + " from UID " + callingUid); 19825 } 19826 } 19827 19828 boolean isHistoricalPackageUsageAvailable() { 19829 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19830 } 19831 19832 /** 19833 * Return a <b>copy</b> of the collection of packages known to the package manager. 19834 * @return A copy of the values of mPackages. 19835 */ 19836 Collection<PackageParser.Package> getPackages() { 19837 synchronized (mPackages) { 19838 return new ArrayList<>(mPackages.values()); 19839 } 19840 } 19841 19842 /** 19843 * Logs process start information (including base APK hash) to the security log. 19844 * @hide 19845 */ 19846 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19847 String apkFile, int pid) { 19848 if (!SecurityLog.isLoggingEnabled()) { 19849 return; 19850 } 19851 Bundle data = new Bundle(); 19852 data.putLong("startTimestamp", System.currentTimeMillis()); 19853 data.putString("processName", processName); 19854 data.putInt("uid", uid); 19855 data.putString("seinfo", seinfo); 19856 data.putString("apkFile", apkFile); 19857 data.putInt("pid", pid); 19858 Message msg = mProcessLoggingHandler.obtainMessage( 19859 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19860 msg.setData(data); 19861 mProcessLoggingHandler.sendMessage(msg); 19862 } 19863} 19864