PackageManagerService.java revision e11eb10e8d994b49e6e04cd14fccb402f8f48ec9
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 (!isFirstBoot()) { 7018 try { 7019 ActivityManagerNative.getDefault().showBootMessage( 7020 mContext.getResources().getString(R.string.android_upgrading_apk, 7021 curr, total), true); 7022 } catch (RemoteException e) { 7023 } 7024 } 7025 7026 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 7027 // If the cache was pruned, any compiled odex files will likely be out of date 7028 // and would have to be patched (would be SELF_PATCHOAT, which is deprecated). 7029 // Instead, force the extraction in this case. 7030 performDexOpt(pkg.packageName, 7031 null /* instructionSet */, 7032 false /* checkProfiles */, 7033 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7034 false /* force */); 7035 } 7036 } 7037 } 7038 7039 @Override 7040 public void notifyPackageUse(String packageName) { 7041 synchronized (mPackages) { 7042 PackageParser.Package p = mPackages.get(packageName); 7043 if (p == null) { 7044 return; 7045 } 7046 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7047 } 7048 } 7049 7050 // TODO: this is not used nor needed. Delete it. 7051 @Override 7052 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7053 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7054 getFullCompilerFilter(), false /* force */); 7055 } 7056 7057 @Override 7058 public boolean performDexOpt(String packageName, String instructionSet, 7059 boolean checkProfiles, int compileReason, boolean force) { 7060 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7061 getCompilerFilterForReason(compileReason), force); 7062 } 7063 7064 @Override 7065 public boolean performDexOptMode(String packageName, String instructionSet, 7066 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7067 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7068 targetCompilerFilter, force); 7069 } 7070 7071 private boolean performDexOptTraced(String packageName, String instructionSet, 7072 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7073 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7074 try { 7075 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7076 targetCompilerFilter, force); 7077 } finally { 7078 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7079 } 7080 } 7081 7082 private boolean performDexOptInternal(String packageName, String instructionSet, 7083 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7084 PackageParser.Package p; 7085 final String targetInstructionSet; 7086 synchronized (mPackages) { 7087 p = mPackages.get(packageName); 7088 if (p == null) { 7089 return false; 7090 } 7091 mPackageUsage.write(false); 7092 7093 targetInstructionSet = instructionSet != null ? instructionSet : 7094 getPrimaryInstructionSet(p.applicationInfo); 7095 } 7096 long callingId = Binder.clearCallingIdentity(); 7097 try { 7098 synchronized (mInstallLock) { 7099 final String[] instructionSets = new String[] { targetInstructionSet }; 7100 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7101 checkProfiles, targetCompilerFilter, force); 7102 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 7103 } 7104 } finally { 7105 Binder.restoreCallingIdentity(callingId); 7106 } 7107 } 7108 7109 public ArraySet<String> getOptimizablePackages() { 7110 ArraySet<String> pkgs = new ArraySet<String>(); 7111 synchronized (mPackages) { 7112 for (PackageParser.Package p : mPackages.values()) { 7113 if (PackageDexOptimizer.canOptimizePackage(p)) { 7114 pkgs.add(p.packageName); 7115 } 7116 } 7117 } 7118 return pkgs; 7119 } 7120 7121 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7122 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7123 boolean force) { 7124 // Select the dex optimizer based on the force parameter. 7125 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7126 // allocate an object here. 7127 PackageDexOptimizer pdo = force 7128 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7129 : mPackageDexOptimizer; 7130 7131 // Optimize all dependencies first. Note: we ignore the return value and march on 7132 // on errors. 7133 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7134 if (!deps.isEmpty()) { 7135 for (PackageParser.Package depPackage : deps) { 7136 // TODO: Analyze and investigate if we (should) profile libraries. 7137 // Currently this will do a full compilation of the library by default. 7138 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7139 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7140 } 7141 } 7142 7143 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7144 } 7145 7146 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7147 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7148 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7149 Set<String> collectedNames = new HashSet<>(); 7150 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7151 7152 retValue.remove(p); 7153 7154 return retValue; 7155 } else { 7156 return Collections.emptyList(); 7157 } 7158 } 7159 7160 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7161 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7162 if (!collectedNames.contains(p.packageName)) { 7163 collectedNames.add(p.packageName); 7164 collected.add(p); 7165 7166 if (p.usesLibraries != null) { 7167 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7168 } 7169 if (p.usesOptionalLibraries != null) { 7170 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7171 collectedNames); 7172 } 7173 } 7174 } 7175 7176 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7177 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7178 for (String libName : libs) { 7179 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7180 if (libPkg != null) { 7181 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7182 } 7183 } 7184 } 7185 7186 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7187 synchronized (mPackages) { 7188 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7189 if (lib != null && lib.apk != null) { 7190 return mPackages.get(lib.apk); 7191 } 7192 } 7193 return null; 7194 } 7195 7196 public void shutdown() { 7197 mPackageUsage.write(true); 7198 } 7199 7200 @Override 7201 public void forceDexOpt(String packageName) { 7202 enforceSystemOrRoot("forceDexOpt"); 7203 7204 PackageParser.Package pkg; 7205 synchronized (mPackages) { 7206 pkg = mPackages.get(packageName); 7207 if (pkg == null) { 7208 throw new IllegalArgumentException("Unknown package: " + packageName); 7209 } 7210 } 7211 7212 synchronized (mInstallLock) { 7213 final String[] instructionSets = new String[] { 7214 getPrimaryInstructionSet(pkg.applicationInfo) }; 7215 7216 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7217 7218 // Whoever is calling forceDexOpt wants a fully compiled package. 7219 // Don't use profiles since that may cause compilation to be skipped. 7220 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7221 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7222 true /* force */); 7223 7224 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7225 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7226 throw new IllegalStateException("Failed to dexopt: " + res); 7227 } 7228 } 7229 } 7230 7231 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7232 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7233 Slog.w(TAG, "Unable to update from " + oldPkg.name 7234 + " to " + newPkg.packageName 7235 + ": old package not in system partition"); 7236 return false; 7237 } else if (mPackages.get(oldPkg.name) != null) { 7238 Slog.w(TAG, "Unable to update from " + oldPkg.name 7239 + " to " + newPkg.packageName 7240 + ": old package still exists"); 7241 return false; 7242 } 7243 return true; 7244 } 7245 7246 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7247 // TODO: triage flags as part of 26466827 7248 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7249 7250 boolean res = true; 7251 final int[] users = sUserManager.getUserIds(); 7252 for (int user : users) { 7253 try { 7254 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7255 } catch (InstallerException e) { 7256 Slog.w(TAG, "Failed to delete data directory", e); 7257 res = false; 7258 } 7259 } 7260 return res; 7261 } 7262 7263 void removeCodePathLI(File codePath) { 7264 if (codePath.isDirectory()) { 7265 try { 7266 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7267 } catch (InstallerException e) { 7268 Slog.w(TAG, "Failed to remove code path", e); 7269 } 7270 } else { 7271 codePath.delete(); 7272 } 7273 } 7274 7275 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7276 try { 7277 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7278 } catch (InstallerException e) { 7279 Slog.w(TAG, "Failed to destroy app data", e); 7280 } 7281 } 7282 7283 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7284 int appId, String seinfo) { 7285 try { 7286 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7287 } catch (InstallerException e) { 7288 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7289 } 7290 } 7291 7292 private void deleteProfilesLI(String packageName, boolean destroy) { 7293 final PackageParser.Package pkg; 7294 synchronized (mPackages) { 7295 pkg = mPackages.get(packageName); 7296 } 7297 if (pkg == null) { 7298 Slog.w(TAG, "Failed to delete profiles. No package: " + packageName); 7299 return; 7300 } 7301 deleteProfilesLI(pkg, destroy); 7302 } 7303 7304 private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) { 7305 try { 7306 if (destroy) { 7307 mInstaller.destroyAppProfiles(pkg.packageName); 7308 } else { 7309 mInstaller.clearAppProfiles(pkg.packageName); 7310 } 7311 } catch (InstallerException ex) { 7312 Log.e(TAG, "Could not delete profiles for package " + pkg.packageName); 7313 } 7314 } 7315 7316 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7317 final PackageParser.Package pkg; 7318 synchronized (mPackages) { 7319 pkg = mPackages.get(packageName); 7320 } 7321 if (pkg == null) { 7322 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7323 return; 7324 } 7325 deleteCodeCacheDirsLI(pkg); 7326 } 7327 7328 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7329 // TODO: triage flags as part of 26466827 7330 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7331 7332 int[] users = sUserManager.getUserIds(); 7333 int res = 0; 7334 for (int user : users) { 7335 // Remove the parent code cache 7336 try { 7337 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7338 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7339 } catch (InstallerException e) { 7340 Slog.w(TAG, "Failed to delete code cache directory", e); 7341 } 7342 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7343 for (int i = 0; i < childCount; i++) { 7344 PackageParser.Package childPkg = pkg.childPackages.get(i); 7345 // Remove the child code cache 7346 try { 7347 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7348 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7349 } catch (InstallerException e) { 7350 Slog.w(TAG, "Failed to delete code cache directory", e); 7351 } 7352 } 7353 } 7354 } 7355 7356 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7357 long lastUpdateTime) { 7358 // Set parent install/update time 7359 PackageSetting ps = (PackageSetting) pkg.mExtras; 7360 if (ps != null) { 7361 ps.firstInstallTime = firstInstallTime; 7362 ps.lastUpdateTime = lastUpdateTime; 7363 } 7364 // Set children install/update time 7365 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7366 for (int i = 0; i < childCount; i++) { 7367 PackageParser.Package childPkg = pkg.childPackages.get(i); 7368 ps = (PackageSetting) childPkg.mExtras; 7369 if (ps != null) { 7370 ps.firstInstallTime = firstInstallTime; 7371 ps.lastUpdateTime = lastUpdateTime; 7372 } 7373 } 7374 } 7375 7376 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7377 PackageParser.Package changingLib) { 7378 if (file.path != null) { 7379 usesLibraryFiles.add(file.path); 7380 return; 7381 } 7382 PackageParser.Package p = mPackages.get(file.apk); 7383 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7384 // If we are doing this while in the middle of updating a library apk, 7385 // then we need to make sure to use that new apk for determining the 7386 // dependencies here. (We haven't yet finished committing the new apk 7387 // to the package manager state.) 7388 if (p == null || p.packageName.equals(changingLib.packageName)) { 7389 p = changingLib; 7390 } 7391 } 7392 if (p != null) { 7393 usesLibraryFiles.addAll(p.getAllCodePaths()); 7394 } 7395 } 7396 7397 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7398 PackageParser.Package changingLib) throws PackageManagerException { 7399 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7400 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7401 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7402 for (int i=0; i<N; i++) { 7403 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7404 if (file == null) { 7405 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7406 "Package " + pkg.packageName + " requires unavailable shared library " 7407 + pkg.usesLibraries.get(i) + "; failing!"); 7408 } 7409 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7410 } 7411 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7412 for (int i=0; i<N; i++) { 7413 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7414 if (file == null) { 7415 Slog.w(TAG, "Package " + pkg.packageName 7416 + " desires unavailable shared library " 7417 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7418 } else { 7419 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7420 } 7421 } 7422 N = usesLibraryFiles.size(); 7423 if (N > 0) { 7424 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7425 } else { 7426 pkg.usesLibraryFiles = null; 7427 } 7428 } 7429 } 7430 7431 private static boolean hasString(List<String> list, List<String> which) { 7432 if (list == null) { 7433 return false; 7434 } 7435 for (int i=list.size()-1; i>=0; i--) { 7436 for (int j=which.size()-1; j>=0; j--) { 7437 if (which.get(j).equals(list.get(i))) { 7438 return true; 7439 } 7440 } 7441 } 7442 return false; 7443 } 7444 7445 private void updateAllSharedLibrariesLPw() { 7446 for (PackageParser.Package pkg : mPackages.values()) { 7447 try { 7448 updateSharedLibrariesLPw(pkg, null); 7449 } catch (PackageManagerException e) { 7450 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7451 } 7452 } 7453 } 7454 7455 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7456 PackageParser.Package changingPkg) { 7457 ArrayList<PackageParser.Package> res = null; 7458 for (PackageParser.Package pkg : mPackages.values()) { 7459 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7460 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7461 if (res == null) { 7462 res = new ArrayList<PackageParser.Package>(); 7463 } 7464 res.add(pkg); 7465 try { 7466 updateSharedLibrariesLPw(pkg, changingPkg); 7467 } catch (PackageManagerException e) { 7468 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7469 } 7470 } 7471 } 7472 return res; 7473 } 7474 7475 /** 7476 * Derive the value of the {@code cpuAbiOverride} based on the provided 7477 * value and an optional stored value from the package settings. 7478 */ 7479 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7480 String cpuAbiOverride = null; 7481 7482 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7483 cpuAbiOverride = null; 7484 } else if (abiOverride != null) { 7485 cpuAbiOverride = abiOverride; 7486 } else if (settings != null) { 7487 cpuAbiOverride = settings.cpuAbiOverrideString; 7488 } 7489 7490 return cpuAbiOverride; 7491 } 7492 7493 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7494 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7495 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7496 // If the package has children and this is the first dive in the function 7497 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7498 // whether all packages (parent and children) would be successfully scanned 7499 // before the actual scan since scanning mutates internal state and we want 7500 // to atomically install the package and its children. 7501 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7502 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7503 scanFlags |= SCAN_CHECK_ONLY; 7504 } 7505 } else { 7506 scanFlags &= ~SCAN_CHECK_ONLY; 7507 } 7508 7509 final PackageParser.Package scannedPkg; 7510 try { 7511 // Scan the parent 7512 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7513 // Scan the children 7514 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7515 for (int i = 0; i < childCount; i++) { 7516 PackageParser.Package childPkg = pkg.childPackages.get(i); 7517 scanPackageLI(childPkg, parseFlags, 7518 scanFlags, currentTime, user); 7519 } 7520 } finally { 7521 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7522 } 7523 7524 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7525 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7526 } 7527 7528 return scannedPkg; 7529 } 7530 7531 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7532 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7533 boolean success = false; 7534 try { 7535 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7536 currentTime, user); 7537 success = true; 7538 return res; 7539 } finally { 7540 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7541 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7542 } 7543 } 7544 } 7545 7546 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7547 int scanFlags, long currentTime, UserHandle user) 7548 throws PackageManagerException { 7549 final File scanFile = new File(pkg.codePath); 7550 if (pkg.applicationInfo.getCodePath() == null || 7551 pkg.applicationInfo.getResourcePath() == null) { 7552 // Bail out. The resource and code paths haven't been set. 7553 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7554 "Code and resource paths haven't been set correctly"); 7555 } 7556 7557 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7558 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7559 } else { 7560 // Only allow system apps to be flagged as core apps. 7561 pkg.coreApp = false; 7562 } 7563 7564 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7565 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7566 } 7567 7568 if (mCustomResolverComponentName != null && 7569 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7570 setUpCustomResolverActivity(pkg); 7571 } 7572 7573 if (pkg.packageName.equals("android")) { 7574 synchronized (mPackages) { 7575 if (mAndroidApplication != null) { 7576 Slog.w(TAG, "*************************************************"); 7577 Slog.w(TAG, "Core android package being redefined. Skipping."); 7578 Slog.w(TAG, " file=" + scanFile); 7579 Slog.w(TAG, "*************************************************"); 7580 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7581 "Core android package being redefined. Skipping."); 7582 } 7583 7584 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7585 // Set up information for our fall-back user intent resolution activity. 7586 mPlatformPackage = pkg; 7587 pkg.mVersionCode = mSdkVersion; 7588 mAndroidApplication = pkg.applicationInfo; 7589 7590 if (!mResolverReplaced) { 7591 mResolveActivity.applicationInfo = mAndroidApplication; 7592 mResolveActivity.name = ResolverActivity.class.getName(); 7593 mResolveActivity.packageName = mAndroidApplication.packageName; 7594 mResolveActivity.processName = "system:ui"; 7595 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7596 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7597 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7598 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7599 mResolveActivity.exported = true; 7600 mResolveActivity.enabled = true; 7601 mResolveInfo.activityInfo = mResolveActivity; 7602 mResolveInfo.priority = 0; 7603 mResolveInfo.preferredOrder = 0; 7604 mResolveInfo.match = 0; 7605 mResolveComponentName = new ComponentName( 7606 mAndroidApplication.packageName, mResolveActivity.name); 7607 } 7608 } 7609 } 7610 } 7611 7612 if (DEBUG_PACKAGE_SCANNING) { 7613 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7614 Log.d(TAG, "Scanning package " + pkg.packageName); 7615 } 7616 7617 synchronized (mPackages) { 7618 if (mPackages.containsKey(pkg.packageName) 7619 || mSharedLibraries.containsKey(pkg.packageName)) { 7620 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7621 "Application package " + pkg.packageName 7622 + " already installed. Skipping duplicate."); 7623 } 7624 7625 // If we're only installing presumed-existing packages, require that the 7626 // scanned APK is both already known and at the path previously established 7627 // for it. Previously unknown packages we pick up normally, but if we have an 7628 // a priori expectation about this package's install presence, enforce it. 7629 // With a singular exception for new system packages. When an OTA contains 7630 // a new system package, we allow the codepath to change from a system location 7631 // to the user-installed location. If we don't allow this change, any newer, 7632 // user-installed version of the application will be ignored. 7633 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7634 if (mExpectingBetter.containsKey(pkg.packageName)) { 7635 logCriticalInfo(Log.WARN, 7636 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7637 } else { 7638 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7639 if (known != null) { 7640 if (DEBUG_PACKAGE_SCANNING) { 7641 Log.d(TAG, "Examining " + pkg.codePath 7642 + " and requiring known paths " + known.codePathString 7643 + " & " + known.resourcePathString); 7644 } 7645 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7646 || !pkg.applicationInfo.getResourcePath().equals( 7647 known.resourcePathString)) { 7648 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7649 "Application package " + pkg.packageName 7650 + " found at " + pkg.applicationInfo.getCodePath() 7651 + " but expected at " + known.codePathString 7652 + "; ignoring."); 7653 } 7654 } 7655 } 7656 } 7657 } 7658 7659 // Initialize package source and resource directories 7660 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7661 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7662 7663 SharedUserSetting suid = null; 7664 PackageSetting pkgSetting = null; 7665 7666 if (!isSystemApp(pkg)) { 7667 // Only system apps can use these features. 7668 pkg.mOriginalPackages = null; 7669 pkg.mRealPackage = null; 7670 pkg.mAdoptPermissions = null; 7671 } 7672 7673 // Getting the package setting may have a side-effect, so if we 7674 // are only checking if scan would succeed, stash a copy of the 7675 // old setting to restore at the end. 7676 PackageSetting nonMutatedPs = null; 7677 7678 // writer 7679 synchronized (mPackages) { 7680 if (pkg.mSharedUserId != null) { 7681 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7682 if (suid == null) { 7683 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7684 "Creating application package " + pkg.packageName 7685 + " for shared user failed"); 7686 } 7687 if (DEBUG_PACKAGE_SCANNING) { 7688 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7689 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7690 + "): packages=" + suid.packages); 7691 } 7692 } 7693 7694 // Check if we are renaming from an original package name. 7695 PackageSetting origPackage = null; 7696 String realName = null; 7697 if (pkg.mOriginalPackages != null) { 7698 // This package may need to be renamed to a previously 7699 // installed name. Let's check on that... 7700 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7701 if (pkg.mOriginalPackages.contains(renamed)) { 7702 // This package had originally been installed as the 7703 // original name, and we have already taken care of 7704 // transitioning to the new one. Just update the new 7705 // one to continue using the old name. 7706 realName = pkg.mRealPackage; 7707 if (!pkg.packageName.equals(renamed)) { 7708 // Callers into this function may have already taken 7709 // care of renaming the package; only do it here if 7710 // it is not already done. 7711 pkg.setPackageName(renamed); 7712 } 7713 7714 } else { 7715 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7716 if ((origPackage = mSettings.peekPackageLPr( 7717 pkg.mOriginalPackages.get(i))) != null) { 7718 // We do have the package already installed under its 7719 // original name... should we use it? 7720 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7721 // New package is not compatible with original. 7722 origPackage = null; 7723 continue; 7724 } else if (origPackage.sharedUser != null) { 7725 // Make sure uid is compatible between packages. 7726 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7727 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7728 + " to " + pkg.packageName + ": old uid " 7729 + origPackage.sharedUser.name 7730 + " differs from " + pkg.mSharedUserId); 7731 origPackage = null; 7732 continue; 7733 } 7734 } else { 7735 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7736 + pkg.packageName + " to old name " + origPackage.name); 7737 } 7738 break; 7739 } 7740 } 7741 } 7742 } 7743 7744 if (mTransferedPackages.contains(pkg.packageName)) { 7745 Slog.w(TAG, "Package " + pkg.packageName 7746 + " was transferred to another, but its .apk remains"); 7747 } 7748 7749 // See comments in nonMutatedPs declaration 7750 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7751 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7752 if (foundPs != null) { 7753 nonMutatedPs = new PackageSetting(foundPs); 7754 } 7755 } 7756 7757 // Just create the setting, don't add it yet. For already existing packages 7758 // the PkgSetting exists already and doesn't have to be created. 7759 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7760 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7761 pkg.applicationInfo.primaryCpuAbi, 7762 pkg.applicationInfo.secondaryCpuAbi, 7763 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7764 user, false); 7765 if (pkgSetting == null) { 7766 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7767 "Creating application package " + pkg.packageName + " failed"); 7768 } 7769 7770 if (pkgSetting.origPackage != null) { 7771 // If we are first transitioning from an original package, 7772 // fix up the new package's name now. We need to do this after 7773 // looking up the package under its new name, so getPackageLP 7774 // can take care of fiddling things correctly. 7775 pkg.setPackageName(origPackage.name); 7776 7777 // File a report about this. 7778 String msg = "New package " + pkgSetting.realName 7779 + " renamed to replace old package " + pkgSetting.name; 7780 reportSettingsProblem(Log.WARN, msg); 7781 7782 // Make a note of it. 7783 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7784 mTransferedPackages.add(origPackage.name); 7785 } 7786 7787 // No longer need to retain this. 7788 pkgSetting.origPackage = null; 7789 } 7790 7791 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7792 // Make a note of it. 7793 mTransferedPackages.add(pkg.packageName); 7794 } 7795 7796 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7797 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7798 } 7799 7800 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7801 // Check all shared libraries and map to their actual file path. 7802 // We only do this here for apps not on a system dir, because those 7803 // are the only ones that can fail an install due to this. We 7804 // will take care of the system apps by updating all of their 7805 // library paths after the scan is done. 7806 updateSharedLibrariesLPw(pkg, null); 7807 } 7808 7809 if (mFoundPolicyFile) { 7810 SELinuxMMAC.assignSeinfoValue(pkg); 7811 } 7812 7813 pkg.applicationInfo.uid = pkgSetting.appId; 7814 pkg.mExtras = pkgSetting; 7815 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7816 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7817 // We just determined the app is signed correctly, so bring 7818 // over the latest parsed certs. 7819 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7820 } else { 7821 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7822 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7823 "Package " + pkg.packageName + " upgrade keys do not match the " 7824 + "previously installed version"); 7825 } else { 7826 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7827 String msg = "System package " + pkg.packageName 7828 + " signature changed; retaining data."; 7829 reportSettingsProblem(Log.WARN, msg); 7830 } 7831 } 7832 } else { 7833 try { 7834 verifySignaturesLP(pkgSetting, pkg); 7835 // We just determined the app is signed correctly, so bring 7836 // over the latest parsed certs. 7837 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7838 } catch (PackageManagerException e) { 7839 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7840 throw e; 7841 } 7842 // The signature has changed, but this package is in the system 7843 // image... let's recover! 7844 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7845 // However... if this package is part of a shared user, but it 7846 // doesn't match the signature of the shared user, let's fail. 7847 // What this means is that you can't change the signatures 7848 // associated with an overall shared user, which doesn't seem all 7849 // that unreasonable. 7850 if (pkgSetting.sharedUser != null) { 7851 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7852 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7853 throw new PackageManagerException( 7854 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7855 "Signature mismatch for shared user: " 7856 + pkgSetting.sharedUser); 7857 } 7858 } 7859 // File a report about this. 7860 String msg = "System package " + pkg.packageName 7861 + " signature changed; retaining data."; 7862 reportSettingsProblem(Log.WARN, msg); 7863 } 7864 } 7865 // Verify that this new package doesn't have any content providers 7866 // that conflict with existing packages. Only do this if the 7867 // package isn't already installed, since we don't want to break 7868 // things that are installed. 7869 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7870 final int N = pkg.providers.size(); 7871 int i; 7872 for (i=0; i<N; i++) { 7873 PackageParser.Provider p = pkg.providers.get(i); 7874 if (p.info.authority != null) { 7875 String names[] = p.info.authority.split(";"); 7876 for (int j = 0; j < names.length; j++) { 7877 if (mProvidersByAuthority.containsKey(names[j])) { 7878 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7879 final String otherPackageName = 7880 ((other != null && other.getComponentName() != null) ? 7881 other.getComponentName().getPackageName() : "?"); 7882 throw new PackageManagerException( 7883 INSTALL_FAILED_CONFLICTING_PROVIDER, 7884 "Can't install because provider name " + names[j] 7885 + " (in package " + pkg.applicationInfo.packageName 7886 + ") is already used by " + otherPackageName); 7887 } 7888 } 7889 } 7890 } 7891 } 7892 7893 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7894 // This package wants to adopt ownership of permissions from 7895 // another package. 7896 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7897 final String origName = pkg.mAdoptPermissions.get(i); 7898 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7899 if (orig != null) { 7900 if (verifyPackageUpdateLPr(orig, pkg)) { 7901 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7902 + pkg.packageName); 7903 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7904 } 7905 } 7906 } 7907 } 7908 } 7909 7910 final String pkgName = pkg.packageName; 7911 7912 final long scanFileTime = scanFile.lastModified(); 7913 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7914 pkg.applicationInfo.processName = fixProcessName( 7915 pkg.applicationInfo.packageName, 7916 pkg.applicationInfo.processName, 7917 pkg.applicationInfo.uid); 7918 7919 if (pkg != mPlatformPackage) { 7920 // Get all of our default paths setup 7921 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7922 } 7923 7924 final String path = scanFile.getPath(); 7925 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7926 7927 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7928 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7929 7930 // Some system apps still use directory structure for native libraries 7931 // in which case we might end up not detecting abi solely based on apk 7932 // structure. Try to detect abi based on directory structure. 7933 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7934 pkg.applicationInfo.primaryCpuAbi == null) { 7935 setBundledAppAbisAndRoots(pkg, pkgSetting); 7936 setNativeLibraryPaths(pkg); 7937 } 7938 7939 } else { 7940 if ((scanFlags & SCAN_MOVE) != 0) { 7941 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7942 // but we already have this packages package info in the PackageSetting. We just 7943 // use that and derive the native library path based on the new codepath. 7944 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7945 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7946 } 7947 7948 // Set native library paths again. For moves, the path will be updated based on the 7949 // ABIs we've determined above. For non-moves, the path will be updated based on the 7950 // ABIs we determined during compilation, but the path will depend on the final 7951 // package path (after the rename away from the stage path). 7952 setNativeLibraryPaths(pkg); 7953 } 7954 7955 // This is a special case for the "system" package, where the ABI is 7956 // dictated by the zygote configuration (and init.rc). We should keep track 7957 // of this ABI so that we can deal with "normal" applications that run under 7958 // the same UID correctly. 7959 if (mPlatformPackage == pkg) { 7960 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7961 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7962 } 7963 7964 // If there's a mismatch between the abi-override in the package setting 7965 // and the abiOverride specified for the install. Warn about this because we 7966 // would've already compiled the app without taking the package setting into 7967 // account. 7968 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7969 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7970 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7971 " for package " + pkg.packageName); 7972 } 7973 } 7974 7975 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7976 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7977 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7978 7979 // Copy the derived override back to the parsed package, so that we can 7980 // update the package settings accordingly. 7981 pkg.cpuAbiOverride = cpuAbiOverride; 7982 7983 if (DEBUG_ABI_SELECTION) { 7984 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7985 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7986 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7987 } 7988 7989 // Push the derived path down into PackageSettings so we know what to 7990 // clean up at uninstall time. 7991 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7992 7993 if (DEBUG_ABI_SELECTION) { 7994 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7995 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7996 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7997 } 7998 7999 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8000 // We don't do this here during boot because we can do it all 8001 // at once after scanning all existing packages. 8002 // 8003 // We also do this *before* we perform dexopt on this package, so that 8004 // we can avoid redundant dexopts, and also to make sure we've got the 8005 // code and package path correct. 8006 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8007 pkg, true /* boot complete */); 8008 } 8009 8010 if (mFactoryTest && pkg.requestedPermissions.contains( 8011 android.Manifest.permission.FACTORY_TEST)) { 8012 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8013 } 8014 8015 ArrayList<PackageParser.Package> clientLibPkgs = null; 8016 8017 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8018 if (nonMutatedPs != null) { 8019 synchronized (mPackages) { 8020 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8021 } 8022 } 8023 return pkg; 8024 } 8025 8026 // Only privileged apps and updated privileged apps can add child packages. 8027 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8028 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8029 throw new PackageManagerException("Only privileged apps and updated " 8030 + "privileged apps can add child packages. Ignoring package " 8031 + pkg.packageName); 8032 } 8033 final int childCount = pkg.childPackages.size(); 8034 for (int i = 0; i < childCount; i++) { 8035 PackageParser.Package childPkg = pkg.childPackages.get(i); 8036 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8037 childPkg.packageName)) { 8038 throw new PackageManagerException("Cannot override a child package of " 8039 + "another disabled system app. Ignoring package " + pkg.packageName); 8040 } 8041 } 8042 } 8043 8044 // writer 8045 synchronized (mPackages) { 8046 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8047 // Only system apps can add new shared libraries. 8048 if (pkg.libraryNames != null) { 8049 for (int i=0; i<pkg.libraryNames.size(); i++) { 8050 String name = pkg.libraryNames.get(i); 8051 boolean allowed = false; 8052 if (pkg.isUpdatedSystemApp()) { 8053 // New library entries can only be added through the 8054 // system image. This is important to get rid of a lot 8055 // of nasty edge cases: for example if we allowed a non- 8056 // system update of the app to add a library, then uninstalling 8057 // the update would make the library go away, and assumptions 8058 // we made such as through app install filtering would now 8059 // have allowed apps on the device which aren't compatible 8060 // with it. Better to just have the restriction here, be 8061 // conservative, and create many fewer cases that can negatively 8062 // impact the user experience. 8063 final PackageSetting sysPs = mSettings 8064 .getDisabledSystemPkgLPr(pkg.packageName); 8065 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8066 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8067 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8068 allowed = true; 8069 break; 8070 } 8071 } 8072 } 8073 } else { 8074 allowed = true; 8075 } 8076 if (allowed) { 8077 if (!mSharedLibraries.containsKey(name)) { 8078 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8079 } else if (!name.equals(pkg.packageName)) { 8080 Slog.w(TAG, "Package " + pkg.packageName + " library " 8081 + name + " already exists; skipping"); 8082 } 8083 } else { 8084 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8085 + name + " that is not declared on system image; skipping"); 8086 } 8087 } 8088 if ((scanFlags & SCAN_BOOTING) == 0) { 8089 // If we are not booting, we need to update any applications 8090 // that are clients of our shared library. If we are booting, 8091 // this will all be done once the scan is complete. 8092 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8093 } 8094 } 8095 } 8096 } 8097 8098 // Request the ActivityManager to kill the process(only for existing packages) 8099 // so that we do not end up in a confused state while the user is still using the older 8100 // version of the application while the new one gets installed. 8101 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 8102 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 8103 if (killApp) { 8104 if (isReplacing) { 8105 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 8106 8107 killApplication(pkg.applicationInfo.packageName, 8108 pkg.applicationInfo.uid, "replace pkg"); 8109 8110 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8111 } 8112 } 8113 8114 // Also need to kill any apps that are dependent on the library. 8115 if (clientLibPkgs != null) { 8116 for (int i=0; i<clientLibPkgs.size(); i++) { 8117 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8118 killApplication(clientPkg.applicationInfo.packageName, 8119 clientPkg.applicationInfo.uid, "update lib"); 8120 } 8121 } 8122 8123 // Make sure we're not adding any bogus keyset info 8124 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8125 ksms.assertScannedPackageValid(pkg); 8126 8127 // writer 8128 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8129 8130 boolean createIdmapFailed = false; 8131 synchronized (mPackages) { 8132 // We don't expect installation to fail beyond this point 8133 8134 // Add the new setting to mSettings 8135 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8136 // Add the new setting to mPackages 8137 mPackages.put(pkg.applicationInfo.packageName, pkg); 8138 // Make sure we don't accidentally delete its data. 8139 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8140 while (iter.hasNext()) { 8141 PackageCleanItem item = iter.next(); 8142 if (pkgName.equals(item.packageName)) { 8143 iter.remove(); 8144 } 8145 } 8146 8147 // Take care of first install / last update times. 8148 if (currentTime != 0) { 8149 if (pkgSetting.firstInstallTime == 0) { 8150 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8151 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8152 pkgSetting.lastUpdateTime = currentTime; 8153 } 8154 } else if (pkgSetting.firstInstallTime == 0) { 8155 // We need *something*. Take time time stamp of the file. 8156 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8157 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8158 if (scanFileTime != pkgSetting.timeStamp) { 8159 // A package on the system image has changed; consider this 8160 // to be an update. 8161 pkgSetting.lastUpdateTime = scanFileTime; 8162 } 8163 } 8164 8165 // Add the package's KeySets to the global KeySetManagerService 8166 ksms.addScannedPackageLPw(pkg); 8167 8168 int N = pkg.providers.size(); 8169 StringBuilder r = null; 8170 int i; 8171 for (i=0; i<N; i++) { 8172 PackageParser.Provider p = pkg.providers.get(i); 8173 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8174 p.info.processName, pkg.applicationInfo.uid); 8175 mProviders.addProvider(p); 8176 p.syncable = p.info.isSyncable; 8177 if (p.info.authority != null) { 8178 String names[] = p.info.authority.split(";"); 8179 p.info.authority = null; 8180 for (int j = 0; j < names.length; j++) { 8181 if (j == 1 && p.syncable) { 8182 // We only want the first authority for a provider to possibly be 8183 // syncable, so if we already added this provider using a different 8184 // authority clear the syncable flag. We copy the provider before 8185 // changing it because the mProviders object contains a reference 8186 // to a provider that we don't want to change. 8187 // Only do this for the second authority since the resulting provider 8188 // object can be the same for all future authorities for this provider. 8189 p = new PackageParser.Provider(p); 8190 p.syncable = false; 8191 } 8192 if (!mProvidersByAuthority.containsKey(names[j])) { 8193 mProvidersByAuthority.put(names[j], p); 8194 if (p.info.authority == null) { 8195 p.info.authority = names[j]; 8196 } else { 8197 p.info.authority = p.info.authority + ";" + names[j]; 8198 } 8199 if (DEBUG_PACKAGE_SCANNING) { 8200 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8201 Log.d(TAG, "Registered content provider: " + names[j] 8202 + ", className = " + p.info.name + ", isSyncable = " 8203 + p.info.isSyncable); 8204 } 8205 } else { 8206 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8207 Slog.w(TAG, "Skipping provider name " + names[j] + 8208 " (in package " + pkg.applicationInfo.packageName + 8209 "): name already used by " 8210 + ((other != null && other.getComponentName() != null) 8211 ? other.getComponentName().getPackageName() : "?")); 8212 } 8213 } 8214 } 8215 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8216 if (r == null) { 8217 r = new StringBuilder(256); 8218 } else { 8219 r.append(' '); 8220 } 8221 r.append(p.info.name); 8222 } 8223 } 8224 if (r != null) { 8225 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8226 } 8227 8228 N = pkg.services.size(); 8229 r = null; 8230 for (i=0; i<N; i++) { 8231 PackageParser.Service s = pkg.services.get(i); 8232 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8233 s.info.processName, pkg.applicationInfo.uid); 8234 mServices.addService(s); 8235 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8236 if (r == null) { 8237 r = new StringBuilder(256); 8238 } else { 8239 r.append(' '); 8240 } 8241 r.append(s.info.name); 8242 } 8243 } 8244 if (r != null) { 8245 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8246 } 8247 8248 N = pkg.receivers.size(); 8249 r = null; 8250 for (i=0; i<N; i++) { 8251 PackageParser.Activity a = pkg.receivers.get(i); 8252 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8253 a.info.processName, pkg.applicationInfo.uid); 8254 mReceivers.addActivity(a, "receiver"); 8255 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8256 if (r == null) { 8257 r = new StringBuilder(256); 8258 } else { 8259 r.append(' '); 8260 } 8261 r.append(a.info.name); 8262 } 8263 } 8264 if (r != null) { 8265 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8266 } 8267 8268 N = pkg.activities.size(); 8269 r = null; 8270 for (i=0; i<N; i++) { 8271 PackageParser.Activity a = pkg.activities.get(i); 8272 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8273 a.info.processName, pkg.applicationInfo.uid); 8274 mActivities.addActivity(a, "activity"); 8275 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8276 if (r == null) { 8277 r = new StringBuilder(256); 8278 } else { 8279 r.append(' '); 8280 } 8281 r.append(a.info.name); 8282 } 8283 } 8284 if (r != null) { 8285 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8286 } 8287 8288 N = pkg.permissionGroups.size(); 8289 r = null; 8290 for (i=0; i<N; i++) { 8291 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8292 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8293 if (cur == null) { 8294 mPermissionGroups.put(pg.info.name, pg); 8295 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8296 if (r == null) { 8297 r = new StringBuilder(256); 8298 } else { 8299 r.append(' '); 8300 } 8301 r.append(pg.info.name); 8302 } 8303 } else { 8304 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8305 + pg.info.packageName + " ignored: original from " 8306 + cur.info.packageName); 8307 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8308 if (r == null) { 8309 r = new StringBuilder(256); 8310 } else { 8311 r.append(' '); 8312 } 8313 r.append("DUP:"); 8314 r.append(pg.info.name); 8315 } 8316 } 8317 } 8318 if (r != null) { 8319 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8320 } 8321 8322 N = pkg.permissions.size(); 8323 r = null; 8324 for (i=0; i<N; i++) { 8325 PackageParser.Permission p = pkg.permissions.get(i); 8326 8327 // Assume by default that we did not install this permission into the system. 8328 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8329 8330 // Now that permission groups have a special meaning, we ignore permission 8331 // groups for legacy apps to prevent unexpected behavior. In particular, 8332 // permissions for one app being granted to someone just becase they happen 8333 // to be in a group defined by another app (before this had no implications). 8334 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8335 p.group = mPermissionGroups.get(p.info.group); 8336 // Warn for a permission in an unknown group. 8337 if (p.info.group != null && p.group == null) { 8338 Slog.w(TAG, "Permission " + p.info.name + " from package " 8339 + p.info.packageName + " in an unknown group " + p.info.group); 8340 } 8341 } 8342 8343 ArrayMap<String, BasePermission> permissionMap = 8344 p.tree ? mSettings.mPermissionTrees 8345 : mSettings.mPermissions; 8346 BasePermission bp = permissionMap.get(p.info.name); 8347 8348 // Allow system apps to redefine non-system permissions 8349 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8350 final boolean currentOwnerIsSystem = (bp.perm != null 8351 && isSystemApp(bp.perm.owner)); 8352 if (isSystemApp(p.owner)) { 8353 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8354 // It's a built-in permission and no owner, take ownership now 8355 bp.packageSetting = pkgSetting; 8356 bp.perm = p; 8357 bp.uid = pkg.applicationInfo.uid; 8358 bp.sourcePackage = p.info.packageName; 8359 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8360 } else if (!currentOwnerIsSystem) { 8361 String msg = "New decl " + p.owner + " of permission " 8362 + p.info.name + " is system; overriding " + bp.sourcePackage; 8363 reportSettingsProblem(Log.WARN, msg); 8364 bp = null; 8365 } 8366 } 8367 } 8368 8369 if (bp == null) { 8370 bp = new BasePermission(p.info.name, p.info.packageName, 8371 BasePermission.TYPE_NORMAL); 8372 permissionMap.put(p.info.name, bp); 8373 } 8374 8375 if (bp.perm == null) { 8376 if (bp.sourcePackage == null 8377 || bp.sourcePackage.equals(p.info.packageName)) { 8378 BasePermission tree = findPermissionTreeLP(p.info.name); 8379 if (tree == null 8380 || tree.sourcePackage.equals(p.info.packageName)) { 8381 bp.packageSetting = pkgSetting; 8382 bp.perm = p; 8383 bp.uid = pkg.applicationInfo.uid; 8384 bp.sourcePackage = p.info.packageName; 8385 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8386 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8387 if (r == null) { 8388 r = new StringBuilder(256); 8389 } else { 8390 r.append(' '); 8391 } 8392 r.append(p.info.name); 8393 } 8394 } else { 8395 Slog.w(TAG, "Permission " + p.info.name + " from package " 8396 + p.info.packageName + " ignored: base tree " 8397 + tree.name + " is from package " 8398 + tree.sourcePackage); 8399 } 8400 } else { 8401 Slog.w(TAG, "Permission " + p.info.name + " from package " 8402 + p.info.packageName + " ignored: original from " 8403 + bp.sourcePackage); 8404 } 8405 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8406 if (r == null) { 8407 r = new StringBuilder(256); 8408 } else { 8409 r.append(' '); 8410 } 8411 r.append("DUP:"); 8412 r.append(p.info.name); 8413 } 8414 if (bp.perm == p) { 8415 bp.protectionLevel = p.info.protectionLevel; 8416 } 8417 } 8418 8419 if (r != null) { 8420 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8421 } 8422 8423 N = pkg.instrumentation.size(); 8424 r = null; 8425 for (i=0; i<N; i++) { 8426 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8427 a.info.packageName = pkg.applicationInfo.packageName; 8428 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8429 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8430 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8431 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8432 a.info.dataDir = pkg.applicationInfo.dataDir; 8433 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8434 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8435 8436 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8437 // need other information about the application, like the ABI and what not ? 8438 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8439 mInstrumentation.put(a.getComponentName(), a); 8440 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8441 if (r == null) { 8442 r = new StringBuilder(256); 8443 } else { 8444 r.append(' '); 8445 } 8446 r.append(a.info.name); 8447 } 8448 } 8449 if (r != null) { 8450 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8451 } 8452 8453 if (pkg.protectedBroadcasts != null) { 8454 N = pkg.protectedBroadcasts.size(); 8455 for (i=0; i<N; i++) { 8456 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8457 } 8458 } 8459 8460 pkgSetting.setTimeStamp(scanFileTime); 8461 8462 // Create idmap files for pairs of (packages, overlay packages). 8463 // Note: "android", ie framework-res.apk, is handled by native layers. 8464 if (pkg.mOverlayTarget != null) { 8465 // This is an overlay package. 8466 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8467 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8468 mOverlays.put(pkg.mOverlayTarget, 8469 new ArrayMap<String, PackageParser.Package>()); 8470 } 8471 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8472 map.put(pkg.packageName, pkg); 8473 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8474 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8475 createIdmapFailed = true; 8476 } 8477 } 8478 } else if (mOverlays.containsKey(pkg.packageName) && 8479 !pkg.packageName.equals("android")) { 8480 // This is a regular package, with one or more known overlay packages. 8481 createIdmapsForPackageLI(pkg); 8482 } 8483 } 8484 8485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8486 8487 if (createIdmapFailed) { 8488 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8489 "scanPackageLI failed to createIdmap"); 8490 } 8491 return pkg; 8492 } 8493 8494 /** 8495 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8496 * is derived purely on the basis of the contents of {@code scanFile} and 8497 * {@code cpuAbiOverride}. 8498 * 8499 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8500 */ 8501 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8502 String cpuAbiOverride, boolean extractLibs) 8503 throws PackageManagerException { 8504 // TODO: We can probably be smarter about this stuff. For installed apps, 8505 // we can calculate this information at install time once and for all. For 8506 // system apps, we can probably assume that this information doesn't change 8507 // after the first boot scan. As things stand, we do lots of unnecessary work. 8508 8509 // Give ourselves some initial paths; we'll come back for another 8510 // pass once we've determined ABI below. 8511 setNativeLibraryPaths(pkg); 8512 8513 // We would never need to extract libs for forward-locked and external packages, 8514 // since the container service will do it for us. We shouldn't attempt to 8515 // extract libs from system app when it was not updated. 8516 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8517 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8518 extractLibs = false; 8519 } 8520 8521 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8522 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8523 8524 NativeLibraryHelper.Handle handle = null; 8525 try { 8526 handle = NativeLibraryHelper.Handle.create(pkg); 8527 // TODO(multiArch): This can be null for apps that didn't go through the 8528 // usual installation process. We can calculate it again, like we 8529 // do during install time. 8530 // 8531 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8532 // unnecessary. 8533 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8534 8535 // Null out the abis so that they can be recalculated. 8536 pkg.applicationInfo.primaryCpuAbi = null; 8537 pkg.applicationInfo.secondaryCpuAbi = null; 8538 if (isMultiArch(pkg.applicationInfo)) { 8539 // Warn if we've set an abiOverride for multi-lib packages.. 8540 // By definition, we need to copy both 32 and 64 bit libraries for 8541 // such packages. 8542 if (pkg.cpuAbiOverride != null 8543 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8544 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8545 } 8546 8547 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8548 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8549 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8550 if (extractLibs) { 8551 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8552 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8553 useIsaSpecificSubdirs); 8554 } else { 8555 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8556 } 8557 } 8558 8559 maybeThrowExceptionForMultiArchCopy( 8560 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8561 8562 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8563 if (extractLibs) { 8564 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8565 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8566 useIsaSpecificSubdirs); 8567 } else { 8568 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8569 } 8570 } 8571 8572 maybeThrowExceptionForMultiArchCopy( 8573 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8574 8575 if (abi64 >= 0) { 8576 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8577 } 8578 8579 if (abi32 >= 0) { 8580 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8581 if (abi64 >= 0) { 8582 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8583 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8584 pkg.applicationInfo.primaryCpuAbi = abi; 8585 } else { 8586 pkg.applicationInfo.secondaryCpuAbi = abi; 8587 } 8588 } else { 8589 pkg.applicationInfo.primaryCpuAbi = abi; 8590 } 8591 } 8592 8593 } else { 8594 String[] abiList = (cpuAbiOverride != null) ? 8595 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8596 8597 // Enable gross and lame hacks for apps that are built with old 8598 // SDK tools. We must scan their APKs for renderscript bitcode and 8599 // not launch them if it's present. Don't bother checking on devices 8600 // that don't have 64 bit support. 8601 boolean needsRenderScriptOverride = false; 8602 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8603 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8604 abiList = Build.SUPPORTED_32_BIT_ABIS; 8605 needsRenderScriptOverride = true; 8606 } 8607 8608 final int copyRet; 8609 if (extractLibs) { 8610 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8611 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8612 } else { 8613 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8614 } 8615 8616 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8617 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8618 "Error unpackaging native libs for app, errorCode=" + copyRet); 8619 } 8620 8621 if (copyRet >= 0) { 8622 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8623 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8624 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8625 } else if (needsRenderScriptOverride) { 8626 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8627 } 8628 } 8629 } catch (IOException ioe) { 8630 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8631 } finally { 8632 IoUtils.closeQuietly(handle); 8633 } 8634 8635 // Now that we've calculated the ABIs and determined if it's an internal app, 8636 // we will go ahead and populate the nativeLibraryPath. 8637 setNativeLibraryPaths(pkg); 8638 } 8639 8640 /** 8641 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8642 * i.e, so that all packages can be run inside a single process if required. 8643 * 8644 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8645 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8646 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8647 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8648 * updating a package that belongs to a shared user. 8649 * 8650 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8651 * adds unnecessary complexity. 8652 */ 8653 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8654 PackageParser.Package scannedPackage, boolean bootComplete) { 8655 String requiredInstructionSet = null; 8656 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8657 requiredInstructionSet = VMRuntime.getInstructionSet( 8658 scannedPackage.applicationInfo.primaryCpuAbi); 8659 } 8660 8661 PackageSetting requirer = null; 8662 for (PackageSetting ps : packagesForUser) { 8663 // If packagesForUser contains scannedPackage, we skip it. This will happen 8664 // when scannedPackage is an update of an existing package. Without this check, 8665 // we will never be able to change the ABI of any package belonging to a shared 8666 // user, even if it's compatible with other packages. 8667 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8668 if (ps.primaryCpuAbiString == null) { 8669 continue; 8670 } 8671 8672 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8673 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8674 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8675 // this but there's not much we can do. 8676 String errorMessage = "Instruction set mismatch, " 8677 + ((requirer == null) ? "[caller]" : requirer) 8678 + " requires " + requiredInstructionSet + " whereas " + ps 8679 + " requires " + instructionSet; 8680 Slog.w(TAG, errorMessage); 8681 } 8682 8683 if (requiredInstructionSet == null) { 8684 requiredInstructionSet = instructionSet; 8685 requirer = ps; 8686 } 8687 } 8688 } 8689 8690 if (requiredInstructionSet != null) { 8691 String adjustedAbi; 8692 if (requirer != null) { 8693 // requirer != null implies that either scannedPackage was null or that scannedPackage 8694 // did not require an ABI, in which case we have to adjust scannedPackage to match 8695 // the ABI of the set (which is the same as requirer's ABI) 8696 adjustedAbi = requirer.primaryCpuAbiString; 8697 if (scannedPackage != null) { 8698 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8699 } 8700 } else { 8701 // requirer == null implies that we're updating all ABIs in the set to 8702 // match scannedPackage. 8703 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8704 } 8705 8706 for (PackageSetting ps : packagesForUser) { 8707 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8708 if (ps.primaryCpuAbiString != null) { 8709 continue; 8710 } 8711 8712 ps.primaryCpuAbiString = adjustedAbi; 8713 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8714 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8715 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8716 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8717 + " (requirer=" 8718 + (requirer == null ? "null" : requirer.pkg.packageName) 8719 + ", scannedPackage=" 8720 + (scannedPackage != null ? scannedPackage.packageName : "null") 8721 + ")"); 8722 try { 8723 mInstaller.rmdex(ps.codePathString, 8724 getDexCodeInstructionSet(getPreferredInstructionSet())); 8725 } catch (InstallerException ignored) { 8726 } 8727 } 8728 } 8729 } 8730 } 8731 } 8732 8733 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8734 synchronized (mPackages) { 8735 mResolverReplaced = true; 8736 // Set up information for custom user intent resolution activity. 8737 mResolveActivity.applicationInfo = pkg.applicationInfo; 8738 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8739 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8740 mResolveActivity.processName = pkg.applicationInfo.packageName; 8741 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8742 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8743 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8744 mResolveActivity.theme = 0; 8745 mResolveActivity.exported = true; 8746 mResolveActivity.enabled = true; 8747 mResolveInfo.activityInfo = mResolveActivity; 8748 mResolveInfo.priority = 0; 8749 mResolveInfo.preferredOrder = 0; 8750 mResolveInfo.match = 0; 8751 mResolveComponentName = mCustomResolverComponentName; 8752 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8753 mResolveComponentName); 8754 } 8755 } 8756 8757 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8758 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8759 8760 // Set up information for ephemeral installer activity 8761 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8762 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8763 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8764 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8765 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8766 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8767 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8768 mEphemeralInstallerActivity.theme = 0; 8769 mEphemeralInstallerActivity.exported = true; 8770 mEphemeralInstallerActivity.enabled = true; 8771 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8772 mEphemeralInstallerInfo.priority = 0; 8773 mEphemeralInstallerInfo.preferredOrder = 0; 8774 mEphemeralInstallerInfo.match = 0; 8775 8776 if (DEBUG_EPHEMERAL) { 8777 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8778 } 8779 } 8780 8781 private static String calculateBundledApkRoot(final String codePathString) { 8782 final File codePath = new File(codePathString); 8783 final File codeRoot; 8784 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8785 codeRoot = Environment.getRootDirectory(); 8786 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8787 codeRoot = Environment.getOemDirectory(); 8788 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8789 codeRoot = Environment.getVendorDirectory(); 8790 } else { 8791 // Unrecognized code path; take its top real segment as the apk root: 8792 // e.g. /something/app/blah.apk => /something 8793 try { 8794 File f = codePath.getCanonicalFile(); 8795 File parent = f.getParentFile(); // non-null because codePath is a file 8796 File tmp; 8797 while ((tmp = parent.getParentFile()) != null) { 8798 f = parent; 8799 parent = tmp; 8800 } 8801 codeRoot = f; 8802 Slog.w(TAG, "Unrecognized code path " 8803 + codePath + " - using " + codeRoot); 8804 } catch (IOException e) { 8805 // Can't canonicalize the code path -- shenanigans? 8806 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8807 return Environment.getRootDirectory().getPath(); 8808 } 8809 } 8810 return codeRoot.getPath(); 8811 } 8812 8813 /** 8814 * Derive and set the location of native libraries for the given package, 8815 * which varies depending on where and how the package was installed. 8816 */ 8817 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8818 final ApplicationInfo info = pkg.applicationInfo; 8819 final String codePath = pkg.codePath; 8820 final File codeFile = new File(codePath); 8821 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8822 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8823 8824 info.nativeLibraryRootDir = null; 8825 info.nativeLibraryRootRequiresIsa = false; 8826 info.nativeLibraryDir = null; 8827 info.secondaryNativeLibraryDir = null; 8828 8829 if (isApkFile(codeFile)) { 8830 // Monolithic install 8831 if (bundledApp) { 8832 // If "/system/lib64/apkname" exists, assume that is the per-package 8833 // native library directory to use; otherwise use "/system/lib/apkname". 8834 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8835 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8836 getPrimaryInstructionSet(info)); 8837 8838 // This is a bundled system app so choose the path based on the ABI. 8839 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8840 // is just the default path. 8841 final String apkName = deriveCodePathName(codePath); 8842 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8843 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8844 apkName).getAbsolutePath(); 8845 8846 if (info.secondaryCpuAbi != null) { 8847 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8848 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8849 secondaryLibDir, apkName).getAbsolutePath(); 8850 } 8851 } else if (asecApp) { 8852 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8853 .getAbsolutePath(); 8854 } else { 8855 final String apkName = deriveCodePathName(codePath); 8856 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8857 .getAbsolutePath(); 8858 } 8859 8860 info.nativeLibraryRootRequiresIsa = false; 8861 info.nativeLibraryDir = info.nativeLibraryRootDir; 8862 } else { 8863 // Cluster install 8864 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8865 info.nativeLibraryRootRequiresIsa = true; 8866 8867 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8868 getPrimaryInstructionSet(info)).getAbsolutePath(); 8869 8870 if (info.secondaryCpuAbi != null) { 8871 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8872 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8873 } 8874 } 8875 } 8876 8877 /** 8878 * Calculate the abis and roots for a bundled app. These can uniquely 8879 * be determined from the contents of the system partition, i.e whether 8880 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8881 * of this information, and instead assume that the system was built 8882 * sensibly. 8883 */ 8884 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8885 PackageSetting pkgSetting) { 8886 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8887 8888 // If "/system/lib64/apkname" exists, assume that is the per-package 8889 // native library directory to use; otherwise use "/system/lib/apkname". 8890 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8891 setBundledAppAbi(pkg, apkRoot, apkName); 8892 // pkgSetting might be null during rescan following uninstall of updates 8893 // to a bundled app, so accommodate that possibility. The settings in 8894 // that case will be established later from the parsed package. 8895 // 8896 // If the settings aren't null, sync them up with what we've just derived. 8897 // note that apkRoot isn't stored in the package settings. 8898 if (pkgSetting != null) { 8899 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8900 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8901 } 8902 } 8903 8904 /** 8905 * Deduces the ABI of a bundled app and sets the relevant fields on the 8906 * parsed pkg object. 8907 * 8908 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8909 * under which system libraries are installed. 8910 * @param apkName the name of the installed package. 8911 */ 8912 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8913 final File codeFile = new File(pkg.codePath); 8914 8915 final boolean has64BitLibs; 8916 final boolean has32BitLibs; 8917 if (isApkFile(codeFile)) { 8918 // Monolithic install 8919 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8920 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8921 } else { 8922 // Cluster install 8923 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8924 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8925 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8926 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8927 has64BitLibs = (new File(rootDir, isa)).exists(); 8928 } else { 8929 has64BitLibs = false; 8930 } 8931 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8932 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8933 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8934 has32BitLibs = (new File(rootDir, isa)).exists(); 8935 } else { 8936 has32BitLibs = false; 8937 } 8938 } 8939 8940 if (has64BitLibs && !has32BitLibs) { 8941 // The package has 64 bit libs, but not 32 bit libs. Its primary 8942 // ABI should be 64 bit. We can safely assume here that the bundled 8943 // native libraries correspond to the most preferred ABI in the list. 8944 8945 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8946 pkg.applicationInfo.secondaryCpuAbi = null; 8947 } else if (has32BitLibs && !has64BitLibs) { 8948 // The package has 32 bit libs but not 64 bit libs. Its primary 8949 // ABI should be 32 bit. 8950 8951 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8952 pkg.applicationInfo.secondaryCpuAbi = null; 8953 } else if (has32BitLibs && has64BitLibs) { 8954 // The application has both 64 and 32 bit bundled libraries. We check 8955 // here that the app declares multiArch support, and warn if it doesn't. 8956 // 8957 // We will be lenient here and record both ABIs. The primary will be the 8958 // ABI that's higher on the list, i.e, a device that's configured to prefer 8959 // 64 bit apps will see a 64 bit primary ABI, 8960 8961 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8962 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8963 } 8964 8965 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8966 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8967 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8968 } else { 8969 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8970 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8971 } 8972 } else { 8973 pkg.applicationInfo.primaryCpuAbi = null; 8974 pkg.applicationInfo.secondaryCpuAbi = null; 8975 } 8976 } 8977 8978 private void killPackage(PackageParser.Package pkg, String reason) { 8979 // Kill the parent package 8980 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8981 // Kill the child packages 8982 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8983 for (int i = 0; i < childCount; i++) { 8984 PackageParser.Package childPkg = pkg.childPackages.get(i); 8985 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8986 } 8987 } 8988 8989 private void killApplication(String pkgName, int appId, String reason) { 8990 // Request the ActivityManager to kill the process(only for existing packages) 8991 // so that we do not end up in a confused state while the user is still using the older 8992 // version of the application while the new one gets installed. 8993 IActivityManager am = ActivityManagerNative.getDefault(); 8994 if (am != null) { 8995 try { 8996 am.killApplicationWithAppId(pkgName, appId, reason); 8997 } catch (RemoteException e) { 8998 } 8999 } 9000 } 9001 9002 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9003 // Remove the parent package setting 9004 PackageSetting ps = (PackageSetting) pkg.mExtras; 9005 if (ps != null) { 9006 removePackageLI(ps, chatty); 9007 } 9008 // Remove the child package setting 9009 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9010 for (int i = 0; i < childCount; i++) { 9011 PackageParser.Package childPkg = pkg.childPackages.get(i); 9012 ps = (PackageSetting) childPkg.mExtras; 9013 if (ps != null) { 9014 removePackageLI(ps, chatty); 9015 } 9016 } 9017 } 9018 9019 void removePackageLI(PackageSetting ps, boolean chatty) { 9020 if (DEBUG_INSTALL) { 9021 if (chatty) 9022 Log.d(TAG, "Removing package " + ps.name); 9023 } 9024 9025 // writer 9026 synchronized (mPackages) { 9027 mPackages.remove(ps.name); 9028 final PackageParser.Package pkg = ps.pkg; 9029 if (pkg != null) { 9030 cleanPackageDataStructuresLILPw(pkg, chatty); 9031 } 9032 } 9033 } 9034 9035 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9036 if (DEBUG_INSTALL) { 9037 if (chatty) 9038 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9039 } 9040 9041 // writer 9042 synchronized (mPackages) { 9043 // Remove the parent package 9044 mPackages.remove(pkg.applicationInfo.packageName); 9045 cleanPackageDataStructuresLILPw(pkg, chatty); 9046 9047 // Remove the child packages 9048 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9049 for (int i = 0; i < childCount; i++) { 9050 PackageParser.Package childPkg = pkg.childPackages.get(i); 9051 mPackages.remove(childPkg.applicationInfo.packageName); 9052 cleanPackageDataStructuresLILPw(childPkg, chatty); 9053 } 9054 } 9055 } 9056 9057 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9058 int N = pkg.providers.size(); 9059 StringBuilder r = null; 9060 int i; 9061 for (i=0; i<N; i++) { 9062 PackageParser.Provider p = pkg.providers.get(i); 9063 mProviders.removeProvider(p); 9064 if (p.info.authority == null) { 9065 9066 /* There was another ContentProvider with this authority when 9067 * this app was installed so this authority is null, 9068 * Ignore it as we don't have to unregister the provider. 9069 */ 9070 continue; 9071 } 9072 String names[] = p.info.authority.split(";"); 9073 for (int j = 0; j < names.length; j++) { 9074 if (mProvidersByAuthority.get(names[j]) == p) { 9075 mProvidersByAuthority.remove(names[j]); 9076 if (DEBUG_REMOVE) { 9077 if (chatty) 9078 Log.d(TAG, "Unregistered content provider: " + names[j] 9079 + ", className = " + p.info.name + ", isSyncable = " 9080 + p.info.isSyncable); 9081 } 9082 } 9083 } 9084 if (DEBUG_REMOVE && chatty) { 9085 if (r == null) { 9086 r = new StringBuilder(256); 9087 } else { 9088 r.append(' '); 9089 } 9090 r.append(p.info.name); 9091 } 9092 } 9093 if (r != null) { 9094 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9095 } 9096 9097 N = pkg.services.size(); 9098 r = null; 9099 for (i=0; i<N; i++) { 9100 PackageParser.Service s = pkg.services.get(i); 9101 mServices.removeService(s); 9102 if (chatty) { 9103 if (r == null) { 9104 r = new StringBuilder(256); 9105 } else { 9106 r.append(' '); 9107 } 9108 r.append(s.info.name); 9109 } 9110 } 9111 if (r != null) { 9112 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9113 } 9114 9115 N = pkg.receivers.size(); 9116 r = null; 9117 for (i=0; i<N; i++) { 9118 PackageParser.Activity a = pkg.receivers.get(i); 9119 mReceivers.removeActivity(a, "receiver"); 9120 if (DEBUG_REMOVE && chatty) { 9121 if (r == null) { 9122 r = new StringBuilder(256); 9123 } else { 9124 r.append(' '); 9125 } 9126 r.append(a.info.name); 9127 } 9128 } 9129 if (r != null) { 9130 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9131 } 9132 9133 N = pkg.activities.size(); 9134 r = null; 9135 for (i=0; i<N; i++) { 9136 PackageParser.Activity a = pkg.activities.get(i); 9137 mActivities.removeActivity(a, "activity"); 9138 if (DEBUG_REMOVE && chatty) { 9139 if (r == null) { 9140 r = new StringBuilder(256); 9141 } else { 9142 r.append(' '); 9143 } 9144 r.append(a.info.name); 9145 } 9146 } 9147 if (r != null) { 9148 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9149 } 9150 9151 N = pkg.permissions.size(); 9152 r = null; 9153 for (i=0; i<N; i++) { 9154 PackageParser.Permission p = pkg.permissions.get(i); 9155 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9156 if (bp == null) { 9157 bp = mSettings.mPermissionTrees.get(p.info.name); 9158 } 9159 if (bp != null && bp.perm == p) { 9160 bp.perm = null; 9161 if (DEBUG_REMOVE && chatty) { 9162 if (r == null) { 9163 r = new StringBuilder(256); 9164 } else { 9165 r.append(' '); 9166 } 9167 r.append(p.info.name); 9168 } 9169 } 9170 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9171 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9172 if (appOpPkgs != null) { 9173 appOpPkgs.remove(pkg.packageName); 9174 } 9175 } 9176 } 9177 if (r != null) { 9178 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9179 } 9180 9181 N = pkg.requestedPermissions.size(); 9182 r = null; 9183 for (i=0; i<N; i++) { 9184 String perm = pkg.requestedPermissions.get(i); 9185 BasePermission bp = mSettings.mPermissions.get(perm); 9186 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9187 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9188 if (appOpPkgs != null) { 9189 appOpPkgs.remove(pkg.packageName); 9190 if (appOpPkgs.isEmpty()) { 9191 mAppOpPermissionPackages.remove(perm); 9192 } 9193 } 9194 } 9195 } 9196 if (r != null) { 9197 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9198 } 9199 9200 N = pkg.instrumentation.size(); 9201 r = null; 9202 for (i=0; i<N; i++) { 9203 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9204 mInstrumentation.remove(a.getComponentName()); 9205 if (DEBUG_REMOVE && chatty) { 9206 if (r == null) { 9207 r = new StringBuilder(256); 9208 } else { 9209 r.append(' '); 9210 } 9211 r.append(a.info.name); 9212 } 9213 } 9214 if (r != null) { 9215 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9216 } 9217 9218 r = null; 9219 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9220 // Only system apps can hold shared libraries. 9221 if (pkg.libraryNames != null) { 9222 for (i=0; i<pkg.libraryNames.size(); i++) { 9223 String name = pkg.libraryNames.get(i); 9224 SharedLibraryEntry cur = mSharedLibraries.get(name); 9225 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9226 mSharedLibraries.remove(name); 9227 if (DEBUG_REMOVE && chatty) { 9228 if (r == null) { 9229 r = new StringBuilder(256); 9230 } else { 9231 r.append(' '); 9232 } 9233 r.append(name); 9234 } 9235 } 9236 } 9237 } 9238 } 9239 if (r != null) { 9240 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9241 } 9242 } 9243 9244 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9245 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9246 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9247 return true; 9248 } 9249 } 9250 return false; 9251 } 9252 9253 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9254 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9255 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9256 9257 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9258 // Update the parent permissions 9259 updatePermissionsLPw(pkg.packageName, pkg, flags); 9260 // Update the child permissions 9261 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9262 for (int i = 0; i < childCount; i++) { 9263 PackageParser.Package childPkg = pkg.childPackages.get(i); 9264 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9265 } 9266 } 9267 9268 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9269 int flags) { 9270 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9271 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9272 } 9273 9274 private void updatePermissionsLPw(String changingPkg, 9275 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9276 // Make sure there are no dangling permission trees. 9277 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9278 while (it.hasNext()) { 9279 final BasePermission bp = it.next(); 9280 if (bp.packageSetting == null) { 9281 // We may not yet have parsed the package, so just see if 9282 // we still know about its settings. 9283 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9284 } 9285 if (bp.packageSetting == null) { 9286 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9287 + " from package " + bp.sourcePackage); 9288 it.remove(); 9289 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9290 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9291 Slog.i(TAG, "Removing old permission tree: " + bp.name 9292 + " from package " + bp.sourcePackage); 9293 flags |= UPDATE_PERMISSIONS_ALL; 9294 it.remove(); 9295 } 9296 } 9297 } 9298 9299 // Make sure all dynamic permissions have been assigned to a package, 9300 // and make sure there are no dangling permissions. 9301 it = mSettings.mPermissions.values().iterator(); 9302 while (it.hasNext()) { 9303 final BasePermission bp = it.next(); 9304 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9305 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9306 + bp.name + " pkg=" + bp.sourcePackage 9307 + " info=" + bp.pendingInfo); 9308 if (bp.packageSetting == null && bp.pendingInfo != null) { 9309 final BasePermission tree = findPermissionTreeLP(bp.name); 9310 if (tree != null && tree.perm != null) { 9311 bp.packageSetting = tree.packageSetting; 9312 bp.perm = new PackageParser.Permission(tree.perm.owner, 9313 new PermissionInfo(bp.pendingInfo)); 9314 bp.perm.info.packageName = tree.perm.info.packageName; 9315 bp.perm.info.name = bp.name; 9316 bp.uid = tree.uid; 9317 } 9318 } 9319 } 9320 if (bp.packageSetting == null) { 9321 // We may not yet have parsed the package, so just see if 9322 // we still know about its settings. 9323 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9324 } 9325 if (bp.packageSetting == null) { 9326 Slog.w(TAG, "Removing dangling permission: " + bp.name 9327 + " from package " + bp.sourcePackage); 9328 it.remove(); 9329 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9330 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9331 Slog.i(TAG, "Removing old permission: " + bp.name 9332 + " from package " + bp.sourcePackage); 9333 flags |= UPDATE_PERMISSIONS_ALL; 9334 it.remove(); 9335 } 9336 } 9337 } 9338 9339 // Now update the permissions for all packages, in particular 9340 // replace the granted permissions of the system packages. 9341 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9342 for (PackageParser.Package pkg : mPackages.values()) { 9343 if (pkg != pkgInfo) { 9344 // Only replace for packages on requested volume 9345 final String volumeUuid = getVolumeUuidForPackage(pkg); 9346 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9347 && Objects.equals(replaceVolumeUuid, volumeUuid); 9348 grantPermissionsLPw(pkg, replace, changingPkg); 9349 } 9350 } 9351 } 9352 9353 if (pkgInfo != null) { 9354 // Only replace for packages on requested volume 9355 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9356 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9357 && Objects.equals(replaceVolumeUuid, volumeUuid); 9358 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9359 } 9360 } 9361 9362 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9363 String packageOfInterest) { 9364 // IMPORTANT: There are two types of permissions: install and runtime. 9365 // Install time permissions are granted when the app is installed to 9366 // all device users and users added in the future. Runtime permissions 9367 // are granted at runtime explicitly to specific users. Normal and signature 9368 // protected permissions are install time permissions. Dangerous permissions 9369 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9370 // otherwise they are runtime permissions. This function does not manage 9371 // runtime permissions except for the case an app targeting Lollipop MR1 9372 // being upgraded to target a newer SDK, in which case dangerous permissions 9373 // are transformed from install time to runtime ones. 9374 9375 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9376 if (ps == null) { 9377 return; 9378 } 9379 9380 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9381 9382 PermissionsState permissionsState = ps.getPermissionsState(); 9383 PermissionsState origPermissions = permissionsState; 9384 9385 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9386 9387 boolean runtimePermissionsRevoked = false; 9388 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9389 9390 boolean changedInstallPermission = false; 9391 9392 if (replace) { 9393 ps.installPermissionsFixed = false; 9394 if (!ps.isSharedUser()) { 9395 origPermissions = new PermissionsState(permissionsState); 9396 permissionsState.reset(); 9397 } else { 9398 // We need to know only about runtime permission changes since the 9399 // calling code always writes the install permissions state but 9400 // the runtime ones are written only if changed. The only cases of 9401 // changed runtime permissions here are promotion of an install to 9402 // runtime and revocation of a runtime from a shared user. 9403 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9404 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9405 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9406 runtimePermissionsRevoked = true; 9407 } 9408 } 9409 } 9410 9411 permissionsState.setGlobalGids(mGlobalGids); 9412 9413 final int N = pkg.requestedPermissions.size(); 9414 for (int i=0; i<N; i++) { 9415 final String name = pkg.requestedPermissions.get(i); 9416 final BasePermission bp = mSettings.mPermissions.get(name); 9417 9418 if (DEBUG_INSTALL) { 9419 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9420 } 9421 9422 if (bp == null || bp.packageSetting == null) { 9423 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9424 Slog.w(TAG, "Unknown permission " + name 9425 + " in package " + pkg.packageName); 9426 } 9427 continue; 9428 } 9429 9430 final String perm = bp.name; 9431 boolean allowedSig = false; 9432 int grant = GRANT_DENIED; 9433 9434 // Keep track of app op permissions. 9435 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9436 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9437 if (pkgs == null) { 9438 pkgs = new ArraySet<>(); 9439 mAppOpPermissionPackages.put(bp.name, pkgs); 9440 } 9441 pkgs.add(pkg.packageName); 9442 } 9443 9444 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9445 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9446 >= Build.VERSION_CODES.M; 9447 switch (level) { 9448 case PermissionInfo.PROTECTION_NORMAL: { 9449 // For all apps normal permissions are install time ones. 9450 grant = GRANT_INSTALL; 9451 } break; 9452 9453 case PermissionInfo.PROTECTION_DANGEROUS: { 9454 // If a permission review is required for legacy apps we represent 9455 // their permissions as always granted runtime ones since we need 9456 // to keep the review required permission flag per user while an 9457 // install permission's state is shared across all users. 9458 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9459 // For legacy apps dangerous permissions are install time ones. 9460 grant = GRANT_INSTALL; 9461 } else if (origPermissions.hasInstallPermission(bp.name)) { 9462 // For legacy apps that became modern, install becomes runtime. 9463 grant = GRANT_UPGRADE; 9464 } else if (mPromoteSystemApps 9465 && isSystemApp(ps) 9466 && mExistingSystemPackages.contains(ps.name)) { 9467 // For legacy system apps, install becomes runtime. 9468 // We cannot check hasInstallPermission() for system apps since those 9469 // permissions were granted implicitly and not persisted pre-M. 9470 grant = GRANT_UPGRADE; 9471 } else { 9472 // For modern apps keep runtime permissions unchanged. 9473 grant = GRANT_RUNTIME; 9474 } 9475 } break; 9476 9477 case PermissionInfo.PROTECTION_SIGNATURE: { 9478 // For all apps signature permissions are install time ones. 9479 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9480 if (allowedSig) { 9481 grant = GRANT_INSTALL; 9482 } 9483 } break; 9484 } 9485 9486 if (DEBUG_INSTALL) { 9487 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9488 } 9489 9490 if (grant != GRANT_DENIED) { 9491 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9492 // If this is an existing, non-system package, then 9493 // we can't add any new permissions to it. 9494 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9495 // Except... if this is a permission that was added 9496 // to the platform (note: need to only do this when 9497 // updating the platform). 9498 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9499 grant = GRANT_DENIED; 9500 } 9501 } 9502 } 9503 9504 switch (grant) { 9505 case GRANT_INSTALL: { 9506 // Revoke this as runtime permission to handle the case of 9507 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9508 for (int userId : UserManagerService.getInstance().getUserIds()) { 9509 if (origPermissions.getRuntimePermissionState( 9510 bp.name, userId) != null) { 9511 // Revoke the runtime permission and clear the flags. 9512 origPermissions.revokeRuntimePermission(bp, userId); 9513 origPermissions.updatePermissionFlags(bp, userId, 9514 PackageManager.MASK_PERMISSION_FLAGS, 0); 9515 // If we revoked a permission permission, we have to write. 9516 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9517 changedRuntimePermissionUserIds, userId); 9518 } 9519 } 9520 // Grant an install permission. 9521 if (permissionsState.grantInstallPermission(bp) != 9522 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9523 changedInstallPermission = true; 9524 } 9525 } break; 9526 9527 case GRANT_RUNTIME: { 9528 // Grant previously granted runtime permissions. 9529 for (int userId : UserManagerService.getInstance().getUserIds()) { 9530 PermissionState permissionState = origPermissions 9531 .getRuntimePermissionState(bp.name, userId); 9532 int flags = permissionState != null 9533 ? permissionState.getFlags() : 0; 9534 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9535 if (permissionsState.grantRuntimePermission(bp, userId) == 9536 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9537 // If we cannot put the permission as it was, we have to write. 9538 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9539 changedRuntimePermissionUserIds, userId); 9540 } 9541 // If the app supports runtime permissions no need for a review. 9542 if (Build.PERMISSIONS_REVIEW_REQUIRED 9543 && appSupportsRuntimePermissions 9544 && (flags & PackageManager 9545 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9546 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9547 // Since we changed the flags, we have to write. 9548 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9549 changedRuntimePermissionUserIds, userId); 9550 } 9551 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9552 && !appSupportsRuntimePermissions) { 9553 // For legacy apps that need a permission review, every new 9554 // runtime permission is granted but it is pending a review. 9555 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9556 permissionsState.grantRuntimePermission(bp, userId); 9557 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9558 // We changed the permission and flags, hence have to write. 9559 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9560 changedRuntimePermissionUserIds, userId); 9561 } 9562 } 9563 // Propagate the permission flags. 9564 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9565 } 9566 } break; 9567 9568 case GRANT_UPGRADE: { 9569 // Grant runtime permissions for a previously held install permission. 9570 PermissionState permissionState = origPermissions 9571 .getInstallPermissionState(bp.name); 9572 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9573 9574 if (origPermissions.revokeInstallPermission(bp) 9575 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9576 // We will be transferring the permission flags, so clear them. 9577 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9578 PackageManager.MASK_PERMISSION_FLAGS, 0); 9579 changedInstallPermission = true; 9580 } 9581 9582 // If the permission is not to be promoted to runtime we ignore it and 9583 // also its other flags as they are not applicable to install permissions. 9584 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9585 for (int userId : currentUserIds) { 9586 if (permissionsState.grantRuntimePermission(bp, userId) != 9587 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9588 // Transfer the permission flags. 9589 permissionsState.updatePermissionFlags(bp, userId, 9590 flags, flags); 9591 // If we granted the permission, we have to write. 9592 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9593 changedRuntimePermissionUserIds, userId); 9594 } 9595 } 9596 } 9597 } break; 9598 9599 default: { 9600 if (packageOfInterest == null 9601 || packageOfInterest.equals(pkg.packageName)) { 9602 Slog.w(TAG, "Not granting permission " + perm 9603 + " to package " + pkg.packageName 9604 + " because it was previously installed without"); 9605 } 9606 } break; 9607 } 9608 } else { 9609 if (permissionsState.revokeInstallPermission(bp) != 9610 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9611 // Also drop the permission flags. 9612 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9613 PackageManager.MASK_PERMISSION_FLAGS, 0); 9614 changedInstallPermission = true; 9615 Slog.i(TAG, "Un-granting permission " + perm 9616 + " from package " + pkg.packageName 9617 + " (protectionLevel=" + bp.protectionLevel 9618 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9619 + ")"); 9620 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9621 // Don't print warning for app op permissions, since it is fine for them 9622 // not to be granted, there is a UI for the user to decide. 9623 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9624 Slog.w(TAG, "Not granting permission " + perm 9625 + " to package " + pkg.packageName 9626 + " (protectionLevel=" + bp.protectionLevel 9627 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9628 + ")"); 9629 } 9630 } 9631 } 9632 } 9633 9634 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9635 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9636 // This is the first that we have heard about this package, so the 9637 // permissions we have now selected are fixed until explicitly 9638 // changed. 9639 ps.installPermissionsFixed = true; 9640 } 9641 9642 // Persist the runtime permissions state for users with changes. If permissions 9643 // were revoked because no app in the shared user declares them we have to 9644 // write synchronously to avoid losing runtime permissions state. 9645 for (int userId : changedRuntimePermissionUserIds) { 9646 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9647 } 9648 9649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9650 } 9651 9652 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9653 boolean allowed = false; 9654 final int NP = PackageParser.NEW_PERMISSIONS.length; 9655 for (int ip=0; ip<NP; ip++) { 9656 final PackageParser.NewPermissionInfo npi 9657 = PackageParser.NEW_PERMISSIONS[ip]; 9658 if (npi.name.equals(perm) 9659 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9660 allowed = true; 9661 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9662 + pkg.packageName); 9663 break; 9664 } 9665 } 9666 return allowed; 9667 } 9668 9669 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9670 BasePermission bp, PermissionsState origPermissions) { 9671 boolean allowed; 9672 allowed = (compareSignatures( 9673 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9674 == PackageManager.SIGNATURE_MATCH) 9675 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9676 == PackageManager.SIGNATURE_MATCH); 9677 if (!allowed && (bp.protectionLevel 9678 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9679 if (isSystemApp(pkg)) { 9680 // For updated system applications, a system permission 9681 // is granted only if it had been defined by the original application. 9682 if (pkg.isUpdatedSystemApp()) { 9683 final PackageSetting sysPs = mSettings 9684 .getDisabledSystemPkgLPr(pkg.packageName); 9685 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9686 // If the original was granted this permission, we take 9687 // that grant decision as read and propagate it to the 9688 // update. 9689 if (sysPs.isPrivileged()) { 9690 allowed = true; 9691 } 9692 } else { 9693 // The system apk may have been updated with an older 9694 // version of the one on the data partition, but which 9695 // granted a new system permission that it didn't have 9696 // before. In this case we do want to allow the app to 9697 // now get the new permission if the ancestral apk is 9698 // privileged to get it. 9699 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9700 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9701 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9702 allowed = true; 9703 break; 9704 } 9705 } 9706 } 9707 // Also if a privileged parent package on the system image or any of 9708 // its children requested a privileged permission, the updated child 9709 // packages can also get the permission. 9710 if (pkg.parentPackage != null) { 9711 final PackageSetting disabledSysParentPs = mSettings 9712 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9713 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9714 && disabledSysParentPs.isPrivileged()) { 9715 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9716 allowed = true; 9717 } else if (disabledSysParentPs.pkg.childPackages != null) { 9718 final int count = disabledSysParentPs.pkg.childPackages.size(); 9719 for (int i = 0; i < count; i++) { 9720 PackageParser.Package disabledSysChildPkg = 9721 disabledSysParentPs.pkg.childPackages.get(i); 9722 if (isPackageRequestingPermission(disabledSysChildPkg, 9723 perm)) { 9724 allowed = true; 9725 break; 9726 } 9727 } 9728 } 9729 } 9730 } 9731 } 9732 } else { 9733 allowed = isPrivilegedApp(pkg); 9734 } 9735 } 9736 } 9737 if (!allowed) { 9738 if (!allowed && (bp.protectionLevel 9739 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9740 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9741 // If this was a previously normal/dangerous permission that got moved 9742 // to a system permission as part of the runtime permission redesign, then 9743 // we still want to blindly grant it to old apps. 9744 allowed = true; 9745 } 9746 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9747 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9748 // If this permission is to be granted to the system installer and 9749 // this app is an installer, then it gets the permission. 9750 allowed = true; 9751 } 9752 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9753 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9754 // If this permission is to be granted to the system verifier and 9755 // this app is a verifier, then it gets the permission. 9756 allowed = true; 9757 } 9758 if (!allowed && (bp.protectionLevel 9759 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9760 && isSystemApp(pkg)) { 9761 // Any pre-installed system app is allowed to get this permission. 9762 allowed = true; 9763 } 9764 if (!allowed && (bp.protectionLevel 9765 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9766 // For development permissions, a development permission 9767 // is granted only if it was already granted. 9768 allowed = origPermissions.hasInstallPermission(perm); 9769 } 9770 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9771 && pkg.packageName.equals(mSetupWizardPackage)) { 9772 // If this permission is to be granted to the system setup wizard and 9773 // this app is a setup wizard, then it gets the permission. 9774 allowed = true; 9775 } 9776 } 9777 return allowed; 9778 } 9779 9780 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9781 final int permCount = pkg.requestedPermissions.size(); 9782 for (int j = 0; j < permCount; j++) { 9783 String requestedPermission = pkg.requestedPermissions.get(j); 9784 if (permission.equals(requestedPermission)) { 9785 return true; 9786 } 9787 } 9788 return false; 9789 } 9790 9791 final class ActivityIntentResolver 9792 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9793 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9794 boolean defaultOnly, int userId) { 9795 if (!sUserManager.exists(userId)) return null; 9796 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9797 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9798 } 9799 9800 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9801 int userId) { 9802 if (!sUserManager.exists(userId)) return null; 9803 mFlags = flags; 9804 return super.queryIntent(intent, resolvedType, 9805 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9806 } 9807 9808 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9809 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9810 if (!sUserManager.exists(userId)) return null; 9811 if (packageActivities == null) { 9812 return null; 9813 } 9814 mFlags = flags; 9815 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9816 final int N = packageActivities.size(); 9817 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9818 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9819 9820 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9821 for (int i = 0; i < N; ++i) { 9822 intentFilters = packageActivities.get(i).intents; 9823 if (intentFilters != null && intentFilters.size() > 0) { 9824 PackageParser.ActivityIntentInfo[] array = 9825 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9826 intentFilters.toArray(array); 9827 listCut.add(array); 9828 } 9829 } 9830 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9831 } 9832 9833 /** 9834 * Finds a privileged activity that matches the specified activity names. 9835 */ 9836 private PackageParser.Activity findMatchingActivity( 9837 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9838 for (PackageParser.Activity sysActivity : activityList) { 9839 if (sysActivity.info.name.equals(activityInfo.name)) { 9840 return sysActivity; 9841 } 9842 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9843 return sysActivity; 9844 } 9845 if (sysActivity.info.targetActivity != null) { 9846 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9847 return sysActivity; 9848 } 9849 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9850 return sysActivity; 9851 } 9852 } 9853 } 9854 return null; 9855 } 9856 9857 public class IterGenerator<E> { 9858 public Iterator<E> generate(ActivityIntentInfo info) { 9859 return null; 9860 } 9861 } 9862 9863 public class ActionIterGenerator extends IterGenerator<String> { 9864 @Override 9865 public Iterator<String> generate(ActivityIntentInfo info) { 9866 return info.actionsIterator(); 9867 } 9868 } 9869 9870 public class CategoriesIterGenerator extends IterGenerator<String> { 9871 @Override 9872 public Iterator<String> generate(ActivityIntentInfo info) { 9873 return info.categoriesIterator(); 9874 } 9875 } 9876 9877 public class SchemesIterGenerator extends IterGenerator<String> { 9878 @Override 9879 public Iterator<String> generate(ActivityIntentInfo info) { 9880 return info.schemesIterator(); 9881 } 9882 } 9883 9884 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9885 @Override 9886 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9887 return info.authoritiesIterator(); 9888 } 9889 } 9890 9891 /** 9892 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9893 * MODIFIED. Do not pass in a list that should not be changed. 9894 */ 9895 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9896 IterGenerator<T> generator, Iterator<T> searchIterator) { 9897 // loop through the set of actions; every one must be found in the intent filter 9898 while (searchIterator.hasNext()) { 9899 // we must have at least one filter in the list to consider a match 9900 if (intentList.size() == 0) { 9901 break; 9902 } 9903 9904 final T searchAction = searchIterator.next(); 9905 9906 // loop through the set of intent filters 9907 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9908 while (intentIter.hasNext()) { 9909 final ActivityIntentInfo intentInfo = intentIter.next(); 9910 boolean selectionFound = false; 9911 9912 // loop through the intent filter's selection criteria; at least one 9913 // of them must match the searched criteria 9914 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9915 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9916 final T intentSelection = intentSelectionIter.next(); 9917 if (intentSelection != null && intentSelection.equals(searchAction)) { 9918 selectionFound = true; 9919 break; 9920 } 9921 } 9922 9923 // the selection criteria wasn't found in this filter's set; this filter 9924 // is not a potential match 9925 if (!selectionFound) { 9926 intentIter.remove(); 9927 } 9928 } 9929 } 9930 } 9931 9932 private boolean isProtectedAction(ActivityIntentInfo filter) { 9933 final Iterator<String> actionsIter = filter.actionsIterator(); 9934 while (actionsIter != null && actionsIter.hasNext()) { 9935 final String filterAction = actionsIter.next(); 9936 if (PROTECTED_ACTIONS.contains(filterAction)) { 9937 return true; 9938 } 9939 } 9940 return false; 9941 } 9942 9943 /** 9944 * Adjusts the priority of the given intent filter according to policy. 9945 * <p> 9946 * <ul> 9947 * <li>The priority for non privileged applications is capped to '0'</li> 9948 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 9949 * <li>The priority for unbundled updates to privileged applications is capped to the 9950 * priority defined on the system partition</li> 9951 * </ul> 9952 * <p> 9953 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 9954 * allowed to obtain any priority on any action. 9955 */ 9956 private void adjustPriority( 9957 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 9958 // nothing to do; priority is fine as-is 9959 if (intent.getPriority() <= 0) { 9960 return; 9961 } 9962 9963 final ActivityInfo activityInfo = intent.activity.info; 9964 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 9965 9966 final boolean privilegedApp = 9967 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 9968 if (!privilegedApp) { 9969 // non-privileged applications can never define a priority >0 9970 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 9971 + " package: " + applicationInfo.packageName 9972 + " activity: " + intent.activity.className 9973 + " origPrio: " + intent.getPriority()); 9974 intent.setPriority(0); 9975 return; 9976 } 9977 9978 if (systemActivities == null) { 9979 // the system package is not disabled; we're parsing the system partition 9980 if (isProtectedAction(intent)) { 9981 if (mDeferProtectedFilters) { 9982 // We can't deal with these just yet. No component should ever obtain a 9983 // >0 priority for a protected actions, with ONE exception -- the setup 9984 // wizard. The setup wizard, however, cannot be known until we're able to 9985 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 9986 // until all intent filters have been processed. Chicken, meet egg. 9987 // Let the filter temporarily have a high priority and rectify the 9988 // priorities after all system packages have been scanned. 9989 mProtectedFilters.add(intent); 9990 if (DEBUG_FILTERS) { 9991 Slog.i(TAG, "Protected action; save for later;" 9992 + " package: " + applicationInfo.packageName 9993 + " activity: " + intent.activity.className 9994 + " origPrio: " + intent.getPriority()); 9995 } 9996 return; 9997 } else { 9998 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 9999 Slog.i(TAG, "No setup wizard;" 10000 + " All protected intents capped to priority 0"); 10001 } 10002 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10003 if (DEBUG_FILTERS) { 10004 Slog.i(TAG, "Found setup wizard;" 10005 + " allow priority " + intent.getPriority() + ";" 10006 + " package: " + intent.activity.info.packageName 10007 + " activity: " + intent.activity.className 10008 + " priority: " + intent.getPriority()); 10009 } 10010 // setup wizard gets whatever it wants 10011 return; 10012 } 10013 Slog.w(TAG, "Protected action; cap priority to 0;" 10014 + " package: " + intent.activity.info.packageName 10015 + " activity: " + intent.activity.className 10016 + " origPrio: " + intent.getPriority()); 10017 intent.setPriority(0); 10018 return; 10019 } 10020 } 10021 // privileged apps on the system image get whatever priority they request 10022 return; 10023 } 10024 10025 // privileged app unbundled update ... try to find the same activity 10026 final PackageParser.Activity foundActivity = 10027 findMatchingActivity(systemActivities, activityInfo); 10028 if (foundActivity == null) { 10029 // this is a new activity; it cannot obtain >0 priority 10030 if (DEBUG_FILTERS) { 10031 Slog.i(TAG, "New activity; cap priority to 0;" 10032 + " package: " + applicationInfo.packageName 10033 + " activity: " + intent.activity.className 10034 + " origPrio: " + intent.getPriority()); 10035 } 10036 intent.setPriority(0); 10037 return; 10038 } 10039 10040 // found activity, now check for filter equivalence 10041 10042 // a shallow copy is enough; we modify the list, not its contents 10043 final List<ActivityIntentInfo> intentListCopy = 10044 new ArrayList<>(foundActivity.intents); 10045 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10046 10047 // find matching action subsets 10048 final Iterator<String> actionsIterator = intent.actionsIterator(); 10049 if (actionsIterator != null) { 10050 getIntentListSubset( 10051 intentListCopy, new ActionIterGenerator(), actionsIterator); 10052 if (intentListCopy.size() == 0) { 10053 // no more intents to match; we're not equivalent 10054 if (DEBUG_FILTERS) { 10055 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10056 + " package: " + applicationInfo.packageName 10057 + " activity: " + intent.activity.className 10058 + " origPrio: " + intent.getPriority()); 10059 } 10060 intent.setPriority(0); 10061 return; 10062 } 10063 } 10064 10065 // find matching category subsets 10066 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10067 if (categoriesIterator != null) { 10068 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10069 categoriesIterator); 10070 if (intentListCopy.size() == 0) { 10071 // no more intents to match; we're not equivalent 10072 if (DEBUG_FILTERS) { 10073 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10074 + " package: " + applicationInfo.packageName 10075 + " activity: " + intent.activity.className 10076 + " origPrio: " + intent.getPriority()); 10077 } 10078 intent.setPriority(0); 10079 return; 10080 } 10081 } 10082 10083 // find matching schemes subsets 10084 final Iterator<String> schemesIterator = intent.schemesIterator(); 10085 if (schemesIterator != null) { 10086 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10087 schemesIterator); 10088 if (intentListCopy.size() == 0) { 10089 // no more intents to match; we're not equivalent 10090 if (DEBUG_FILTERS) { 10091 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10092 + " package: " + applicationInfo.packageName 10093 + " activity: " + intent.activity.className 10094 + " origPrio: " + intent.getPriority()); 10095 } 10096 intent.setPriority(0); 10097 return; 10098 } 10099 } 10100 10101 // find matching authorities subsets 10102 final Iterator<IntentFilter.AuthorityEntry> 10103 authoritiesIterator = intent.authoritiesIterator(); 10104 if (authoritiesIterator != null) { 10105 getIntentListSubset(intentListCopy, 10106 new AuthoritiesIterGenerator(), 10107 authoritiesIterator); 10108 if (intentListCopy.size() == 0) { 10109 // no more intents to match; we're not equivalent 10110 if (DEBUG_FILTERS) { 10111 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10112 + " package: " + applicationInfo.packageName 10113 + " activity: " + intent.activity.className 10114 + " origPrio: " + intent.getPriority()); 10115 } 10116 intent.setPriority(0); 10117 return; 10118 } 10119 } 10120 10121 // we found matching filter(s); app gets the max priority of all intents 10122 int cappedPriority = 0; 10123 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10124 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10125 } 10126 if (intent.getPriority() > cappedPriority) { 10127 if (DEBUG_FILTERS) { 10128 Slog.i(TAG, "Found matching filter(s);" 10129 + " cap priority to " + cappedPriority + ";" 10130 + " package: " + applicationInfo.packageName 10131 + " activity: " + intent.activity.className 10132 + " origPrio: " + intent.getPriority()); 10133 } 10134 intent.setPriority(cappedPriority); 10135 return; 10136 } 10137 // all this for nothing; the requested priority was <= what was on the system 10138 } 10139 10140 public final void addActivity(PackageParser.Activity a, String type) { 10141 mActivities.put(a.getComponentName(), a); 10142 if (DEBUG_SHOW_INFO) 10143 Log.v( 10144 TAG, " " + type + " " + 10145 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10146 if (DEBUG_SHOW_INFO) 10147 Log.v(TAG, " Class=" + a.info.name); 10148 final int NI = a.intents.size(); 10149 for (int j=0; j<NI; j++) { 10150 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10151 if ("activity".equals(type)) { 10152 final PackageSetting ps = 10153 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10154 final List<PackageParser.Activity> systemActivities = 10155 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10156 adjustPriority(systemActivities, intent); 10157 } 10158 if (DEBUG_SHOW_INFO) { 10159 Log.v(TAG, " IntentFilter:"); 10160 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10161 } 10162 if (!intent.debugCheck()) { 10163 Log.w(TAG, "==> For Activity " + a.info.name); 10164 } 10165 addFilter(intent); 10166 } 10167 } 10168 10169 public final void removeActivity(PackageParser.Activity a, String type) { 10170 mActivities.remove(a.getComponentName()); 10171 if (DEBUG_SHOW_INFO) { 10172 Log.v(TAG, " " + type + " " 10173 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10174 : a.info.name) + ":"); 10175 Log.v(TAG, " Class=" + a.info.name); 10176 } 10177 final int NI = a.intents.size(); 10178 for (int j=0; j<NI; j++) { 10179 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10180 if (DEBUG_SHOW_INFO) { 10181 Log.v(TAG, " IntentFilter:"); 10182 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10183 } 10184 removeFilter(intent); 10185 } 10186 } 10187 10188 @Override 10189 protected boolean allowFilterResult( 10190 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10191 ActivityInfo filterAi = filter.activity.info; 10192 for (int i=dest.size()-1; i>=0; i--) { 10193 ActivityInfo destAi = dest.get(i).activityInfo; 10194 if (destAi.name == filterAi.name 10195 && destAi.packageName == filterAi.packageName) { 10196 return false; 10197 } 10198 } 10199 return true; 10200 } 10201 10202 @Override 10203 protected ActivityIntentInfo[] newArray(int size) { 10204 return new ActivityIntentInfo[size]; 10205 } 10206 10207 @Override 10208 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10209 if (!sUserManager.exists(userId)) return true; 10210 PackageParser.Package p = filter.activity.owner; 10211 if (p != null) { 10212 PackageSetting ps = (PackageSetting)p.mExtras; 10213 if (ps != null) { 10214 // System apps are never considered stopped for purposes of 10215 // filtering, because there may be no way for the user to 10216 // actually re-launch them. 10217 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10218 && ps.getStopped(userId); 10219 } 10220 } 10221 return false; 10222 } 10223 10224 @Override 10225 protected boolean isPackageForFilter(String packageName, 10226 PackageParser.ActivityIntentInfo info) { 10227 return packageName.equals(info.activity.owner.packageName); 10228 } 10229 10230 @Override 10231 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10232 int match, int userId) { 10233 if (!sUserManager.exists(userId)) return null; 10234 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10235 return null; 10236 } 10237 final PackageParser.Activity activity = info.activity; 10238 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10239 if (ps == null) { 10240 return null; 10241 } 10242 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10243 ps.readUserState(userId), userId); 10244 if (ai == null) { 10245 return null; 10246 } 10247 final ResolveInfo res = new ResolveInfo(); 10248 res.activityInfo = ai; 10249 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10250 res.filter = info; 10251 } 10252 if (info != null) { 10253 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10254 } 10255 res.priority = info.getPriority(); 10256 res.preferredOrder = activity.owner.mPreferredOrder; 10257 //System.out.println("Result: " + res.activityInfo.className + 10258 // " = " + res.priority); 10259 res.match = match; 10260 res.isDefault = info.hasDefault; 10261 res.labelRes = info.labelRes; 10262 res.nonLocalizedLabel = info.nonLocalizedLabel; 10263 if (userNeedsBadging(userId)) { 10264 res.noResourceId = true; 10265 } else { 10266 res.icon = info.icon; 10267 } 10268 res.iconResourceId = info.icon; 10269 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10270 return res; 10271 } 10272 10273 @Override 10274 protected void sortResults(List<ResolveInfo> results) { 10275 Collections.sort(results, mResolvePrioritySorter); 10276 } 10277 10278 @Override 10279 protected void dumpFilter(PrintWriter out, String prefix, 10280 PackageParser.ActivityIntentInfo filter) { 10281 out.print(prefix); out.print( 10282 Integer.toHexString(System.identityHashCode(filter.activity))); 10283 out.print(' '); 10284 filter.activity.printComponentShortName(out); 10285 out.print(" filter "); 10286 out.println(Integer.toHexString(System.identityHashCode(filter))); 10287 } 10288 10289 @Override 10290 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10291 return filter.activity; 10292 } 10293 10294 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10295 PackageParser.Activity activity = (PackageParser.Activity)label; 10296 out.print(prefix); out.print( 10297 Integer.toHexString(System.identityHashCode(activity))); 10298 out.print(' '); 10299 activity.printComponentShortName(out); 10300 if (count > 1) { 10301 out.print(" ("); out.print(count); out.print(" filters)"); 10302 } 10303 out.println(); 10304 } 10305 10306 // Keys are String (activity class name), values are Activity. 10307 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10308 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10309 private int mFlags; 10310 } 10311 10312 private final class ServiceIntentResolver 10313 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10314 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10315 boolean defaultOnly, int userId) { 10316 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10317 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10318 } 10319 10320 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10321 int userId) { 10322 if (!sUserManager.exists(userId)) return null; 10323 mFlags = flags; 10324 return super.queryIntent(intent, resolvedType, 10325 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10326 } 10327 10328 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10329 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10330 if (!sUserManager.exists(userId)) return null; 10331 if (packageServices == null) { 10332 return null; 10333 } 10334 mFlags = flags; 10335 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10336 final int N = packageServices.size(); 10337 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10338 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10339 10340 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10341 for (int i = 0; i < N; ++i) { 10342 intentFilters = packageServices.get(i).intents; 10343 if (intentFilters != null && intentFilters.size() > 0) { 10344 PackageParser.ServiceIntentInfo[] array = 10345 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10346 intentFilters.toArray(array); 10347 listCut.add(array); 10348 } 10349 } 10350 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10351 } 10352 10353 public final void addService(PackageParser.Service s) { 10354 mServices.put(s.getComponentName(), s); 10355 if (DEBUG_SHOW_INFO) { 10356 Log.v(TAG, " " 10357 + (s.info.nonLocalizedLabel != null 10358 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10359 Log.v(TAG, " Class=" + s.info.name); 10360 } 10361 final int NI = s.intents.size(); 10362 int j; 10363 for (j=0; j<NI; j++) { 10364 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10365 if (DEBUG_SHOW_INFO) { 10366 Log.v(TAG, " IntentFilter:"); 10367 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10368 } 10369 if (!intent.debugCheck()) { 10370 Log.w(TAG, "==> For Service " + s.info.name); 10371 } 10372 addFilter(intent); 10373 } 10374 } 10375 10376 public final void removeService(PackageParser.Service s) { 10377 mServices.remove(s.getComponentName()); 10378 if (DEBUG_SHOW_INFO) { 10379 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10380 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10381 Log.v(TAG, " Class=" + s.info.name); 10382 } 10383 final int NI = s.intents.size(); 10384 int j; 10385 for (j=0; j<NI; j++) { 10386 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10387 if (DEBUG_SHOW_INFO) { 10388 Log.v(TAG, " IntentFilter:"); 10389 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10390 } 10391 removeFilter(intent); 10392 } 10393 } 10394 10395 @Override 10396 protected boolean allowFilterResult( 10397 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10398 ServiceInfo filterSi = filter.service.info; 10399 for (int i=dest.size()-1; i>=0; i--) { 10400 ServiceInfo destAi = dest.get(i).serviceInfo; 10401 if (destAi.name == filterSi.name 10402 && destAi.packageName == filterSi.packageName) { 10403 return false; 10404 } 10405 } 10406 return true; 10407 } 10408 10409 @Override 10410 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10411 return new PackageParser.ServiceIntentInfo[size]; 10412 } 10413 10414 @Override 10415 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10416 if (!sUserManager.exists(userId)) return true; 10417 PackageParser.Package p = filter.service.owner; 10418 if (p != null) { 10419 PackageSetting ps = (PackageSetting)p.mExtras; 10420 if (ps != null) { 10421 // System apps are never considered stopped for purposes of 10422 // filtering, because there may be no way for the user to 10423 // actually re-launch them. 10424 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10425 && ps.getStopped(userId); 10426 } 10427 } 10428 return false; 10429 } 10430 10431 @Override 10432 protected boolean isPackageForFilter(String packageName, 10433 PackageParser.ServiceIntentInfo info) { 10434 return packageName.equals(info.service.owner.packageName); 10435 } 10436 10437 @Override 10438 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10439 int match, int userId) { 10440 if (!sUserManager.exists(userId)) return null; 10441 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10442 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10443 return null; 10444 } 10445 final PackageParser.Service service = info.service; 10446 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10447 if (ps == null) { 10448 return null; 10449 } 10450 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10451 ps.readUserState(userId), userId); 10452 if (si == null) { 10453 return null; 10454 } 10455 final ResolveInfo res = new ResolveInfo(); 10456 res.serviceInfo = si; 10457 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10458 res.filter = filter; 10459 } 10460 res.priority = info.getPriority(); 10461 res.preferredOrder = service.owner.mPreferredOrder; 10462 res.match = match; 10463 res.isDefault = info.hasDefault; 10464 res.labelRes = info.labelRes; 10465 res.nonLocalizedLabel = info.nonLocalizedLabel; 10466 res.icon = info.icon; 10467 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10468 return res; 10469 } 10470 10471 @Override 10472 protected void sortResults(List<ResolveInfo> results) { 10473 Collections.sort(results, mResolvePrioritySorter); 10474 } 10475 10476 @Override 10477 protected void dumpFilter(PrintWriter out, String prefix, 10478 PackageParser.ServiceIntentInfo filter) { 10479 out.print(prefix); out.print( 10480 Integer.toHexString(System.identityHashCode(filter.service))); 10481 out.print(' '); 10482 filter.service.printComponentShortName(out); 10483 out.print(" filter "); 10484 out.println(Integer.toHexString(System.identityHashCode(filter))); 10485 } 10486 10487 @Override 10488 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10489 return filter.service; 10490 } 10491 10492 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10493 PackageParser.Service service = (PackageParser.Service)label; 10494 out.print(prefix); out.print( 10495 Integer.toHexString(System.identityHashCode(service))); 10496 out.print(' '); 10497 service.printComponentShortName(out); 10498 if (count > 1) { 10499 out.print(" ("); out.print(count); out.print(" filters)"); 10500 } 10501 out.println(); 10502 } 10503 10504// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10505// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10506// final List<ResolveInfo> retList = Lists.newArrayList(); 10507// while (i.hasNext()) { 10508// final ResolveInfo resolveInfo = (ResolveInfo) i; 10509// if (isEnabledLP(resolveInfo.serviceInfo)) { 10510// retList.add(resolveInfo); 10511// } 10512// } 10513// return retList; 10514// } 10515 10516 // Keys are String (activity class name), values are Activity. 10517 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10518 = new ArrayMap<ComponentName, PackageParser.Service>(); 10519 private int mFlags; 10520 }; 10521 10522 private final class ProviderIntentResolver 10523 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10524 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10525 boolean defaultOnly, int userId) { 10526 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10527 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10528 } 10529 10530 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10531 int userId) { 10532 if (!sUserManager.exists(userId)) 10533 return null; 10534 mFlags = flags; 10535 return super.queryIntent(intent, resolvedType, 10536 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10537 } 10538 10539 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10540 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10541 if (!sUserManager.exists(userId)) 10542 return null; 10543 if (packageProviders == null) { 10544 return null; 10545 } 10546 mFlags = flags; 10547 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10548 final int N = packageProviders.size(); 10549 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10550 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10551 10552 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10553 for (int i = 0; i < N; ++i) { 10554 intentFilters = packageProviders.get(i).intents; 10555 if (intentFilters != null && intentFilters.size() > 0) { 10556 PackageParser.ProviderIntentInfo[] array = 10557 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10558 intentFilters.toArray(array); 10559 listCut.add(array); 10560 } 10561 } 10562 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10563 } 10564 10565 public final void addProvider(PackageParser.Provider p) { 10566 if (mProviders.containsKey(p.getComponentName())) { 10567 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10568 return; 10569 } 10570 10571 mProviders.put(p.getComponentName(), p); 10572 if (DEBUG_SHOW_INFO) { 10573 Log.v(TAG, " " 10574 + (p.info.nonLocalizedLabel != null 10575 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10576 Log.v(TAG, " Class=" + p.info.name); 10577 } 10578 final int NI = p.intents.size(); 10579 int j; 10580 for (j = 0; j < NI; j++) { 10581 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10582 if (DEBUG_SHOW_INFO) { 10583 Log.v(TAG, " IntentFilter:"); 10584 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10585 } 10586 if (!intent.debugCheck()) { 10587 Log.w(TAG, "==> For Provider " + p.info.name); 10588 } 10589 addFilter(intent); 10590 } 10591 } 10592 10593 public final void removeProvider(PackageParser.Provider p) { 10594 mProviders.remove(p.getComponentName()); 10595 if (DEBUG_SHOW_INFO) { 10596 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10597 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10598 Log.v(TAG, " Class=" + p.info.name); 10599 } 10600 final int NI = p.intents.size(); 10601 int j; 10602 for (j = 0; j < NI; j++) { 10603 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10604 if (DEBUG_SHOW_INFO) { 10605 Log.v(TAG, " IntentFilter:"); 10606 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10607 } 10608 removeFilter(intent); 10609 } 10610 } 10611 10612 @Override 10613 protected boolean allowFilterResult( 10614 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10615 ProviderInfo filterPi = filter.provider.info; 10616 for (int i = dest.size() - 1; i >= 0; i--) { 10617 ProviderInfo destPi = dest.get(i).providerInfo; 10618 if (destPi.name == filterPi.name 10619 && destPi.packageName == filterPi.packageName) { 10620 return false; 10621 } 10622 } 10623 return true; 10624 } 10625 10626 @Override 10627 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10628 return new PackageParser.ProviderIntentInfo[size]; 10629 } 10630 10631 @Override 10632 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10633 if (!sUserManager.exists(userId)) 10634 return true; 10635 PackageParser.Package p = filter.provider.owner; 10636 if (p != null) { 10637 PackageSetting ps = (PackageSetting) p.mExtras; 10638 if (ps != null) { 10639 // System apps are never considered stopped for purposes of 10640 // filtering, because there may be no way for the user to 10641 // actually re-launch them. 10642 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10643 && ps.getStopped(userId); 10644 } 10645 } 10646 return false; 10647 } 10648 10649 @Override 10650 protected boolean isPackageForFilter(String packageName, 10651 PackageParser.ProviderIntentInfo info) { 10652 return packageName.equals(info.provider.owner.packageName); 10653 } 10654 10655 @Override 10656 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10657 int match, int userId) { 10658 if (!sUserManager.exists(userId)) 10659 return null; 10660 final PackageParser.ProviderIntentInfo info = filter; 10661 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10662 return null; 10663 } 10664 final PackageParser.Provider provider = info.provider; 10665 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10666 if (ps == null) { 10667 return null; 10668 } 10669 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10670 ps.readUserState(userId), userId); 10671 if (pi == null) { 10672 return null; 10673 } 10674 final ResolveInfo res = new ResolveInfo(); 10675 res.providerInfo = pi; 10676 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10677 res.filter = filter; 10678 } 10679 res.priority = info.getPriority(); 10680 res.preferredOrder = provider.owner.mPreferredOrder; 10681 res.match = match; 10682 res.isDefault = info.hasDefault; 10683 res.labelRes = info.labelRes; 10684 res.nonLocalizedLabel = info.nonLocalizedLabel; 10685 res.icon = info.icon; 10686 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10687 return res; 10688 } 10689 10690 @Override 10691 protected void sortResults(List<ResolveInfo> results) { 10692 Collections.sort(results, mResolvePrioritySorter); 10693 } 10694 10695 @Override 10696 protected void dumpFilter(PrintWriter out, String prefix, 10697 PackageParser.ProviderIntentInfo filter) { 10698 out.print(prefix); 10699 out.print( 10700 Integer.toHexString(System.identityHashCode(filter.provider))); 10701 out.print(' '); 10702 filter.provider.printComponentShortName(out); 10703 out.print(" filter "); 10704 out.println(Integer.toHexString(System.identityHashCode(filter))); 10705 } 10706 10707 @Override 10708 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10709 return filter.provider; 10710 } 10711 10712 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10713 PackageParser.Provider provider = (PackageParser.Provider)label; 10714 out.print(prefix); out.print( 10715 Integer.toHexString(System.identityHashCode(provider))); 10716 out.print(' '); 10717 provider.printComponentShortName(out); 10718 if (count > 1) { 10719 out.print(" ("); out.print(count); out.print(" filters)"); 10720 } 10721 out.println(); 10722 } 10723 10724 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10725 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10726 private int mFlags; 10727 } 10728 10729 private static final class EphemeralIntentResolver 10730 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10731 @Override 10732 protected EphemeralResolveIntentInfo[] newArray(int size) { 10733 return new EphemeralResolveIntentInfo[size]; 10734 } 10735 10736 @Override 10737 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10738 return true; 10739 } 10740 10741 @Override 10742 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10743 int userId) { 10744 if (!sUserManager.exists(userId)) { 10745 return null; 10746 } 10747 return info.getEphemeralResolveInfo(); 10748 } 10749 } 10750 10751 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10752 new Comparator<ResolveInfo>() { 10753 public int compare(ResolveInfo r1, ResolveInfo r2) { 10754 int v1 = r1.priority; 10755 int v2 = r2.priority; 10756 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10757 if (v1 != v2) { 10758 return (v1 > v2) ? -1 : 1; 10759 } 10760 v1 = r1.preferredOrder; 10761 v2 = r2.preferredOrder; 10762 if (v1 != v2) { 10763 return (v1 > v2) ? -1 : 1; 10764 } 10765 if (r1.isDefault != r2.isDefault) { 10766 return r1.isDefault ? -1 : 1; 10767 } 10768 v1 = r1.match; 10769 v2 = r2.match; 10770 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10771 if (v1 != v2) { 10772 return (v1 > v2) ? -1 : 1; 10773 } 10774 if (r1.system != r2.system) { 10775 return r1.system ? -1 : 1; 10776 } 10777 if (r1.activityInfo != null) { 10778 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10779 } 10780 if (r1.serviceInfo != null) { 10781 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10782 } 10783 if (r1.providerInfo != null) { 10784 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10785 } 10786 return 0; 10787 } 10788 }; 10789 10790 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10791 new Comparator<ProviderInfo>() { 10792 public int compare(ProviderInfo p1, ProviderInfo p2) { 10793 final int v1 = p1.initOrder; 10794 final int v2 = p2.initOrder; 10795 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10796 } 10797 }; 10798 10799 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10800 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10801 final int[] userIds) { 10802 mHandler.post(new Runnable() { 10803 @Override 10804 public void run() { 10805 try { 10806 final IActivityManager am = ActivityManagerNative.getDefault(); 10807 if (am == null) return; 10808 final int[] resolvedUserIds; 10809 if (userIds == null) { 10810 resolvedUserIds = am.getRunningUserIds(); 10811 } else { 10812 resolvedUserIds = userIds; 10813 } 10814 for (int id : resolvedUserIds) { 10815 final Intent intent = new Intent(action, 10816 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10817 if (extras != null) { 10818 intent.putExtras(extras); 10819 } 10820 if (targetPkg != null) { 10821 intent.setPackage(targetPkg); 10822 } 10823 // Modify the UID when posting to other users 10824 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10825 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10826 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10827 intent.putExtra(Intent.EXTRA_UID, uid); 10828 } 10829 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10830 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10831 if (DEBUG_BROADCASTS) { 10832 RuntimeException here = new RuntimeException("here"); 10833 here.fillInStackTrace(); 10834 Slog.d(TAG, "Sending to user " + id + ": " 10835 + intent.toShortString(false, true, false, false) 10836 + " " + intent.getExtras(), here); 10837 } 10838 am.broadcastIntent(null, intent, null, finishedReceiver, 10839 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10840 null, finishedReceiver != null, false, id); 10841 } 10842 } catch (RemoteException ex) { 10843 } 10844 } 10845 }); 10846 } 10847 10848 /** 10849 * Check if the external storage media is available. This is true if there 10850 * is a mounted external storage medium or if the external storage is 10851 * emulated. 10852 */ 10853 private boolean isExternalMediaAvailable() { 10854 return mMediaMounted || Environment.isExternalStorageEmulated(); 10855 } 10856 10857 @Override 10858 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10859 // writer 10860 synchronized (mPackages) { 10861 if (!isExternalMediaAvailable()) { 10862 // If the external storage is no longer mounted at this point, 10863 // the caller may not have been able to delete all of this 10864 // packages files and can not delete any more. Bail. 10865 return null; 10866 } 10867 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10868 if (lastPackage != null) { 10869 pkgs.remove(lastPackage); 10870 } 10871 if (pkgs.size() > 0) { 10872 return pkgs.get(0); 10873 } 10874 } 10875 return null; 10876 } 10877 10878 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10879 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10880 userId, andCode ? 1 : 0, packageName); 10881 if (mSystemReady) { 10882 msg.sendToTarget(); 10883 } else { 10884 if (mPostSystemReadyMessages == null) { 10885 mPostSystemReadyMessages = new ArrayList<>(); 10886 } 10887 mPostSystemReadyMessages.add(msg); 10888 } 10889 } 10890 10891 void startCleaningPackages() { 10892 // reader 10893 if (!isExternalMediaAvailable()) { 10894 return; 10895 } 10896 synchronized (mPackages) { 10897 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10898 return; 10899 } 10900 } 10901 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10902 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10903 IActivityManager am = ActivityManagerNative.getDefault(); 10904 if (am != null) { 10905 try { 10906 am.startService(null, intent, null, mContext.getOpPackageName(), 10907 UserHandle.USER_SYSTEM); 10908 } catch (RemoteException e) { 10909 } 10910 } 10911 } 10912 10913 @Override 10914 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10915 int installFlags, String installerPackageName, int userId) { 10916 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10917 10918 final int callingUid = Binder.getCallingUid(); 10919 enforceCrossUserPermission(callingUid, userId, 10920 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10921 10922 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10923 try { 10924 if (observer != null) { 10925 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10926 } 10927 } catch (RemoteException re) { 10928 } 10929 return; 10930 } 10931 10932 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10933 installFlags |= PackageManager.INSTALL_FROM_ADB; 10934 10935 } else { 10936 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10937 // about installerPackageName. 10938 10939 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10940 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10941 } 10942 10943 UserHandle user; 10944 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10945 user = UserHandle.ALL; 10946 } else { 10947 user = new UserHandle(userId); 10948 } 10949 10950 // Only system components can circumvent runtime permissions when installing. 10951 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10952 && mContext.checkCallingOrSelfPermission(Manifest.permission 10953 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10954 throw new SecurityException("You need the " 10955 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10956 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10957 } 10958 10959 final File originFile = new File(originPath); 10960 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10961 10962 final Message msg = mHandler.obtainMessage(INIT_COPY); 10963 final VerificationInfo verificationInfo = new VerificationInfo( 10964 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10965 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10966 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10967 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10968 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10969 msg.obj = params; 10970 10971 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10972 System.identityHashCode(msg.obj)); 10973 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10974 System.identityHashCode(msg.obj)); 10975 10976 mHandler.sendMessage(msg); 10977 } 10978 10979 void installStage(String packageName, File stagedDir, String stagedCid, 10980 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10981 String installerPackageName, int installerUid, UserHandle user) { 10982 if (DEBUG_EPHEMERAL) { 10983 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10984 Slog.d(TAG, "Ephemeral install of " + packageName); 10985 } 10986 } 10987 final VerificationInfo verificationInfo = new VerificationInfo( 10988 sessionParams.originatingUri, sessionParams.referrerUri, 10989 sessionParams.originatingUid, installerUid); 10990 10991 final OriginInfo origin; 10992 if (stagedDir != null) { 10993 origin = OriginInfo.fromStagedFile(stagedDir); 10994 } else { 10995 origin = OriginInfo.fromStagedContainer(stagedCid); 10996 } 10997 10998 final Message msg = mHandler.obtainMessage(INIT_COPY); 10999 final InstallParams params = new InstallParams(origin, null, observer, 11000 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11001 verificationInfo, user, sessionParams.abiOverride, 11002 sessionParams.grantedRuntimePermissions); 11003 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11004 msg.obj = params; 11005 11006 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11007 System.identityHashCode(msg.obj)); 11008 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11009 System.identityHashCode(msg.obj)); 11010 11011 mHandler.sendMessage(msg); 11012 } 11013 11014 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11015 int userId) { 11016 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11017 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11018 } 11019 11020 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11021 int appId, int userId) { 11022 Bundle extras = new Bundle(1); 11023 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11024 11025 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11026 packageName, extras, 0, null, null, new int[] {userId}); 11027 try { 11028 IActivityManager am = ActivityManagerNative.getDefault(); 11029 if (isSystem && am.isUserRunning(userId, 0)) { 11030 // The just-installed/enabled app is bundled on the system, so presumed 11031 // to be able to run automatically without needing an explicit launch. 11032 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11033 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11034 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11035 .setPackage(packageName); 11036 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11037 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11038 } 11039 } catch (RemoteException e) { 11040 // shouldn't happen 11041 Slog.w(TAG, "Unable to bootstrap installed package", e); 11042 } 11043 } 11044 11045 @Override 11046 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11047 int userId) { 11048 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11049 PackageSetting pkgSetting; 11050 final int uid = Binder.getCallingUid(); 11051 enforceCrossUserPermission(uid, userId, 11052 true /* requireFullPermission */, true /* checkShell */, 11053 "setApplicationHiddenSetting for user " + userId); 11054 11055 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11056 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11057 return false; 11058 } 11059 11060 long callingId = Binder.clearCallingIdentity(); 11061 try { 11062 boolean sendAdded = false; 11063 boolean sendRemoved = false; 11064 // writer 11065 synchronized (mPackages) { 11066 pkgSetting = mSettings.mPackages.get(packageName); 11067 if (pkgSetting == null) { 11068 return false; 11069 } 11070 if (pkgSetting.getHidden(userId) != hidden) { 11071 pkgSetting.setHidden(hidden, userId); 11072 mSettings.writePackageRestrictionsLPr(userId); 11073 if (hidden) { 11074 sendRemoved = true; 11075 } else { 11076 sendAdded = true; 11077 } 11078 } 11079 } 11080 if (sendAdded) { 11081 sendPackageAddedForUser(packageName, pkgSetting, userId); 11082 return true; 11083 } 11084 if (sendRemoved) { 11085 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11086 "hiding pkg"); 11087 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11088 return true; 11089 } 11090 } finally { 11091 Binder.restoreCallingIdentity(callingId); 11092 } 11093 return false; 11094 } 11095 11096 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11097 int userId) { 11098 final PackageRemovedInfo info = new PackageRemovedInfo(); 11099 info.removedPackage = packageName; 11100 info.removedUsers = new int[] {userId}; 11101 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11102 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11103 } 11104 11105 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11106 if (pkgList.length > 0) { 11107 Bundle extras = new Bundle(1); 11108 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11109 11110 sendPackageBroadcast( 11111 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11112 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11113 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11114 new int[] {userId}); 11115 } 11116 } 11117 11118 /** 11119 * Returns true if application is not found or there was an error. Otherwise it returns 11120 * the hidden state of the package for the given user. 11121 */ 11122 @Override 11123 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11124 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11125 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11126 true /* requireFullPermission */, false /* checkShell */, 11127 "getApplicationHidden for user " + userId); 11128 PackageSetting pkgSetting; 11129 long callingId = Binder.clearCallingIdentity(); 11130 try { 11131 // writer 11132 synchronized (mPackages) { 11133 pkgSetting = mSettings.mPackages.get(packageName); 11134 if (pkgSetting == null) { 11135 return true; 11136 } 11137 return pkgSetting.getHidden(userId); 11138 } 11139 } finally { 11140 Binder.restoreCallingIdentity(callingId); 11141 } 11142 } 11143 11144 /** 11145 * @hide 11146 */ 11147 @Override 11148 public int installExistingPackageAsUser(String packageName, int userId) { 11149 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11150 null); 11151 PackageSetting pkgSetting; 11152 final int uid = Binder.getCallingUid(); 11153 enforceCrossUserPermission(uid, userId, 11154 true /* requireFullPermission */, true /* checkShell */, 11155 "installExistingPackage for user " + userId); 11156 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11157 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11158 } 11159 11160 long callingId = Binder.clearCallingIdentity(); 11161 try { 11162 boolean installed = false; 11163 11164 // writer 11165 synchronized (mPackages) { 11166 pkgSetting = mSettings.mPackages.get(packageName); 11167 if (pkgSetting == null) { 11168 return PackageManager.INSTALL_FAILED_INVALID_URI; 11169 } 11170 if (!pkgSetting.getInstalled(userId)) { 11171 pkgSetting.setInstalled(true, userId); 11172 pkgSetting.setHidden(false, userId); 11173 mSettings.writePackageRestrictionsLPr(userId); 11174 installed = true; 11175 } 11176 } 11177 11178 if (installed) { 11179 if (pkgSetting.pkg != null) { 11180 prepareAppDataAfterInstall(pkgSetting.pkg); 11181 } 11182 sendPackageAddedForUser(packageName, pkgSetting, userId); 11183 } 11184 } finally { 11185 Binder.restoreCallingIdentity(callingId); 11186 } 11187 11188 return PackageManager.INSTALL_SUCCEEDED; 11189 } 11190 11191 boolean isUserRestricted(int userId, String restrictionKey) { 11192 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11193 if (restrictions.getBoolean(restrictionKey, false)) { 11194 Log.w(TAG, "User is restricted: " + restrictionKey); 11195 return true; 11196 } 11197 return false; 11198 } 11199 11200 @Override 11201 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11202 int userId) { 11203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11204 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11205 true /* requireFullPermission */, true /* checkShell */, 11206 "setPackagesSuspended for user " + userId); 11207 11208 if (ArrayUtils.isEmpty(packageNames)) { 11209 return packageNames; 11210 } 11211 11212 // List of package names for whom the suspended state has changed. 11213 List<String> changedPackages = new ArrayList<>(packageNames.length); 11214 // List of package names for whom the suspended state is not set as requested in this 11215 // method. 11216 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11217 for (int i = 0; i < packageNames.length; i++) { 11218 String packageName = packageNames[i]; 11219 long callingId = Binder.clearCallingIdentity(); 11220 try { 11221 boolean changed = false; 11222 final int appId; 11223 synchronized (mPackages) { 11224 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11225 if (pkgSetting == null) { 11226 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11227 + "\". Skipping suspending/un-suspending."); 11228 unactionedPackages.add(packageName); 11229 continue; 11230 } 11231 appId = pkgSetting.appId; 11232 if (pkgSetting.getSuspended(userId) != suspended) { 11233 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11234 unactionedPackages.add(packageName); 11235 continue; 11236 } 11237 pkgSetting.setSuspended(suspended, userId); 11238 mSettings.writePackageRestrictionsLPr(userId); 11239 changed = true; 11240 changedPackages.add(packageName); 11241 } 11242 } 11243 11244 if (changed && suspended) { 11245 killApplication(packageName, UserHandle.getUid(userId, appId), 11246 "suspending package"); 11247 } 11248 } finally { 11249 Binder.restoreCallingIdentity(callingId); 11250 } 11251 } 11252 11253 if (!changedPackages.isEmpty()) { 11254 sendPackagesSuspendedForUser(changedPackages.toArray( 11255 new String[changedPackages.size()]), userId, suspended); 11256 } 11257 11258 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11259 } 11260 11261 @Override 11262 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11264 true /* requireFullPermission */, false /* checkShell */, 11265 "isPackageSuspendedForUser for user " + userId); 11266 synchronized (mPackages) { 11267 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11268 if (pkgSetting == null) { 11269 throw new IllegalArgumentException("Unknown target package: " + packageName); 11270 } 11271 return pkgSetting.getSuspended(userId); 11272 } 11273 } 11274 11275 /** 11276 * TODO: cache and disallow blocking the active dialer. 11277 * 11278 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11279 */ 11280 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11281 if (isPackageDeviceAdmin(packageName, userId)) { 11282 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11283 + "\": has an active device admin"); 11284 return false; 11285 } 11286 11287 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11288 if (packageName.equals(activeLauncherPackageName)) { 11289 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11290 + "\": contains the active launcher"); 11291 return false; 11292 } 11293 11294 if (packageName.equals(mRequiredInstallerPackage)) { 11295 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11296 + "\": required for package installation"); 11297 return false; 11298 } 11299 11300 if (packageName.equals(mRequiredVerifierPackage)) { 11301 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11302 + "\": required for package verification"); 11303 return false; 11304 } 11305 11306 final PackageParser.Package pkg = mPackages.get(packageName); 11307 if (pkg != null && isPrivilegedApp(pkg)) { 11308 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11309 + "\": is a privileged app"); 11310 return false; 11311 } 11312 11313 return true; 11314 } 11315 11316 private String getActiveLauncherPackageName(int userId) { 11317 Intent intent = new Intent(Intent.ACTION_MAIN); 11318 intent.addCategory(Intent.CATEGORY_HOME); 11319 ResolveInfo resolveInfo = resolveIntent( 11320 intent, 11321 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11322 PackageManager.MATCH_DEFAULT_ONLY, 11323 userId); 11324 11325 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11326 } 11327 11328 @Override 11329 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11330 mContext.enforceCallingOrSelfPermission( 11331 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11332 "Only package verification agents can verify applications"); 11333 11334 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11335 final PackageVerificationResponse response = new PackageVerificationResponse( 11336 verificationCode, Binder.getCallingUid()); 11337 msg.arg1 = id; 11338 msg.obj = response; 11339 mHandler.sendMessage(msg); 11340 } 11341 11342 @Override 11343 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11344 long millisecondsToDelay) { 11345 mContext.enforceCallingOrSelfPermission( 11346 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11347 "Only package verification agents can extend verification timeouts"); 11348 11349 final PackageVerificationState state = mPendingVerification.get(id); 11350 final PackageVerificationResponse response = new PackageVerificationResponse( 11351 verificationCodeAtTimeout, Binder.getCallingUid()); 11352 11353 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11354 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11355 } 11356 if (millisecondsToDelay < 0) { 11357 millisecondsToDelay = 0; 11358 } 11359 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11360 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11361 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11362 } 11363 11364 if ((state != null) && !state.timeoutExtended()) { 11365 state.extendTimeout(); 11366 11367 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11368 msg.arg1 = id; 11369 msg.obj = response; 11370 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11371 } 11372 } 11373 11374 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11375 int verificationCode, UserHandle user) { 11376 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11377 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11378 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11379 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11380 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11381 11382 mContext.sendBroadcastAsUser(intent, user, 11383 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11384 } 11385 11386 private ComponentName matchComponentForVerifier(String packageName, 11387 List<ResolveInfo> receivers) { 11388 ActivityInfo targetReceiver = null; 11389 11390 final int NR = receivers.size(); 11391 for (int i = 0; i < NR; i++) { 11392 final ResolveInfo info = receivers.get(i); 11393 if (info.activityInfo == null) { 11394 continue; 11395 } 11396 11397 if (packageName.equals(info.activityInfo.packageName)) { 11398 targetReceiver = info.activityInfo; 11399 break; 11400 } 11401 } 11402 11403 if (targetReceiver == null) { 11404 return null; 11405 } 11406 11407 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11408 } 11409 11410 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11411 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11412 if (pkgInfo.verifiers.length == 0) { 11413 return null; 11414 } 11415 11416 final int N = pkgInfo.verifiers.length; 11417 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11418 for (int i = 0; i < N; i++) { 11419 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11420 11421 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11422 receivers); 11423 if (comp == null) { 11424 continue; 11425 } 11426 11427 final int verifierUid = getUidForVerifier(verifierInfo); 11428 if (verifierUid == -1) { 11429 continue; 11430 } 11431 11432 if (DEBUG_VERIFY) { 11433 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11434 + " with the correct signature"); 11435 } 11436 sufficientVerifiers.add(comp); 11437 verificationState.addSufficientVerifier(verifierUid); 11438 } 11439 11440 return sufficientVerifiers; 11441 } 11442 11443 private int getUidForVerifier(VerifierInfo verifierInfo) { 11444 synchronized (mPackages) { 11445 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11446 if (pkg == null) { 11447 return -1; 11448 } else if (pkg.mSignatures.length != 1) { 11449 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11450 + " has more than one signature; ignoring"); 11451 return -1; 11452 } 11453 11454 /* 11455 * If the public key of the package's signature does not match 11456 * our expected public key, then this is a different package and 11457 * we should skip. 11458 */ 11459 11460 final byte[] expectedPublicKey; 11461 try { 11462 final Signature verifierSig = pkg.mSignatures[0]; 11463 final PublicKey publicKey = verifierSig.getPublicKey(); 11464 expectedPublicKey = publicKey.getEncoded(); 11465 } catch (CertificateException e) { 11466 return -1; 11467 } 11468 11469 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11470 11471 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11472 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11473 + " does not have the expected public key; ignoring"); 11474 return -1; 11475 } 11476 11477 return pkg.applicationInfo.uid; 11478 } 11479 } 11480 11481 @Override 11482 public void finishPackageInstall(int token) { 11483 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11484 11485 if (DEBUG_INSTALL) { 11486 Slog.v(TAG, "BM finishing package install for " + token); 11487 } 11488 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11489 11490 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11491 mHandler.sendMessage(msg); 11492 } 11493 11494 /** 11495 * Get the verification agent timeout. 11496 * 11497 * @return verification timeout in milliseconds 11498 */ 11499 private long getVerificationTimeout() { 11500 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11501 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11502 DEFAULT_VERIFICATION_TIMEOUT); 11503 } 11504 11505 /** 11506 * Get the default verification agent response code. 11507 * 11508 * @return default verification response code 11509 */ 11510 private int getDefaultVerificationResponse() { 11511 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11512 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11513 DEFAULT_VERIFICATION_RESPONSE); 11514 } 11515 11516 /** 11517 * Check whether or not package verification has been enabled. 11518 * 11519 * @return true if verification should be performed 11520 */ 11521 private boolean isVerificationEnabled(int userId, int installFlags) { 11522 if (!DEFAULT_VERIFY_ENABLE) { 11523 return false; 11524 } 11525 // Ephemeral apps don't get the full verification treatment 11526 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11527 if (DEBUG_EPHEMERAL) { 11528 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11529 } 11530 return false; 11531 } 11532 11533 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11534 11535 // Check if installing from ADB 11536 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11537 // Do not run verification in a test harness environment 11538 if (ActivityManager.isRunningInTestHarness()) { 11539 return false; 11540 } 11541 if (ensureVerifyAppsEnabled) { 11542 return true; 11543 } 11544 // Check if the developer does not want package verification for ADB installs 11545 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11546 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11547 return false; 11548 } 11549 } 11550 11551 if (ensureVerifyAppsEnabled) { 11552 return true; 11553 } 11554 11555 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11556 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11557 } 11558 11559 @Override 11560 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11561 throws RemoteException { 11562 mContext.enforceCallingOrSelfPermission( 11563 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11564 "Only intentfilter verification agents can verify applications"); 11565 11566 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11567 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11568 Binder.getCallingUid(), verificationCode, failedDomains); 11569 msg.arg1 = id; 11570 msg.obj = response; 11571 mHandler.sendMessage(msg); 11572 } 11573 11574 @Override 11575 public int getIntentVerificationStatus(String packageName, int userId) { 11576 synchronized (mPackages) { 11577 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11578 } 11579 } 11580 11581 @Override 11582 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11583 mContext.enforceCallingOrSelfPermission( 11584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11585 11586 boolean result = false; 11587 synchronized (mPackages) { 11588 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11589 } 11590 if (result) { 11591 scheduleWritePackageRestrictionsLocked(userId); 11592 } 11593 return result; 11594 } 11595 11596 @Override 11597 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11598 String packageName) { 11599 synchronized (mPackages) { 11600 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11601 } 11602 } 11603 11604 @Override 11605 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11606 if (TextUtils.isEmpty(packageName)) { 11607 return ParceledListSlice.emptyList(); 11608 } 11609 synchronized (mPackages) { 11610 PackageParser.Package pkg = mPackages.get(packageName); 11611 if (pkg == null || pkg.activities == null) { 11612 return ParceledListSlice.emptyList(); 11613 } 11614 final int count = pkg.activities.size(); 11615 ArrayList<IntentFilter> result = new ArrayList<>(); 11616 for (int n=0; n<count; n++) { 11617 PackageParser.Activity activity = pkg.activities.get(n); 11618 if (activity.intents != null && activity.intents.size() > 0) { 11619 result.addAll(activity.intents); 11620 } 11621 } 11622 return new ParceledListSlice<>(result); 11623 } 11624 } 11625 11626 @Override 11627 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11628 mContext.enforceCallingOrSelfPermission( 11629 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11630 11631 synchronized (mPackages) { 11632 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11633 if (packageName != null) { 11634 result |= updateIntentVerificationStatus(packageName, 11635 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11636 userId); 11637 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11638 packageName, userId); 11639 } 11640 return result; 11641 } 11642 } 11643 11644 @Override 11645 public String getDefaultBrowserPackageName(int userId) { 11646 synchronized (mPackages) { 11647 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11648 } 11649 } 11650 11651 /** 11652 * Get the "allow unknown sources" setting. 11653 * 11654 * @return the current "allow unknown sources" setting 11655 */ 11656 private int getUnknownSourcesSettings() { 11657 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11658 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11659 -1); 11660 } 11661 11662 @Override 11663 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11664 final int uid = Binder.getCallingUid(); 11665 // writer 11666 synchronized (mPackages) { 11667 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11668 if (targetPackageSetting == null) { 11669 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11670 } 11671 11672 PackageSetting installerPackageSetting; 11673 if (installerPackageName != null) { 11674 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11675 if (installerPackageSetting == null) { 11676 throw new IllegalArgumentException("Unknown installer package: " 11677 + installerPackageName); 11678 } 11679 } else { 11680 installerPackageSetting = null; 11681 } 11682 11683 Signature[] callerSignature; 11684 Object obj = mSettings.getUserIdLPr(uid); 11685 if (obj != null) { 11686 if (obj instanceof SharedUserSetting) { 11687 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11688 } else if (obj instanceof PackageSetting) { 11689 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11690 } else { 11691 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11692 } 11693 } else { 11694 throw new SecurityException("Unknown calling UID: " + uid); 11695 } 11696 11697 // Verify: can't set installerPackageName to a package that is 11698 // not signed with the same cert as the caller. 11699 if (installerPackageSetting != null) { 11700 if (compareSignatures(callerSignature, 11701 installerPackageSetting.signatures.mSignatures) 11702 != PackageManager.SIGNATURE_MATCH) { 11703 throw new SecurityException( 11704 "Caller does not have same cert as new installer package " 11705 + installerPackageName); 11706 } 11707 } 11708 11709 // Verify: if target already has an installer package, it must 11710 // be signed with the same cert as the caller. 11711 if (targetPackageSetting.installerPackageName != null) { 11712 PackageSetting setting = mSettings.mPackages.get( 11713 targetPackageSetting.installerPackageName); 11714 // If the currently set package isn't valid, then it's always 11715 // okay to change it. 11716 if (setting != null) { 11717 if (compareSignatures(callerSignature, 11718 setting.signatures.mSignatures) 11719 != PackageManager.SIGNATURE_MATCH) { 11720 throw new SecurityException( 11721 "Caller does not have same cert as old installer package " 11722 + targetPackageSetting.installerPackageName); 11723 } 11724 } 11725 } 11726 11727 // Okay! 11728 targetPackageSetting.installerPackageName = installerPackageName; 11729 scheduleWriteSettingsLocked(); 11730 } 11731 } 11732 11733 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11734 // Queue up an async operation since the package installation may take a little while. 11735 mHandler.post(new Runnable() { 11736 public void run() { 11737 mHandler.removeCallbacks(this); 11738 // Result object to be returned 11739 PackageInstalledInfo res = new PackageInstalledInfo(); 11740 res.setReturnCode(currentStatus); 11741 res.uid = -1; 11742 res.pkg = null; 11743 res.removedInfo = null; 11744 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11745 args.doPreInstall(res.returnCode); 11746 synchronized (mInstallLock) { 11747 installPackageTracedLI(args, res); 11748 } 11749 args.doPostInstall(res.returnCode, res.uid); 11750 } 11751 11752 // A restore should be performed at this point if (a) the install 11753 // succeeded, (b) the operation is not an update, and (c) the new 11754 // package has not opted out of backup participation. 11755 final boolean update = res.removedInfo != null 11756 && res.removedInfo.removedPackage != null; 11757 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11758 boolean doRestore = !update 11759 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11760 11761 // Set up the post-install work request bookkeeping. This will be used 11762 // and cleaned up by the post-install event handling regardless of whether 11763 // there's a restore pass performed. Token values are >= 1. 11764 int token; 11765 if (mNextInstallToken < 0) mNextInstallToken = 1; 11766 token = mNextInstallToken++; 11767 11768 PostInstallData data = new PostInstallData(args, res); 11769 mRunningInstalls.put(token, data); 11770 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11771 11772 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11773 // Pass responsibility to the Backup Manager. It will perform a 11774 // restore if appropriate, then pass responsibility back to the 11775 // Package Manager to run the post-install observer callbacks 11776 // and broadcasts. 11777 IBackupManager bm = IBackupManager.Stub.asInterface( 11778 ServiceManager.getService(Context.BACKUP_SERVICE)); 11779 if (bm != null) { 11780 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11781 + " to BM for possible restore"); 11782 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11783 try { 11784 // TODO: http://b/22388012 11785 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11786 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11787 } else { 11788 doRestore = false; 11789 } 11790 } catch (RemoteException e) { 11791 // can't happen; the backup manager is local 11792 } catch (Exception e) { 11793 Slog.e(TAG, "Exception trying to enqueue restore", e); 11794 doRestore = false; 11795 } 11796 } else { 11797 Slog.e(TAG, "Backup Manager not found!"); 11798 doRestore = false; 11799 } 11800 } 11801 11802 if (!doRestore) { 11803 // No restore possible, or the Backup Manager was mysteriously not 11804 // available -- just fire the post-install work request directly. 11805 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11806 11807 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11808 11809 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11810 mHandler.sendMessage(msg); 11811 } 11812 } 11813 }); 11814 } 11815 11816 private abstract class HandlerParams { 11817 private static final int MAX_RETRIES = 4; 11818 11819 /** 11820 * Number of times startCopy() has been attempted and had a non-fatal 11821 * error. 11822 */ 11823 private int mRetries = 0; 11824 11825 /** User handle for the user requesting the information or installation. */ 11826 private final UserHandle mUser; 11827 String traceMethod; 11828 int traceCookie; 11829 11830 HandlerParams(UserHandle user) { 11831 mUser = user; 11832 } 11833 11834 UserHandle getUser() { 11835 return mUser; 11836 } 11837 11838 HandlerParams setTraceMethod(String traceMethod) { 11839 this.traceMethod = traceMethod; 11840 return this; 11841 } 11842 11843 HandlerParams setTraceCookie(int traceCookie) { 11844 this.traceCookie = traceCookie; 11845 return this; 11846 } 11847 11848 final boolean startCopy() { 11849 boolean res; 11850 try { 11851 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11852 11853 if (++mRetries > MAX_RETRIES) { 11854 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11855 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11856 handleServiceError(); 11857 return false; 11858 } else { 11859 handleStartCopy(); 11860 res = true; 11861 } 11862 } catch (RemoteException e) { 11863 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11864 mHandler.sendEmptyMessage(MCS_RECONNECT); 11865 res = false; 11866 } 11867 handleReturnCode(); 11868 return res; 11869 } 11870 11871 final void serviceError() { 11872 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11873 handleServiceError(); 11874 handleReturnCode(); 11875 } 11876 11877 abstract void handleStartCopy() throws RemoteException; 11878 abstract void handleServiceError(); 11879 abstract void handleReturnCode(); 11880 } 11881 11882 class MeasureParams extends HandlerParams { 11883 private final PackageStats mStats; 11884 private boolean mSuccess; 11885 11886 private final IPackageStatsObserver mObserver; 11887 11888 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11889 super(new UserHandle(stats.userHandle)); 11890 mObserver = observer; 11891 mStats = stats; 11892 } 11893 11894 @Override 11895 public String toString() { 11896 return "MeasureParams{" 11897 + Integer.toHexString(System.identityHashCode(this)) 11898 + " " + mStats.packageName + "}"; 11899 } 11900 11901 @Override 11902 void handleStartCopy() throws RemoteException { 11903 synchronized (mInstallLock) { 11904 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11905 } 11906 11907 if (mSuccess) { 11908 final boolean mounted; 11909 if (Environment.isExternalStorageEmulated()) { 11910 mounted = true; 11911 } else { 11912 final String status = Environment.getExternalStorageState(); 11913 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11914 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11915 } 11916 11917 if (mounted) { 11918 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11919 11920 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11921 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11922 11923 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11924 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11925 11926 // Always subtract cache size, since it's a subdirectory 11927 mStats.externalDataSize -= mStats.externalCacheSize; 11928 11929 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11930 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11931 11932 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11933 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11934 } 11935 } 11936 } 11937 11938 @Override 11939 void handleReturnCode() { 11940 if (mObserver != null) { 11941 try { 11942 mObserver.onGetStatsCompleted(mStats, mSuccess); 11943 } catch (RemoteException e) { 11944 Slog.i(TAG, "Observer no longer exists."); 11945 } 11946 } 11947 } 11948 11949 @Override 11950 void handleServiceError() { 11951 Slog.e(TAG, "Could not measure application " + mStats.packageName 11952 + " external storage"); 11953 } 11954 } 11955 11956 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11957 throws RemoteException { 11958 long result = 0; 11959 for (File path : paths) { 11960 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11961 } 11962 return result; 11963 } 11964 11965 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11966 for (File path : paths) { 11967 try { 11968 mcs.clearDirectory(path.getAbsolutePath()); 11969 } catch (RemoteException e) { 11970 } 11971 } 11972 } 11973 11974 static class OriginInfo { 11975 /** 11976 * Location where install is coming from, before it has been 11977 * copied/renamed into place. This could be a single monolithic APK 11978 * file, or a cluster directory. This location may be untrusted. 11979 */ 11980 final File file; 11981 final String cid; 11982 11983 /** 11984 * Flag indicating that {@link #file} or {@link #cid} has already been 11985 * staged, meaning downstream users don't need to defensively copy the 11986 * contents. 11987 */ 11988 final boolean staged; 11989 11990 /** 11991 * Flag indicating that {@link #file} or {@link #cid} is an already 11992 * installed app that is being moved. 11993 */ 11994 final boolean existing; 11995 11996 final String resolvedPath; 11997 final File resolvedFile; 11998 11999 static OriginInfo fromNothing() { 12000 return new OriginInfo(null, null, false, false); 12001 } 12002 12003 static OriginInfo fromUntrustedFile(File file) { 12004 return new OriginInfo(file, null, false, false); 12005 } 12006 12007 static OriginInfo fromExistingFile(File file) { 12008 return new OriginInfo(file, null, false, true); 12009 } 12010 12011 static OriginInfo fromStagedFile(File file) { 12012 return new OriginInfo(file, null, true, false); 12013 } 12014 12015 static OriginInfo fromStagedContainer(String cid) { 12016 return new OriginInfo(null, cid, true, false); 12017 } 12018 12019 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12020 this.file = file; 12021 this.cid = cid; 12022 this.staged = staged; 12023 this.existing = existing; 12024 12025 if (cid != null) { 12026 resolvedPath = PackageHelper.getSdDir(cid); 12027 resolvedFile = new File(resolvedPath); 12028 } else if (file != null) { 12029 resolvedPath = file.getAbsolutePath(); 12030 resolvedFile = file; 12031 } else { 12032 resolvedPath = null; 12033 resolvedFile = null; 12034 } 12035 } 12036 } 12037 12038 static class MoveInfo { 12039 final int moveId; 12040 final String fromUuid; 12041 final String toUuid; 12042 final String packageName; 12043 final String dataAppName; 12044 final int appId; 12045 final String seinfo; 12046 final int targetSdkVersion; 12047 12048 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12049 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12050 this.moveId = moveId; 12051 this.fromUuid = fromUuid; 12052 this.toUuid = toUuid; 12053 this.packageName = packageName; 12054 this.dataAppName = dataAppName; 12055 this.appId = appId; 12056 this.seinfo = seinfo; 12057 this.targetSdkVersion = targetSdkVersion; 12058 } 12059 } 12060 12061 static class VerificationInfo { 12062 /** A constant used to indicate that a uid value is not present. */ 12063 public static final int NO_UID = -1; 12064 12065 /** URI referencing where the package was downloaded from. */ 12066 final Uri originatingUri; 12067 12068 /** HTTP referrer URI associated with the originatingURI. */ 12069 final Uri referrer; 12070 12071 /** UID of the application that the install request originated from. */ 12072 final int originatingUid; 12073 12074 /** UID of application requesting the install */ 12075 final int installerUid; 12076 12077 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12078 this.originatingUri = originatingUri; 12079 this.referrer = referrer; 12080 this.originatingUid = originatingUid; 12081 this.installerUid = installerUid; 12082 } 12083 } 12084 12085 class InstallParams extends HandlerParams { 12086 final OriginInfo origin; 12087 final MoveInfo move; 12088 final IPackageInstallObserver2 observer; 12089 int installFlags; 12090 final String installerPackageName; 12091 final String volumeUuid; 12092 private InstallArgs mArgs; 12093 private int mRet; 12094 final String packageAbiOverride; 12095 final String[] grantedRuntimePermissions; 12096 final VerificationInfo verificationInfo; 12097 12098 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12099 int installFlags, String installerPackageName, String volumeUuid, 12100 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12101 String[] grantedPermissions) { 12102 super(user); 12103 this.origin = origin; 12104 this.move = move; 12105 this.observer = observer; 12106 this.installFlags = installFlags; 12107 this.installerPackageName = installerPackageName; 12108 this.volumeUuid = volumeUuid; 12109 this.verificationInfo = verificationInfo; 12110 this.packageAbiOverride = packageAbiOverride; 12111 this.grantedRuntimePermissions = grantedPermissions; 12112 } 12113 12114 @Override 12115 public String toString() { 12116 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12117 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12118 } 12119 12120 private int installLocationPolicy(PackageInfoLite pkgLite) { 12121 String packageName = pkgLite.packageName; 12122 int installLocation = pkgLite.installLocation; 12123 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12124 // reader 12125 synchronized (mPackages) { 12126 // Currently installed package which the new package is attempting to replace or 12127 // null if no such package is installed. 12128 PackageParser.Package installedPkg = mPackages.get(packageName); 12129 // Package which currently owns the data which the new package will own if installed. 12130 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12131 // will be null whereas dataOwnerPkg will contain information about the package 12132 // which was uninstalled while keeping its data. 12133 PackageParser.Package dataOwnerPkg = installedPkg; 12134 if (dataOwnerPkg == null) { 12135 PackageSetting ps = mSettings.mPackages.get(packageName); 12136 if (ps != null) { 12137 dataOwnerPkg = ps.pkg; 12138 } 12139 } 12140 12141 if (dataOwnerPkg != null) { 12142 // If installed, the package will get access to data left on the device by its 12143 // predecessor. As a security measure, this is permited only if this is not a 12144 // version downgrade or if the predecessor package is marked as debuggable and 12145 // a downgrade is explicitly requested. 12146 // 12147 // On debuggable platform builds, downgrades are permitted even for 12148 // non-debuggable packages to make testing easier. Debuggable platform builds do 12149 // not offer security guarantees and thus it's OK to disable some security 12150 // mechanisms to make debugging/testing easier on those builds. However, even on 12151 // debuggable builds downgrades of packages are permitted only if requested via 12152 // installFlags. This is because we aim to keep the behavior of debuggable 12153 // platform builds as close as possible to the behavior of non-debuggable 12154 // platform builds. 12155 final boolean downgradeRequested = 12156 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12157 final boolean packageDebuggable = 12158 (dataOwnerPkg.applicationInfo.flags 12159 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12160 final boolean downgradePermitted = 12161 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12162 if (!downgradePermitted) { 12163 try { 12164 checkDowngrade(dataOwnerPkg, pkgLite); 12165 } catch (PackageManagerException e) { 12166 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12167 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12168 } 12169 } 12170 } 12171 12172 if (installedPkg != null) { 12173 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12174 // Check for updated system application. 12175 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12176 if (onSd) { 12177 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12178 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12179 } 12180 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12181 } else { 12182 if (onSd) { 12183 // Install flag overrides everything. 12184 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12185 } 12186 // If current upgrade specifies particular preference 12187 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12188 // Application explicitly specified internal. 12189 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12190 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12191 // App explictly prefers external. Let policy decide 12192 } else { 12193 // Prefer previous location 12194 if (isExternal(installedPkg)) { 12195 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12196 } 12197 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12198 } 12199 } 12200 } else { 12201 // Invalid install. Return error code 12202 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12203 } 12204 } 12205 } 12206 // All the special cases have been taken care of. 12207 // Return result based on recommended install location. 12208 if (onSd) { 12209 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12210 } 12211 return pkgLite.recommendedInstallLocation; 12212 } 12213 12214 /* 12215 * Invoke remote method to get package information and install 12216 * location values. Override install location based on default 12217 * policy if needed and then create install arguments based 12218 * on the install location. 12219 */ 12220 public void handleStartCopy() throws RemoteException { 12221 int ret = PackageManager.INSTALL_SUCCEEDED; 12222 12223 // If we're already staged, we've firmly committed to an install location 12224 if (origin.staged) { 12225 if (origin.file != null) { 12226 installFlags |= PackageManager.INSTALL_INTERNAL; 12227 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12228 } else if (origin.cid != null) { 12229 installFlags |= PackageManager.INSTALL_EXTERNAL; 12230 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12231 } else { 12232 throw new IllegalStateException("Invalid stage location"); 12233 } 12234 } 12235 12236 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12237 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12238 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12239 PackageInfoLite pkgLite = null; 12240 12241 if (onInt && onSd) { 12242 // Check if both bits are set. 12243 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12244 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12245 } else if (onSd && ephemeral) { 12246 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12247 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12248 } else { 12249 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12250 packageAbiOverride); 12251 12252 if (DEBUG_EPHEMERAL && ephemeral) { 12253 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12254 } 12255 12256 /* 12257 * If we have too little free space, try to free cache 12258 * before giving up. 12259 */ 12260 if (!origin.staged && pkgLite.recommendedInstallLocation 12261 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12262 // TODO: focus freeing disk space on the target device 12263 final StorageManager storage = StorageManager.from(mContext); 12264 final long lowThreshold = storage.getStorageLowBytes( 12265 Environment.getDataDirectory()); 12266 12267 final long sizeBytes = mContainerService.calculateInstalledSize( 12268 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12269 12270 try { 12271 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12272 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12273 installFlags, packageAbiOverride); 12274 } catch (InstallerException e) { 12275 Slog.w(TAG, "Failed to free cache", e); 12276 } 12277 12278 /* 12279 * The cache free must have deleted the file we 12280 * downloaded to install. 12281 * 12282 * TODO: fix the "freeCache" call to not delete 12283 * the file we care about. 12284 */ 12285 if (pkgLite.recommendedInstallLocation 12286 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12287 pkgLite.recommendedInstallLocation 12288 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12289 } 12290 } 12291 } 12292 12293 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12294 int loc = pkgLite.recommendedInstallLocation; 12295 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12296 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12297 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12298 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12299 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12300 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12301 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12302 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12303 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12304 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12305 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12306 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12307 } else { 12308 // Override with defaults if needed. 12309 loc = installLocationPolicy(pkgLite); 12310 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12311 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12312 } else if (!onSd && !onInt) { 12313 // Override install location with flags 12314 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12315 // Set the flag to install on external media. 12316 installFlags |= PackageManager.INSTALL_EXTERNAL; 12317 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12318 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12319 if (DEBUG_EPHEMERAL) { 12320 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12321 } 12322 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12323 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12324 |PackageManager.INSTALL_INTERNAL); 12325 } else { 12326 // Make sure the flag for installing on external 12327 // media is unset 12328 installFlags |= PackageManager.INSTALL_INTERNAL; 12329 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12330 } 12331 } 12332 } 12333 } 12334 12335 final InstallArgs args = createInstallArgs(this); 12336 mArgs = args; 12337 12338 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12339 // TODO: http://b/22976637 12340 // Apps installed for "all" users use the device owner to verify the app 12341 UserHandle verifierUser = getUser(); 12342 if (verifierUser == UserHandle.ALL) { 12343 verifierUser = UserHandle.SYSTEM; 12344 } 12345 12346 /* 12347 * Determine if we have any installed package verifiers. If we 12348 * do, then we'll defer to them to verify the packages. 12349 */ 12350 final int requiredUid = mRequiredVerifierPackage == null ? -1 12351 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12352 verifierUser.getIdentifier()); 12353 if (!origin.existing && requiredUid != -1 12354 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12355 final Intent verification = new Intent( 12356 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12357 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12358 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12359 PACKAGE_MIME_TYPE); 12360 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12361 12362 // Query all live verifiers based on current user state 12363 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12364 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12365 12366 if (DEBUG_VERIFY) { 12367 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12368 + verification.toString() + " with " + pkgLite.verifiers.length 12369 + " optional verifiers"); 12370 } 12371 12372 final int verificationId = mPendingVerificationToken++; 12373 12374 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12375 12376 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12377 installerPackageName); 12378 12379 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12380 installFlags); 12381 12382 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12383 pkgLite.packageName); 12384 12385 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12386 pkgLite.versionCode); 12387 12388 if (verificationInfo != null) { 12389 if (verificationInfo.originatingUri != null) { 12390 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12391 verificationInfo.originatingUri); 12392 } 12393 if (verificationInfo.referrer != null) { 12394 verification.putExtra(Intent.EXTRA_REFERRER, 12395 verificationInfo.referrer); 12396 } 12397 if (verificationInfo.originatingUid >= 0) { 12398 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12399 verificationInfo.originatingUid); 12400 } 12401 if (verificationInfo.installerUid >= 0) { 12402 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12403 verificationInfo.installerUid); 12404 } 12405 } 12406 12407 final PackageVerificationState verificationState = new PackageVerificationState( 12408 requiredUid, args); 12409 12410 mPendingVerification.append(verificationId, verificationState); 12411 12412 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12413 receivers, verificationState); 12414 12415 /* 12416 * If any sufficient verifiers were listed in the package 12417 * manifest, attempt to ask them. 12418 */ 12419 if (sufficientVerifiers != null) { 12420 final int N = sufficientVerifiers.size(); 12421 if (N == 0) { 12422 Slog.i(TAG, "Additional verifiers required, but none installed."); 12423 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12424 } else { 12425 for (int i = 0; i < N; i++) { 12426 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12427 12428 final Intent sufficientIntent = new Intent(verification); 12429 sufficientIntent.setComponent(verifierComponent); 12430 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12431 } 12432 } 12433 } 12434 12435 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12436 mRequiredVerifierPackage, receivers); 12437 if (ret == PackageManager.INSTALL_SUCCEEDED 12438 && mRequiredVerifierPackage != null) { 12439 Trace.asyncTraceBegin( 12440 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12441 /* 12442 * Send the intent to the required verification agent, 12443 * but only start the verification timeout after the 12444 * target BroadcastReceivers have run. 12445 */ 12446 verification.setComponent(requiredVerifierComponent); 12447 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12448 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12449 new BroadcastReceiver() { 12450 @Override 12451 public void onReceive(Context context, Intent intent) { 12452 final Message msg = mHandler 12453 .obtainMessage(CHECK_PENDING_VERIFICATION); 12454 msg.arg1 = verificationId; 12455 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12456 } 12457 }, null, 0, null, null); 12458 12459 /* 12460 * We don't want the copy to proceed until verification 12461 * succeeds, so null out this field. 12462 */ 12463 mArgs = null; 12464 } 12465 } else { 12466 /* 12467 * No package verification is enabled, so immediately start 12468 * the remote call to initiate copy using temporary file. 12469 */ 12470 ret = args.copyApk(mContainerService, true); 12471 } 12472 } 12473 12474 mRet = ret; 12475 } 12476 12477 @Override 12478 void handleReturnCode() { 12479 // If mArgs is null, then MCS couldn't be reached. When it 12480 // reconnects, it will try again to install. At that point, this 12481 // will succeed. 12482 if (mArgs != null) { 12483 processPendingInstall(mArgs, mRet); 12484 } 12485 } 12486 12487 @Override 12488 void handleServiceError() { 12489 mArgs = createInstallArgs(this); 12490 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12491 } 12492 12493 public boolean isForwardLocked() { 12494 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12495 } 12496 } 12497 12498 /** 12499 * Used during creation of InstallArgs 12500 * 12501 * @param installFlags package installation flags 12502 * @return true if should be installed on external storage 12503 */ 12504 private static boolean installOnExternalAsec(int installFlags) { 12505 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12506 return false; 12507 } 12508 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12509 return true; 12510 } 12511 return false; 12512 } 12513 12514 /** 12515 * Used during creation of InstallArgs 12516 * 12517 * @param installFlags package installation flags 12518 * @return true if should be installed as forward locked 12519 */ 12520 private static boolean installForwardLocked(int installFlags) { 12521 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12522 } 12523 12524 private InstallArgs createInstallArgs(InstallParams params) { 12525 if (params.move != null) { 12526 return new MoveInstallArgs(params); 12527 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12528 return new AsecInstallArgs(params); 12529 } else { 12530 return new FileInstallArgs(params); 12531 } 12532 } 12533 12534 /** 12535 * Create args that describe an existing installed package. Typically used 12536 * when cleaning up old installs, or used as a move source. 12537 */ 12538 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12539 String resourcePath, String[] instructionSets) { 12540 final boolean isInAsec; 12541 if (installOnExternalAsec(installFlags)) { 12542 /* Apps on SD card are always in ASEC containers. */ 12543 isInAsec = true; 12544 } else if (installForwardLocked(installFlags) 12545 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12546 /* 12547 * Forward-locked apps are only in ASEC containers if they're the 12548 * new style 12549 */ 12550 isInAsec = true; 12551 } else { 12552 isInAsec = false; 12553 } 12554 12555 if (isInAsec) { 12556 return new AsecInstallArgs(codePath, instructionSets, 12557 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12558 } else { 12559 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12560 } 12561 } 12562 12563 static abstract class InstallArgs { 12564 /** @see InstallParams#origin */ 12565 final OriginInfo origin; 12566 /** @see InstallParams#move */ 12567 final MoveInfo move; 12568 12569 final IPackageInstallObserver2 observer; 12570 // Always refers to PackageManager flags only 12571 final int installFlags; 12572 final String installerPackageName; 12573 final String volumeUuid; 12574 final UserHandle user; 12575 final String abiOverride; 12576 final String[] installGrantPermissions; 12577 /** If non-null, drop an async trace when the install completes */ 12578 final String traceMethod; 12579 final int traceCookie; 12580 12581 // The list of instruction sets supported by this app. This is currently 12582 // only used during the rmdex() phase to clean up resources. We can get rid of this 12583 // if we move dex files under the common app path. 12584 /* nullable */ String[] instructionSets; 12585 12586 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12587 int installFlags, String installerPackageName, String volumeUuid, 12588 UserHandle user, String[] instructionSets, 12589 String abiOverride, String[] installGrantPermissions, 12590 String traceMethod, int traceCookie) { 12591 this.origin = origin; 12592 this.move = move; 12593 this.installFlags = installFlags; 12594 this.observer = observer; 12595 this.installerPackageName = installerPackageName; 12596 this.volumeUuid = volumeUuid; 12597 this.user = user; 12598 this.instructionSets = instructionSets; 12599 this.abiOverride = abiOverride; 12600 this.installGrantPermissions = installGrantPermissions; 12601 this.traceMethod = traceMethod; 12602 this.traceCookie = traceCookie; 12603 } 12604 12605 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12606 abstract int doPreInstall(int status); 12607 12608 /** 12609 * Rename package into final resting place. All paths on the given 12610 * scanned package should be updated to reflect the rename. 12611 */ 12612 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12613 abstract int doPostInstall(int status, int uid); 12614 12615 /** @see PackageSettingBase#codePathString */ 12616 abstract String getCodePath(); 12617 /** @see PackageSettingBase#resourcePathString */ 12618 abstract String getResourcePath(); 12619 12620 // Need installer lock especially for dex file removal. 12621 abstract void cleanUpResourcesLI(); 12622 abstract boolean doPostDeleteLI(boolean delete); 12623 12624 /** 12625 * Called before the source arguments are copied. This is used mostly 12626 * for MoveParams when it needs to read the source file to put it in the 12627 * destination. 12628 */ 12629 int doPreCopy() { 12630 return PackageManager.INSTALL_SUCCEEDED; 12631 } 12632 12633 /** 12634 * Called after the source arguments are copied. This is used mostly for 12635 * MoveParams when it needs to read the source file to put it in the 12636 * destination. 12637 */ 12638 int doPostCopy(int uid) { 12639 return PackageManager.INSTALL_SUCCEEDED; 12640 } 12641 12642 protected boolean isFwdLocked() { 12643 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12644 } 12645 12646 protected boolean isExternalAsec() { 12647 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12648 } 12649 12650 protected boolean isEphemeral() { 12651 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12652 } 12653 12654 UserHandle getUser() { 12655 return user; 12656 } 12657 } 12658 12659 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12660 if (!allCodePaths.isEmpty()) { 12661 if (instructionSets == null) { 12662 throw new IllegalStateException("instructionSet == null"); 12663 } 12664 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12665 for (String codePath : allCodePaths) { 12666 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12667 try { 12668 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12669 } catch (InstallerException ignored) { 12670 } 12671 } 12672 } 12673 } 12674 } 12675 12676 /** 12677 * Logic to handle installation of non-ASEC applications, including copying 12678 * and renaming logic. 12679 */ 12680 class FileInstallArgs extends InstallArgs { 12681 private File codeFile; 12682 private File resourceFile; 12683 12684 // Example topology: 12685 // /data/app/com.example/base.apk 12686 // /data/app/com.example/split_foo.apk 12687 // /data/app/com.example/lib/arm/libfoo.so 12688 // /data/app/com.example/lib/arm64/libfoo.so 12689 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12690 12691 /** New install */ 12692 FileInstallArgs(InstallParams params) { 12693 super(params.origin, params.move, params.observer, params.installFlags, 12694 params.installerPackageName, params.volumeUuid, 12695 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12696 params.grantedRuntimePermissions, 12697 params.traceMethod, params.traceCookie); 12698 if (isFwdLocked()) { 12699 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12700 } 12701 } 12702 12703 /** Existing install */ 12704 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12705 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12706 null, null, null, 0); 12707 this.codeFile = (codePath != null) ? new File(codePath) : null; 12708 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12709 } 12710 12711 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12712 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12713 try { 12714 return doCopyApk(imcs, temp); 12715 } finally { 12716 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12717 } 12718 } 12719 12720 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12721 if (origin.staged) { 12722 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12723 codeFile = origin.file; 12724 resourceFile = origin.file; 12725 return PackageManager.INSTALL_SUCCEEDED; 12726 } 12727 12728 try { 12729 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12730 final File tempDir = 12731 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12732 codeFile = tempDir; 12733 resourceFile = tempDir; 12734 } catch (IOException e) { 12735 Slog.w(TAG, "Failed to create copy file: " + e); 12736 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12737 } 12738 12739 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12740 @Override 12741 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12742 if (!FileUtils.isValidExtFilename(name)) { 12743 throw new IllegalArgumentException("Invalid filename: " + name); 12744 } 12745 try { 12746 final File file = new File(codeFile, name); 12747 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12748 O_RDWR | O_CREAT, 0644); 12749 Os.chmod(file.getAbsolutePath(), 0644); 12750 return new ParcelFileDescriptor(fd); 12751 } catch (ErrnoException e) { 12752 throw new RemoteException("Failed to open: " + e.getMessage()); 12753 } 12754 } 12755 }; 12756 12757 int ret = PackageManager.INSTALL_SUCCEEDED; 12758 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12759 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12760 Slog.e(TAG, "Failed to copy package"); 12761 return ret; 12762 } 12763 12764 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12765 NativeLibraryHelper.Handle handle = null; 12766 try { 12767 handle = NativeLibraryHelper.Handle.create(codeFile); 12768 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12769 abiOverride); 12770 } catch (IOException e) { 12771 Slog.e(TAG, "Copying native libraries failed", e); 12772 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12773 } finally { 12774 IoUtils.closeQuietly(handle); 12775 } 12776 12777 return ret; 12778 } 12779 12780 int doPreInstall(int status) { 12781 if (status != PackageManager.INSTALL_SUCCEEDED) { 12782 cleanUp(); 12783 } 12784 return status; 12785 } 12786 12787 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12788 if (status != PackageManager.INSTALL_SUCCEEDED) { 12789 cleanUp(); 12790 return false; 12791 } 12792 12793 final File targetDir = codeFile.getParentFile(); 12794 final File beforeCodeFile = codeFile; 12795 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12796 12797 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12798 try { 12799 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12800 } catch (ErrnoException e) { 12801 Slog.w(TAG, "Failed to rename", e); 12802 return false; 12803 } 12804 12805 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12806 Slog.w(TAG, "Failed to restorecon"); 12807 return false; 12808 } 12809 12810 // Reflect the rename internally 12811 codeFile = afterCodeFile; 12812 resourceFile = afterCodeFile; 12813 12814 // Reflect the rename in scanned details 12815 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12816 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12817 afterCodeFile, pkg.baseCodePath)); 12818 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12819 afterCodeFile, pkg.splitCodePaths)); 12820 12821 // Reflect the rename in app info 12822 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12823 pkg.setApplicationInfoCodePath(pkg.codePath); 12824 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12825 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12826 pkg.setApplicationInfoResourcePath(pkg.codePath); 12827 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12828 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12829 12830 return true; 12831 } 12832 12833 int doPostInstall(int status, int uid) { 12834 if (status != PackageManager.INSTALL_SUCCEEDED) { 12835 cleanUp(); 12836 } 12837 return status; 12838 } 12839 12840 @Override 12841 String getCodePath() { 12842 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12843 } 12844 12845 @Override 12846 String getResourcePath() { 12847 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12848 } 12849 12850 private boolean cleanUp() { 12851 if (codeFile == null || !codeFile.exists()) { 12852 return false; 12853 } 12854 12855 removeCodePathLI(codeFile); 12856 12857 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12858 resourceFile.delete(); 12859 } 12860 12861 return true; 12862 } 12863 12864 void cleanUpResourcesLI() { 12865 // Try enumerating all code paths before deleting 12866 List<String> allCodePaths = Collections.EMPTY_LIST; 12867 if (codeFile != null && codeFile.exists()) { 12868 try { 12869 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12870 allCodePaths = pkg.getAllCodePaths(); 12871 } catch (PackageParserException e) { 12872 // Ignored; we tried our best 12873 } 12874 } 12875 12876 cleanUp(); 12877 removeDexFiles(allCodePaths, instructionSets); 12878 } 12879 12880 boolean doPostDeleteLI(boolean delete) { 12881 // XXX err, shouldn't we respect the delete flag? 12882 cleanUpResourcesLI(); 12883 return true; 12884 } 12885 } 12886 12887 private boolean isAsecExternal(String cid) { 12888 final String asecPath = PackageHelper.getSdFilesystem(cid); 12889 return !asecPath.startsWith(mAsecInternalPath); 12890 } 12891 12892 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12893 PackageManagerException { 12894 if (copyRet < 0) { 12895 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12896 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12897 throw new PackageManagerException(copyRet, message); 12898 } 12899 } 12900 } 12901 12902 /** 12903 * Extract the MountService "container ID" from the full code path of an 12904 * .apk. 12905 */ 12906 static String cidFromCodePath(String fullCodePath) { 12907 int eidx = fullCodePath.lastIndexOf("/"); 12908 String subStr1 = fullCodePath.substring(0, eidx); 12909 int sidx = subStr1.lastIndexOf("/"); 12910 return subStr1.substring(sidx+1, eidx); 12911 } 12912 12913 /** 12914 * Logic to handle installation of ASEC applications, including copying and 12915 * renaming logic. 12916 */ 12917 class AsecInstallArgs extends InstallArgs { 12918 static final String RES_FILE_NAME = "pkg.apk"; 12919 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12920 12921 String cid; 12922 String packagePath; 12923 String resourcePath; 12924 12925 /** New install */ 12926 AsecInstallArgs(InstallParams params) { 12927 super(params.origin, params.move, params.observer, params.installFlags, 12928 params.installerPackageName, params.volumeUuid, 12929 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12930 params.grantedRuntimePermissions, 12931 params.traceMethod, params.traceCookie); 12932 } 12933 12934 /** Existing install */ 12935 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12936 boolean isExternal, boolean isForwardLocked) { 12937 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12938 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12939 instructionSets, null, null, null, 0); 12940 // Hackily pretend we're still looking at a full code path 12941 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12942 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12943 } 12944 12945 // Extract cid from fullCodePath 12946 int eidx = fullCodePath.lastIndexOf("/"); 12947 String subStr1 = fullCodePath.substring(0, eidx); 12948 int sidx = subStr1.lastIndexOf("/"); 12949 cid = subStr1.substring(sidx+1, eidx); 12950 setMountPath(subStr1); 12951 } 12952 12953 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12954 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12955 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12956 instructionSets, null, null, null, 0); 12957 this.cid = cid; 12958 setMountPath(PackageHelper.getSdDir(cid)); 12959 } 12960 12961 void createCopyFile() { 12962 cid = mInstallerService.allocateExternalStageCidLegacy(); 12963 } 12964 12965 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12966 if (origin.staged && origin.cid != null) { 12967 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12968 cid = origin.cid; 12969 setMountPath(PackageHelper.getSdDir(cid)); 12970 return PackageManager.INSTALL_SUCCEEDED; 12971 } 12972 12973 if (temp) { 12974 createCopyFile(); 12975 } else { 12976 /* 12977 * Pre-emptively destroy the container since it's destroyed if 12978 * copying fails due to it existing anyway. 12979 */ 12980 PackageHelper.destroySdDir(cid); 12981 } 12982 12983 final String newMountPath = imcs.copyPackageToContainer( 12984 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12985 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12986 12987 if (newMountPath != null) { 12988 setMountPath(newMountPath); 12989 return PackageManager.INSTALL_SUCCEEDED; 12990 } else { 12991 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12992 } 12993 } 12994 12995 @Override 12996 String getCodePath() { 12997 return packagePath; 12998 } 12999 13000 @Override 13001 String getResourcePath() { 13002 return resourcePath; 13003 } 13004 13005 int doPreInstall(int status) { 13006 if (status != PackageManager.INSTALL_SUCCEEDED) { 13007 // Destroy container 13008 PackageHelper.destroySdDir(cid); 13009 } else { 13010 boolean mounted = PackageHelper.isContainerMounted(cid); 13011 if (!mounted) { 13012 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13013 Process.SYSTEM_UID); 13014 if (newMountPath != null) { 13015 setMountPath(newMountPath); 13016 } else { 13017 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13018 } 13019 } 13020 } 13021 return status; 13022 } 13023 13024 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13025 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13026 String newMountPath = null; 13027 if (PackageHelper.isContainerMounted(cid)) { 13028 // Unmount the container 13029 if (!PackageHelper.unMountSdDir(cid)) { 13030 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13031 return false; 13032 } 13033 } 13034 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13035 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13036 " which might be stale. Will try to clean up."); 13037 // Clean up the stale container and proceed to recreate. 13038 if (!PackageHelper.destroySdDir(newCacheId)) { 13039 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13040 return false; 13041 } 13042 // Successfully cleaned up stale container. Try to rename again. 13043 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13044 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13045 + " inspite of cleaning it up."); 13046 return false; 13047 } 13048 } 13049 if (!PackageHelper.isContainerMounted(newCacheId)) { 13050 Slog.w(TAG, "Mounting container " + newCacheId); 13051 newMountPath = PackageHelper.mountSdDir(newCacheId, 13052 getEncryptKey(), Process.SYSTEM_UID); 13053 } else { 13054 newMountPath = PackageHelper.getSdDir(newCacheId); 13055 } 13056 if (newMountPath == null) { 13057 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13058 return false; 13059 } 13060 Log.i(TAG, "Succesfully renamed " + cid + 13061 " to " + newCacheId + 13062 " at new path: " + newMountPath); 13063 cid = newCacheId; 13064 13065 final File beforeCodeFile = new File(packagePath); 13066 setMountPath(newMountPath); 13067 final File afterCodeFile = new File(packagePath); 13068 13069 // Reflect the rename in scanned details 13070 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13071 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13072 afterCodeFile, pkg.baseCodePath)); 13073 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13074 afterCodeFile, pkg.splitCodePaths)); 13075 13076 // Reflect the rename in app info 13077 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13078 pkg.setApplicationInfoCodePath(pkg.codePath); 13079 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13080 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13081 pkg.setApplicationInfoResourcePath(pkg.codePath); 13082 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13083 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13084 13085 return true; 13086 } 13087 13088 private void setMountPath(String mountPath) { 13089 final File mountFile = new File(mountPath); 13090 13091 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13092 if (monolithicFile.exists()) { 13093 packagePath = monolithicFile.getAbsolutePath(); 13094 if (isFwdLocked()) { 13095 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13096 } else { 13097 resourcePath = packagePath; 13098 } 13099 } else { 13100 packagePath = mountFile.getAbsolutePath(); 13101 resourcePath = packagePath; 13102 } 13103 } 13104 13105 int doPostInstall(int status, int uid) { 13106 if (status != PackageManager.INSTALL_SUCCEEDED) { 13107 cleanUp(); 13108 } else { 13109 final int groupOwner; 13110 final String protectedFile; 13111 if (isFwdLocked()) { 13112 groupOwner = UserHandle.getSharedAppGid(uid); 13113 protectedFile = RES_FILE_NAME; 13114 } else { 13115 groupOwner = -1; 13116 protectedFile = null; 13117 } 13118 13119 if (uid < Process.FIRST_APPLICATION_UID 13120 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13121 Slog.e(TAG, "Failed to finalize " + cid); 13122 PackageHelper.destroySdDir(cid); 13123 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13124 } 13125 13126 boolean mounted = PackageHelper.isContainerMounted(cid); 13127 if (!mounted) { 13128 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13129 } 13130 } 13131 return status; 13132 } 13133 13134 private void cleanUp() { 13135 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13136 13137 // Destroy secure container 13138 PackageHelper.destroySdDir(cid); 13139 } 13140 13141 private List<String> getAllCodePaths() { 13142 final File codeFile = new File(getCodePath()); 13143 if (codeFile != null && codeFile.exists()) { 13144 try { 13145 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13146 return pkg.getAllCodePaths(); 13147 } catch (PackageParserException e) { 13148 // Ignored; we tried our best 13149 } 13150 } 13151 return Collections.EMPTY_LIST; 13152 } 13153 13154 void cleanUpResourcesLI() { 13155 // Enumerate all code paths before deleting 13156 cleanUpResourcesLI(getAllCodePaths()); 13157 } 13158 13159 private void cleanUpResourcesLI(List<String> allCodePaths) { 13160 cleanUp(); 13161 removeDexFiles(allCodePaths, instructionSets); 13162 } 13163 13164 String getPackageName() { 13165 return getAsecPackageName(cid); 13166 } 13167 13168 boolean doPostDeleteLI(boolean delete) { 13169 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13170 final List<String> allCodePaths = getAllCodePaths(); 13171 boolean mounted = PackageHelper.isContainerMounted(cid); 13172 if (mounted) { 13173 // Unmount first 13174 if (PackageHelper.unMountSdDir(cid)) { 13175 mounted = false; 13176 } 13177 } 13178 if (!mounted && delete) { 13179 cleanUpResourcesLI(allCodePaths); 13180 } 13181 return !mounted; 13182 } 13183 13184 @Override 13185 int doPreCopy() { 13186 if (isFwdLocked()) { 13187 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13188 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13189 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13190 } 13191 } 13192 13193 return PackageManager.INSTALL_SUCCEEDED; 13194 } 13195 13196 @Override 13197 int doPostCopy(int uid) { 13198 if (isFwdLocked()) { 13199 if (uid < Process.FIRST_APPLICATION_UID 13200 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13201 RES_FILE_NAME)) { 13202 Slog.e(TAG, "Failed to finalize " + cid); 13203 PackageHelper.destroySdDir(cid); 13204 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13205 } 13206 } 13207 13208 return PackageManager.INSTALL_SUCCEEDED; 13209 } 13210 } 13211 13212 /** 13213 * Logic to handle movement of existing installed applications. 13214 */ 13215 class MoveInstallArgs extends InstallArgs { 13216 private File codeFile; 13217 private File resourceFile; 13218 13219 /** New install */ 13220 MoveInstallArgs(InstallParams params) { 13221 super(params.origin, params.move, params.observer, params.installFlags, 13222 params.installerPackageName, params.volumeUuid, 13223 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13224 params.grantedRuntimePermissions, 13225 params.traceMethod, params.traceCookie); 13226 } 13227 13228 int copyApk(IMediaContainerService imcs, boolean temp) { 13229 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13230 + move.fromUuid + " to " + move.toUuid); 13231 synchronized (mInstaller) { 13232 try { 13233 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13234 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13235 } catch (InstallerException e) { 13236 Slog.w(TAG, "Failed to move app", e); 13237 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13238 } 13239 } 13240 13241 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13242 resourceFile = codeFile; 13243 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13244 13245 return PackageManager.INSTALL_SUCCEEDED; 13246 } 13247 13248 int doPreInstall(int status) { 13249 if (status != PackageManager.INSTALL_SUCCEEDED) { 13250 cleanUp(move.toUuid); 13251 } 13252 return status; 13253 } 13254 13255 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13256 if (status != PackageManager.INSTALL_SUCCEEDED) { 13257 cleanUp(move.toUuid); 13258 return false; 13259 } 13260 13261 // Reflect the move in app info 13262 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13263 pkg.setApplicationInfoCodePath(pkg.codePath); 13264 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13265 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13266 pkg.setApplicationInfoResourcePath(pkg.codePath); 13267 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13268 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13269 13270 return true; 13271 } 13272 13273 int doPostInstall(int status, int uid) { 13274 if (status == PackageManager.INSTALL_SUCCEEDED) { 13275 cleanUp(move.fromUuid); 13276 } else { 13277 cleanUp(move.toUuid); 13278 } 13279 return status; 13280 } 13281 13282 @Override 13283 String getCodePath() { 13284 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13285 } 13286 13287 @Override 13288 String getResourcePath() { 13289 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13290 } 13291 13292 private boolean cleanUp(String volumeUuid) { 13293 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13294 move.dataAppName); 13295 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13296 synchronized (mInstallLock) { 13297 // Clean up both app data and code 13298 removeDataDirsLI(volumeUuid, move.packageName); 13299 removeCodePathLI(codeFile); 13300 } 13301 return true; 13302 } 13303 13304 void cleanUpResourcesLI() { 13305 throw new UnsupportedOperationException(); 13306 } 13307 13308 boolean doPostDeleteLI(boolean delete) { 13309 throw new UnsupportedOperationException(); 13310 } 13311 } 13312 13313 static String getAsecPackageName(String packageCid) { 13314 int idx = packageCid.lastIndexOf("-"); 13315 if (idx == -1) { 13316 return packageCid; 13317 } 13318 return packageCid.substring(0, idx); 13319 } 13320 13321 // Utility method used to create code paths based on package name and available index. 13322 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13323 String idxStr = ""; 13324 int idx = 1; 13325 // Fall back to default value of idx=1 if prefix is not 13326 // part of oldCodePath 13327 if (oldCodePath != null) { 13328 String subStr = oldCodePath; 13329 // Drop the suffix right away 13330 if (suffix != null && subStr.endsWith(suffix)) { 13331 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13332 } 13333 // If oldCodePath already contains prefix find out the 13334 // ending index to either increment or decrement. 13335 int sidx = subStr.lastIndexOf(prefix); 13336 if (sidx != -1) { 13337 subStr = subStr.substring(sidx + prefix.length()); 13338 if (subStr != null) { 13339 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13340 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13341 } 13342 try { 13343 idx = Integer.parseInt(subStr); 13344 if (idx <= 1) { 13345 idx++; 13346 } else { 13347 idx--; 13348 } 13349 } catch(NumberFormatException e) { 13350 } 13351 } 13352 } 13353 } 13354 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13355 return prefix + idxStr; 13356 } 13357 13358 private File getNextCodePath(File targetDir, String packageName) { 13359 int suffix = 1; 13360 File result; 13361 do { 13362 result = new File(targetDir, packageName + "-" + suffix); 13363 suffix++; 13364 } while (result.exists()); 13365 return result; 13366 } 13367 13368 // Utility method that returns the relative package path with respect 13369 // to the installation directory. Like say for /data/data/com.test-1.apk 13370 // string com.test-1 is returned. 13371 static String deriveCodePathName(String codePath) { 13372 if (codePath == null) { 13373 return null; 13374 } 13375 final File codeFile = new File(codePath); 13376 final String name = codeFile.getName(); 13377 if (codeFile.isDirectory()) { 13378 return name; 13379 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13380 final int lastDot = name.lastIndexOf('.'); 13381 return name.substring(0, lastDot); 13382 } else { 13383 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13384 return null; 13385 } 13386 } 13387 13388 static class PackageInstalledInfo { 13389 String name; 13390 int uid; 13391 // The set of users that originally had this package installed. 13392 int[] origUsers; 13393 // The set of users that now have this package installed. 13394 int[] newUsers; 13395 PackageParser.Package pkg; 13396 int returnCode; 13397 String returnMsg; 13398 PackageRemovedInfo removedInfo; 13399 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13400 13401 public void setError(int code, String msg) { 13402 setReturnCode(code); 13403 setReturnMessage(msg); 13404 Slog.w(TAG, msg); 13405 } 13406 13407 public void setError(String msg, PackageParserException e) { 13408 setReturnCode(e.error); 13409 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13410 Slog.w(TAG, msg, e); 13411 } 13412 13413 public void setError(String msg, PackageManagerException e) { 13414 returnCode = e.error; 13415 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13416 Slog.w(TAG, msg, e); 13417 } 13418 13419 public void setReturnCode(int returnCode) { 13420 this.returnCode = returnCode; 13421 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13422 for (int i = 0; i < childCount; i++) { 13423 addedChildPackages.valueAt(i).returnCode = returnCode; 13424 } 13425 } 13426 13427 private void setReturnMessage(String returnMsg) { 13428 this.returnMsg = returnMsg; 13429 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13430 for (int i = 0; i < childCount; i++) { 13431 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13432 } 13433 } 13434 13435 // In some error cases we want to convey more info back to the observer 13436 String origPackage; 13437 String origPermission; 13438 } 13439 13440 /* 13441 * Install a non-existing package. 13442 */ 13443 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13444 UserHandle user, String installerPackageName, String volumeUuid, 13445 PackageInstalledInfo res) { 13446 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13447 13448 // Remember this for later, in case we need to rollback this install 13449 String pkgName = pkg.packageName; 13450 13451 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13452 13453 synchronized(mPackages) { 13454 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13455 // A package with the same name is already installed, though 13456 // it has been renamed to an older name. The package we 13457 // are trying to install should be installed as an update to 13458 // the existing one, but that has not been requested, so bail. 13459 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13460 + " without first uninstalling package running as " 13461 + mSettings.mRenamedPackages.get(pkgName)); 13462 return; 13463 } 13464 if (mPackages.containsKey(pkgName)) { 13465 // Don't allow installation over an existing package with the same name. 13466 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13467 + " without first uninstalling."); 13468 return; 13469 } 13470 } 13471 13472 try { 13473 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13474 System.currentTimeMillis(), user); 13475 13476 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13477 13478 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13479 prepareAppDataAfterInstall(newPackage); 13480 13481 } else { 13482 // Remove package from internal structures, but keep around any 13483 // data that might have already existed 13484 deletePackageLI(pkgName, UserHandle.ALL, false, null, 13485 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13486 } 13487 } catch (PackageManagerException e) { 13488 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13489 } 13490 13491 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13492 } 13493 13494 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13495 // Can't rotate keys during boot or if sharedUser. 13496 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13497 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13498 return false; 13499 } 13500 // app is using upgradeKeySets; make sure all are valid 13501 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13502 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13503 for (int i = 0; i < upgradeKeySets.length; i++) { 13504 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13505 Slog.wtf(TAG, "Package " 13506 + (oldPs.name != null ? oldPs.name : "<null>") 13507 + " contains upgrade-key-set reference to unknown key-set: " 13508 + upgradeKeySets[i] 13509 + " reverting to signatures check."); 13510 return false; 13511 } 13512 } 13513 return true; 13514 } 13515 13516 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13517 // Upgrade keysets are being used. Determine if new package has a superset of the 13518 // required keys. 13519 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13520 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13521 for (int i = 0; i < upgradeKeySets.length; i++) { 13522 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13523 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13524 return true; 13525 } 13526 } 13527 return false; 13528 } 13529 13530 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13531 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13532 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13533 13534 final PackageParser.Package oldPackage; 13535 final String pkgName = pkg.packageName; 13536 final int[] allUsers; 13537 final boolean weFroze; 13538 13539 // First find the old package info and check signatures 13540 synchronized(mPackages) { 13541 oldPackage = mPackages.get(pkgName); 13542 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13543 if (isEphemeral && !oldIsEphemeral) { 13544 // can't downgrade from full to ephemeral 13545 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13546 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13547 return; 13548 } 13549 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13550 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13551 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13552 if (!checkUpgradeKeySetLP(ps, pkg)) { 13553 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13554 "New package not signed by keys specified by upgrade-keysets: " 13555 + pkgName); 13556 return; 13557 } 13558 } else { 13559 // default to original signature matching 13560 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13561 != PackageManager.SIGNATURE_MATCH) { 13562 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13563 "New package has a different signature: " + pkgName); 13564 return; 13565 } 13566 } 13567 13568 // In case of rollback, remember per-user/profile install state 13569 allUsers = sUserManager.getUserIds(); 13570 13571 // Mark the app as frozen to prevent launching during the upgrade 13572 // process, and then kill all running instances 13573 if (!ps.frozen) { 13574 ps.frozen = true; 13575 weFroze = true; 13576 } else { 13577 weFroze = false; 13578 } 13579 } 13580 13581 try { 13582 replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers, 13583 installerPackageName, res); 13584 } finally { 13585 // Regardless of success or failure of upgrade steps above, always 13586 // unfreeze the package if we froze it 13587 if (weFroze) { 13588 unfreezePackage(pkgName); 13589 } 13590 } 13591 } 13592 13593 private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage, 13594 int parseFlags, int scanFlags, UserHandle user, int[] allUsers, 13595 String installerPackageName, PackageInstalledInfo res) { 13596 // Update what is removed 13597 res.removedInfo = new PackageRemovedInfo(); 13598 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13599 res.removedInfo.removedPackage = oldPackage.packageName; 13600 res.removedInfo.isUpdate = true; 13601 final int childCount = (oldPackage.childPackages != null) 13602 ? oldPackage.childPackages.size() : 0; 13603 for (int i = 0; i < childCount; i++) { 13604 boolean childPackageUpdated = false; 13605 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13606 if (res.addedChildPackages != null) { 13607 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13608 if (childRes != null) { 13609 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13610 childRes.removedInfo.removedPackage = childPkg.packageName; 13611 childRes.removedInfo.isUpdate = true; 13612 childPackageUpdated = true; 13613 } 13614 } 13615 if (!childPackageUpdated) { 13616 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13617 childRemovedRes.removedPackage = childPkg.packageName; 13618 childRemovedRes.isUpdate = false; 13619 childRemovedRes.dataRemoved = true; 13620 synchronized (mPackages) { 13621 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13622 if (childPs != null) { 13623 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13624 } 13625 } 13626 if (res.removedInfo.removedChildPackages == null) { 13627 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13628 } 13629 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13630 } 13631 } 13632 13633 boolean sysPkg = (isSystemApp(oldPackage)); 13634 if (sysPkg) { 13635 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13636 user, allUsers, installerPackageName, res); 13637 } else { 13638 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13639 user, allUsers, installerPackageName, res); 13640 } 13641 } 13642 13643 public List<String> getPreviousCodePaths(String packageName) { 13644 final PackageSetting ps = mSettings.mPackages.get(packageName); 13645 final List<String> result = new ArrayList<String>(); 13646 if (ps != null && ps.oldCodePaths != null) { 13647 result.addAll(ps.oldCodePaths); 13648 } 13649 return result; 13650 } 13651 13652 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13653 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13654 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13655 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13656 + deletedPackage); 13657 13658 String pkgName = deletedPackage.packageName; 13659 boolean deletedPkg = true; 13660 boolean addedPkg = false; 13661 boolean updatedSettings = false; 13662 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13663 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13664 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13665 13666 final long origUpdateTime = (pkg.mExtras != null) 13667 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13668 13669 // First delete the existing package while retaining the data directory 13670 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13671 res.removedInfo, true, pkg)) { 13672 // If the existing package wasn't successfully deleted 13673 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13674 deletedPkg = false; 13675 } else { 13676 // Successfully deleted the old package; proceed with replace. 13677 13678 // If deleted package lived in a container, give users a chance to 13679 // relinquish resources before killing. 13680 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13681 if (DEBUG_INSTALL) { 13682 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13683 } 13684 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13685 final ArrayList<String> pkgList = new ArrayList<String>(1); 13686 pkgList.add(deletedPackage.applicationInfo.packageName); 13687 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13688 } 13689 13690 deleteCodeCacheDirsLI(pkg); 13691 deleteProfilesLI(pkg, /*destroy*/ false); 13692 13693 try { 13694 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13695 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13696 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13697 13698 // Update the in-memory copy of the previous code paths. 13699 PackageSetting ps = mSettings.mPackages.get(pkgName); 13700 if (!killApp) { 13701 if (ps.oldCodePaths == null) { 13702 ps.oldCodePaths = new ArraySet<>(); 13703 } 13704 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13705 if (deletedPackage.splitCodePaths != null) { 13706 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13707 } 13708 } else { 13709 ps.oldCodePaths = null; 13710 } 13711 if (ps.childPackageNames != null) { 13712 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13713 final String childPkgName = ps.childPackageNames.get(i); 13714 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13715 childPs.oldCodePaths = ps.oldCodePaths; 13716 } 13717 } 13718 prepareAppDataAfterInstall(newPackage); 13719 addedPkg = true; 13720 } catch (PackageManagerException e) { 13721 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13722 } 13723 } 13724 13725 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13726 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13727 13728 // Revert all internal state mutations and added folders for the failed install 13729 if (addedPkg) { 13730 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13731 res.removedInfo, true, null); 13732 } 13733 13734 // Restore the old package 13735 if (deletedPkg) { 13736 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13737 File restoreFile = new File(deletedPackage.codePath); 13738 // Parse old package 13739 boolean oldExternal = isExternal(deletedPackage); 13740 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13741 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13742 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13743 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13744 try { 13745 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13746 null); 13747 } catch (PackageManagerException e) { 13748 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13749 + e.getMessage()); 13750 return; 13751 } 13752 13753 synchronized (mPackages) { 13754 // Ensure the installer package name up to date 13755 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13756 13757 // Update permissions for restored package 13758 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13759 13760 mSettings.writeLPr(); 13761 } 13762 13763 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13764 } 13765 } else { 13766 synchronized (mPackages) { 13767 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13768 if (ps != null) { 13769 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13770 if (res.removedInfo.removedChildPackages != null) { 13771 final int childCount = res.removedInfo.removedChildPackages.size(); 13772 // Iterate in reverse as we may modify the collection 13773 for (int i = childCount - 1; i >= 0; i--) { 13774 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13775 if (res.addedChildPackages.containsKey(childPackageName)) { 13776 res.removedInfo.removedChildPackages.removeAt(i); 13777 } else { 13778 PackageRemovedInfo childInfo = res.removedInfo 13779 .removedChildPackages.valueAt(i); 13780 childInfo.removedForAllUsers = mPackages.get( 13781 childInfo.removedPackage) == null; 13782 } 13783 } 13784 } 13785 } 13786 } 13787 } 13788 } 13789 13790 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13791 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13792 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13793 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13794 + ", old=" + deletedPackage); 13795 13796 final boolean disabledSystem; 13797 13798 // Set the system/privileged flags as needed 13799 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13800 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13801 != 0) { 13802 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13803 } 13804 13805 // Kill package processes including services, providers, etc. 13806 killPackage(deletedPackage, "replace sys pkg"); 13807 13808 // Remove existing system package 13809 removePackageLI(deletedPackage, true); 13810 13811 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13812 if (!disabledSystem) { 13813 // We didn't need to disable the .apk as a current system package, 13814 // which means we are replacing another update that is already 13815 // installed. We need to make sure to delete the older one's .apk. 13816 res.removedInfo.args = createInstallArgsForExisting(0, 13817 deletedPackage.applicationInfo.getCodePath(), 13818 deletedPackage.applicationInfo.getResourcePath(), 13819 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13820 } else { 13821 res.removedInfo.args = null; 13822 } 13823 13824 // Successfully disabled the old package. Now proceed with re-installation 13825 deleteCodeCacheDirsLI(pkg); 13826 deleteProfilesLI(pkg, /*destroy*/ false); 13827 13828 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13829 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13830 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13831 13832 PackageParser.Package newPackage = null; 13833 try { 13834 // Add the package to the internal data structures 13835 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13836 13837 // Set the update and install times 13838 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13839 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13840 System.currentTimeMillis()); 13841 13842 // Check for shared user id changes 13843 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13844 deletedPackage, newPackage); 13845 if (invalidPackageName != null) { 13846 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13847 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13848 + " to " + invalidPackageName); 13849 } 13850 13851 // Update the package dynamic state if succeeded 13852 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13853 // Now that the install succeeded make sure we remove data 13854 // directories for any child package the update removed. 13855 final int deletedChildCount = (deletedPackage.childPackages != null) 13856 ? deletedPackage.childPackages.size() : 0; 13857 final int newChildCount = (newPackage.childPackages != null) 13858 ? newPackage.childPackages.size() : 0; 13859 for (int i = 0; i < deletedChildCount; i++) { 13860 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13861 boolean childPackageDeleted = true; 13862 for (int j = 0; j < newChildCount; j++) { 13863 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13864 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13865 childPackageDeleted = false; 13866 break; 13867 } 13868 } 13869 if (childPackageDeleted) { 13870 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13871 deletedChildPkg.packageName); 13872 if (ps != null && res.removedInfo.removedChildPackages != null) { 13873 PackageRemovedInfo removedChildRes = res.removedInfo 13874 .removedChildPackages.get(deletedChildPkg.packageName); 13875 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13876 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13877 } 13878 } 13879 } 13880 13881 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13882 prepareAppDataAfterInstall(newPackage); 13883 } 13884 } catch (PackageManagerException e) { 13885 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13886 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13887 } 13888 13889 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13890 // Re installation failed. Restore old information 13891 // Remove new pkg information 13892 if (newPackage != null) { 13893 removeInstalledPackageLI(newPackage, true); 13894 } 13895 // Add back the old system package 13896 try { 13897 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13898 } catch (PackageManagerException e) { 13899 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13900 } 13901 13902 synchronized (mPackages) { 13903 if (disabledSystem) { 13904 enableSystemPackageLPw(deletedPackage); 13905 } 13906 13907 // Ensure the installer package name up to date 13908 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13909 13910 // Update permissions for restored package 13911 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13912 13913 mSettings.writeLPr(); 13914 } 13915 13916 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13917 + " after failed upgrade"); 13918 } 13919 } 13920 13921 /** 13922 * Checks whether the parent or any of the child packages have a change shared 13923 * user. For a package to be a valid update the shred users of the parent and 13924 * the children should match. We may later support changing child shared users. 13925 * @param oldPkg The updated package. 13926 * @param newPkg The update package. 13927 * @return The shared user that change between the versions. 13928 */ 13929 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13930 PackageParser.Package newPkg) { 13931 // Check parent shared user 13932 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13933 return newPkg.packageName; 13934 } 13935 // Check child shared users 13936 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13937 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13938 for (int i = 0; i < newChildCount; i++) { 13939 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13940 // If this child was present, did it have the same shared user? 13941 for (int j = 0; j < oldChildCount; j++) { 13942 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13943 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13944 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13945 return newChildPkg.packageName; 13946 } 13947 } 13948 } 13949 return null; 13950 } 13951 13952 private void removeNativeBinariesLI(PackageSetting ps) { 13953 // Remove the lib path for the parent package 13954 if (ps != null) { 13955 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13956 // Remove the lib path for the child packages 13957 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13958 for (int i = 0; i < childCount; i++) { 13959 PackageSetting childPs = null; 13960 synchronized (mPackages) { 13961 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13962 } 13963 if (childPs != null) { 13964 NativeLibraryHelper.removeNativeBinariesLI(childPs 13965 .legacyNativeLibraryPathString); 13966 } 13967 } 13968 } 13969 } 13970 13971 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13972 // Enable the parent package 13973 mSettings.enableSystemPackageLPw(pkg.packageName); 13974 // Enable the child packages 13975 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13976 for (int i = 0; i < childCount; i++) { 13977 PackageParser.Package childPkg = pkg.childPackages.get(i); 13978 mSettings.enableSystemPackageLPw(childPkg.packageName); 13979 } 13980 } 13981 13982 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13983 PackageParser.Package newPkg) { 13984 // Disable the parent package (parent always replaced) 13985 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13986 // Disable the child packages 13987 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13988 for (int i = 0; i < childCount; i++) { 13989 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13990 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13991 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13992 } 13993 return disabled; 13994 } 13995 13996 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13997 String installerPackageName) { 13998 // Enable the parent package 13999 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14000 // Enable the child packages 14001 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14002 for (int i = 0; i < childCount; i++) { 14003 PackageParser.Package childPkg = pkg.childPackages.get(i); 14004 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14005 } 14006 } 14007 14008 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14009 // Collect all used permissions in the UID 14010 ArraySet<String> usedPermissions = new ArraySet<>(); 14011 final int packageCount = su.packages.size(); 14012 for (int i = 0; i < packageCount; i++) { 14013 PackageSetting ps = su.packages.valueAt(i); 14014 if (ps.pkg == null) { 14015 continue; 14016 } 14017 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14018 for (int j = 0; j < requestedPermCount; j++) { 14019 String permission = ps.pkg.requestedPermissions.get(j); 14020 BasePermission bp = mSettings.mPermissions.get(permission); 14021 if (bp != null) { 14022 usedPermissions.add(permission); 14023 } 14024 } 14025 } 14026 14027 PermissionsState permissionsState = su.getPermissionsState(); 14028 // Prune install permissions 14029 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14030 final int installPermCount = installPermStates.size(); 14031 for (int i = installPermCount - 1; i >= 0; i--) { 14032 PermissionState permissionState = installPermStates.get(i); 14033 if (!usedPermissions.contains(permissionState.getName())) { 14034 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14035 if (bp != null) { 14036 permissionsState.revokeInstallPermission(bp); 14037 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14038 PackageManager.MASK_PERMISSION_FLAGS, 0); 14039 } 14040 } 14041 } 14042 14043 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14044 14045 // Prune runtime permissions 14046 for (int userId : allUserIds) { 14047 List<PermissionState> runtimePermStates = permissionsState 14048 .getRuntimePermissionStates(userId); 14049 final int runtimePermCount = runtimePermStates.size(); 14050 for (int i = runtimePermCount - 1; i >= 0; i--) { 14051 PermissionState permissionState = runtimePermStates.get(i); 14052 if (!usedPermissions.contains(permissionState.getName())) { 14053 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14054 if (bp != null) { 14055 permissionsState.revokeRuntimePermission(bp, userId); 14056 permissionsState.updatePermissionFlags(bp, userId, 14057 PackageManager.MASK_PERMISSION_FLAGS, 0); 14058 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14059 runtimePermissionChangedUserIds, userId); 14060 } 14061 } 14062 } 14063 } 14064 14065 return runtimePermissionChangedUserIds; 14066 } 14067 14068 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14069 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14070 // Update the parent package setting 14071 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14072 res, user); 14073 // Update the child packages setting 14074 final int childCount = (newPackage.childPackages != null) 14075 ? newPackage.childPackages.size() : 0; 14076 for (int i = 0; i < childCount; i++) { 14077 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14078 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14079 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14080 childRes.origUsers, childRes, user); 14081 } 14082 } 14083 14084 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14085 String installerPackageName, int[] allUsers, int[] installedForUsers, 14086 PackageInstalledInfo res, UserHandle user) { 14087 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14088 14089 String pkgName = newPackage.packageName; 14090 synchronized (mPackages) { 14091 //write settings. the installStatus will be incomplete at this stage. 14092 //note that the new package setting would have already been 14093 //added to mPackages. It hasn't been persisted yet. 14094 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14095 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14096 mSettings.writeLPr(); 14097 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14098 } 14099 14100 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14101 synchronized (mPackages) { 14102 updatePermissionsLPw(newPackage.packageName, newPackage, 14103 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14104 ? UPDATE_PERMISSIONS_ALL : 0)); 14105 // For system-bundled packages, we assume that installing an upgraded version 14106 // of the package implies that the user actually wants to run that new code, 14107 // so we enable the package. 14108 PackageSetting ps = mSettings.mPackages.get(pkgName); 14109 final int userId = user.getIdentifier(); 14110 if (ps != null) { 14111 if (isSystemApp(newPackage)) { 14112 if (DEBUG_INSTALL) { 14113 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14114 } 14115 // Enable system package for requested users 14116 if (res.origUsers != null) { 14117 for (int origUserId : res.origUsers) { 14118 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14119 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14120 origUserId, installerPackageName); 14121 } 14122 } 14123 } 14124 // Also convey the prior install/uninstall state 14125 if (allUsers != null && installedForUsers != null) { 14126 for (int currentUserId : allUsers) { 14127 final boolean installed = ArrayUtils.contains( 14128 installedForUsers, currentUserId); 14129 if (DEBUG_INSTALL) { 14130 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14131 } 14132 ps.setInstalled(installed, currentUserId); 14133 } 14134 // these install state changes will be persisted in the 14135 // upcoming call to mSettings.writeLPr(). 14136 } 14137 } 14138 // It's implied that when a user requests installation, they want the app to be 14139 // installed and enabled. 14140 if (userId != UserHandle.USER_ALL) { 14141 ps.setInstalled(true, userId); 14142 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14143 } 14144 } 14145 res.name = pkgName; 14146 res.uid = newPackage.applicationInfo.uid; 14147 res.pkg = newPackage; 14148 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14149 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14150 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14151 //to update install status 14152 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14153 mSettings.writeLPr(); 14154 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14155 } 14156 14157 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14158 } 14159 14160 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14161 try { 14162 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14163 installPackageLI(args, res); 14164 } finally { 14165 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14166 } 14167 } 14168 14169 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14170 final int installFlags = args.installFlags; 14171 final String installerPackageName = args.installerPackageName; 14172 final String volumeUuid = args.volumeUuid; 14173 final File tmpPackageFile = new File(args.getCodePath()); 14174 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14175 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14176 || (args.volumeUuid != null)); 14177 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14178 boolean replace = false; 14179 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14180 if (args.move != null) { 14181 // moving a complete application; perform an initial scan on the new install location 14182 scanFlags |= SCAN_INITIAL; 14183 } 14184 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14185 scanFlags |= SCAN_DONT_KILL_APP; 14186 } 14187 14188 // Result object to be returned 14189 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14190 14191 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14192 14193 // Sanity check 14194 if (ephemeral && (forwardLocked || onExternal)) { 14195 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14196 + " external=" + onExternal); 14197 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14198 return; 14199 } 14200 14201 // Retrieve PackageSettings and parse package 14202 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14203 | PackageParser.PARSE_ENFORCE_CODE 14204 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14205 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14206 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14207 PackageParser pp = new PackageParser(); 14208 pp.setSeparateProcesses(mSeparateProcesses); 14209 pp.setDisplayMetrics(mMetrics); 14210 14211 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14212 final PackageParser.Package pkg; 14213 try { 14214 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14215 } catch (PackageParserException e) { 14216 res.setError("Failed parse during installPackageLI", e); 14217 return; 14218 } finally { 14219 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14220 } 14221 14222 // If we are installing a clustered package add results for the children 14223 if (pkg.childPackages != null) { 14224 synchronized (mPackages) { 14225 final int childCount = pkg.childPackages.size(); 14226 for (int i = 0; i < childCount; i++) { 14227 PackageParser.Package childPkg = pkg.childPackages.get(i); 14228 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14229 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14230 childRes.pkg = childPkg; 14231 childRes.name = childPkg.packageName; 14232 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14233 if (childPs != null) { 14234 childRes.origUsers = childPs.queryInstalledUsers( 14235 sUserManager.getUserIds(), true); 14236 } 14237 if ((mPackages.containsKey(childPkg.packageName))) { 14238 childRes.removedInfo = new PackageRemovedInfo(); 14239 childRes.removedInfo.removedPackage = childPkg.packageName; 14240 } 14241 if (res.addedChildPackages == null) { 14242 res.addedChildPackages = new ArrayMap<>(); 14243 } 14244 res.addedChildPackages.put(childPkg.packageName, childRes); 14245 } 14246 } 14247 } 14248 14249 // If package doesn't declare API override, mark that we have an install 14250 // time CPU ABI override. 14251 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14252 pkg.cpuAbiOverride = args.abiOverride; 14253 } 14254 14255 String pkgName = res.name = pkg.packageName; 14256 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14257 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14258 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14259 return; 14260 } 14261 } 14262 14263 try { 14264 PackageParser.collectCertificates(pkg, parseFlags); 14265 } catch (PackageParserException e) { 14266 res.setError("Failed collect during installPackageLI", e); 14267 return; 14268 } 14269 14270 // Get rid of all references to package scan path via parser. 14271 pp = null; 14272 String oldCodePath = null; 14273 boolean systemApp = false; 14274 synchronized (mPackages) { 14275 // Check if installing already existing package 14276 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14277 String oldName = mSettings.mRenamedPackages.get(pkgName); 14278 if (pkg.mOriginalPackages != null 14279 && pkg.mOriginalPackages.contains(oldName) 14280 && mPackages.containsKey(oldName)) { 14281 // This package is derived from an original package, 14282 // and this device has been updating from that original 14283 // name. We must continue using the original name, so 14284 // rename the new package here. 14285 pkg.setPackageName(oldName); 14286 pkgName = pkg.packageName; 14287 replace = true; 14288 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14289 + oldName + " pkgName=" + pkgName); 14290 } else if (mPackages.containsKey(pkgName)) { 14291 // This package, under its official name, already exists 14292 // on the device; we should replace it. 14293 replace = true; 14294 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14295 } 14296 14297 // Child packages are installed through the parent package 14298 if (pkg.parentPackage != null) { 14299 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14300 "Package " + pkg.packageName + " is child of package " 14301 + pkg.parentPackage.parentPackage + ". Child packages " 14302 + "can be updated only through the parent package."); 14303 return; 14304 } 14305 14306 if (replace) { 14307 // Prevent apps opting out from runtime permissions 14308 PackageParser.Package oldPackage = mPackages.get(pkgName); 14309 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14310 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14311 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14312 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14313 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14314 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14315 + " doesn't support runtime permissions but the old" 14316 + " target SDK " + oldTargetSdk + " does."); 14317 return; 14318 } 14319 14320 // Prevent installing of child packages 14321 if (oldPackage.parentPackage != null) { 14322 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14323 "Package " + pkg.packageName + " is child of package " 14324 + oldPackage.parentPackage + ". Child packages " 14325 + "can be updated only through the parent package."); 14326 return; 14327 } 14328 } 14329 } 14330 14331 PackageSetting ps = mSettings.mPackages.get(pkgName); 14332 if (ps != null) { 14333 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14334 14335 // Quick sanity check that we're signed correctly if updating; 14336 // we'll check this again later when scanning, but we want to 14337 // bail early here before tripping over redefined permissions. 14338 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14339 if (!checkUpgradeKeySetLP(ps, pkg)) { 14340 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14341 + pkg.packageName + " upgrade keys do not match the " 14342 + "previously installed version"); 14343 return; 14344 } 14345 } else { 14346 try { 14347 verifySignaturesLP(ps, pkg); 14348 } catch (PackageManagerException e) { 14349 res.setError(e.error, e.getMessage()); 14350 return; 14351 } 14352 } 14353 14354 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14355 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14356 systemApp = (ps.pkg.applicationInfo.flags & 14357 ApplicationInfo.FLAG_SYSTEM) != 0; 14358 } 14359 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14360 } 14361 14362 // Check whether the newly-scanned package wants to define an already-defined perm 14363 int N = pkg.permissions.size(); 14364 for (int i = N-1; i >= 0; i--) { 14365 PackageParser.Permission perm = pkg.permissions.get(i); 14366 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14367 if (bp != null) { 14368 // If the defining package is signed with our cert, it's okay. This 14369 // also includes the "updating the same package" case, of course. 14370 // "updating same package" could also involve key-rotation. 14371 final boolean sigsOk; 14372 if (bp.sourcePackage.equals(pkg.packageName) 14373 && (bp.packageSetting instanceof PackageSetting) 14374 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14375 scanFlags))) { 14376 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14377 } else { 14378 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14379 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14380 } 14381 if (!sigsOk) { 14382 // If the owning package is the system itself, we log but allow 14383 // install to proceed; we fail the install on all other permission 14384 // redefinitions. 14385 if (!bp.sourcePackage.equals("android")) { 14386 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14387 + pkg.packageName + " attempting to redeclare permission " 14388 + perm.info.name + " already owned by " + bp.sourcePackage); 14389 res.origPermission = perm.info.name; 14390 res.origPackage = bp.sourcePackage; 14391 return; 14392 } else { 14393 Slog.w(TAG, "Package " + pkg.packageName 14394 + " attempting to redeclare system permission " 14395 + perm.info.name + "; ignoring new declaration"); 14396 pkg.permissions.remove(i); 14397 } 14398 } 14399 } 14400 } 14401 } 14402 14403 if (systemApp) { 14404 if (onExternal) { 14405 // Abort update; system app can't be replaced with app on sdcard 14406 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14407 "Cannot install updates to system apps on sdcard"); 14408 return; 14409 } else if (ephemeral) { 14410 // Abort update; system app can't be replaced with an ephemeral app 14411 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14412 "Cannot update a system app with an ephemeral app"); 14413 return; 14414 } 14415 } 14416 14417 if (args.move != null) { 14418 // We did an in-place move, so dex is ready to roll 14419 scanFlags |= SCAN_NO_DEX; 14420 scanFlags |= SCAN_MOVE; 14421 14422 synchronized (mPackages) { 14423 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14424 if (ps == null) { 14425 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14426 "Missing settings for moved package " + pkgName); 14427 } 14428 14429 // We moved the entire application as-is, so bring over the 14430 // previously derived ABI information. 14431 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14432 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14433 } 14434 14435 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14436 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14437 scanFlags |= SCAN_NO_DEX; 14438 14439 try { 14440 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14441 args.abiOverride : pkg.cpuAbiOverride); 14442 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14443 true /* extract libs */); 14444 } catch (PackageManagerException pme) { 14445 Slog.e(TAG, "Error deriving application ABI", pme); 14446 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14447 return; 14448 } 14449 14450 14451 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14452 // Do not run PackageDexOptimizer through the local performDexOpt 14453 // method because `pkg` is not in `mPackages` yet. 14454 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14455 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14457 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14458 String msg = "Extracking package failed for " + pkgName; 14459 res.setError(INSTALL_FAILED_DEXOPT, msg); 14460 return; 14461 } 14462 } 14463 14464 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14465 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14466 return; 14467 } 14468 14469 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14470 14471 if (replace) { 14472 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14473 installerPackageName, res); 14474 } else { 14475 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14476 args.user, installerPackageName, volumeUuid, res); 14477 } 14478 synchronized (mPackages) { 14479 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14480 if (ps != null) { 14481 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14482 } 14483 14484 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14485 for (int i = 0; i < childCount; i++) { 14486 PackageParser.Package childPkg = pkg.childPackages.get(i); 14487 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14488 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14489 if (childPs != null) { 14490 childRes.newUsers = childPs.queryInstalledUsers( 14491 sUserManager.getUserIds(), true); 14492 } 14493 } 14494 } 14495 } 14496 14497 private void startIntentFilterVerifications(int userId, boolean replacing, 14498 PackageParser.Package pkg) { 14499 if (mIntentFilterVerifierComponent == null) { 14500 Slog.w(TAG, "No IntentFilter verification will not be done as " 14501 + "there is no IntentFilterVerifier available!"); 14502 return; 14503 } 14504 14505 final int verifierUid = getPackageUid( 14506 mIntentFilterVerifierComponent.getPackageName(), 14507 MATCH_DEBUG_TRIAGED_MISSING, 14508 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14509 14510 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14511 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14512 mHandler.sendMessage(msg); 14513 14514 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14515 for (int i = 0; i < childCount; i++) { 14516 PackageParser.Package childPkg = pkg.childPackages.get(i); 14517 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14518 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14519 mHandler.sendMessage(msg); 14520 } 14521 } 14522 14523 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14524 PackageParser.Package pkg) { 14525 int size = pkg.activities.size(); 14526 if (size == 0) { 14527 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14528 "No activity, so no need to verify any IntentFilter!"); 14529 return; 14530 } 14531 14532 final boolean hasDomainURLs = hasDomainURLs(pkg); 14533 if (!hasDomainURLs) { 14534 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14535 "No domain URLs, so no need to verify any IntentFilter!"); 14536 return; 14537 } 14538 14539 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14540 + " if any IntentFilter from the " + size 14541 + " Activities needs verification ..."); 14542 14543 int count = 0; 14544 final String packageName = pkg.packageName; 14545 14546 synchronized (mPackages) { 14547 // If this is a new install and we see that we've already run verification for this 14548 // package, we have nothing to do: it means the state was restored from backup. 14549 if (!replacing) { 14550 IntentFilterVerificationInfo ivi = 14551 mSettings.getIntentFilterVerificationLPr(packageName); 14552 if (ivi != null) { 14553 if (DEBUG_DOMAIN_VERIFICATION) { 14554 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14555 + ivi.getStatusString()); 14556 } 14557 return; 14558 } 14559 } 14560 14561 // If any filters need to be verified, then all need to be. 14562 boolean needToVerify = false; 14563 for (PackageParser.Activity a : pkg.activities) { 14564 for (ActivityIntentInfo filter : a.intents) { 14565 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14566 if (DEBUG_DOMAIN_VERIFICATION) { 14567 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14568 } 14569 needToVerify = true; 14570 break; 14571 } 14572 } 14573 } 14574 14575 if (needToVerify) { 14576 final int verificationId = mIntentFilterVerificationToken++; 14577 for (PackageParser.Activity a : pkg.activities) { 14578 for (ActivityIntentInfo filter : a.intents) { 14579 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14580 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14581 "Verification needed for IntentFilter:" + filter.toString()); 14582 mIntentFilterVerifier.addOneIntentFilterVerification( 14583 verifierUid, userId, verificationId, filter, packageName); 14584 count++; 14585 } 14586 } 14587 } 14588 } 14589 } 14590 14591 if (count > 0) { 14592 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14593 + " IntentFilter verification" + (count > 1 ? "s" : "") 14594 + " for userId:" + userId); 14595 mIntentFilterVerifier.startVerifications(userId); 14596 } else { 14597 if (DEBUG_DOMAIN_VERIFICATION) { 14598 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14599 } 14600 } 14601 } 14602 14603 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14604 final ComponentName cn = filter.activity.getComponentName(); 14605 final String packageName = cn.getPackageName(); 14606 14607 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14608 packageName); 14609 if (ivi == null) { 14610 return true; 14611 } 14612 int status = ivi.getStatus(); 14613 switch (status) { 14614 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14615 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14616 return true; 14617 14618 default: 14619 // Nothing to do 14620 return false; 14621 } 14622 } 14623 14624 private static boolean isMultiArch(ApplicationInfo info) { 14625 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14626 } 14627 14628 private static boolean isExternal(PackageParser.Package pkg) { 14629 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14630 } 14631 14632 private static boolean isExternal(PackageSetting ps) { 14633 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14634 } 14635 14636 private static boolean isEphemeral(PackageParser.Package pkg) { 14637 return pkg.applicationInfo.isEphemeralApp(); 14638 } 14639 14640 private static boolean isEphemeral(PackageSetting ps) { 14641 return ps.pkg != null && isEphemeral(ps.pkg); 14642 } 14643 14644 private static boolean isSystemApp(PackageParser.Package pkg) { 14645 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14646 } 14647 14648 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14649 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14650 } 14651 14652 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14653 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14654 } 14655 14656 private static boolean isSystemApp(PackageSetting ps) { 14657 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14658 } 14659 14660 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14661 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14662 } 14663 14664 private int packageFlagsToInstallFlags(PackageSetting ps) { 14665 int installFlags = 0; 14666 if (isEphemeral(ps)) { 14667 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14668 } 14669 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14670 // This existing package was an external ASEC install when we have 14671 // the external flag without a UUID 14672 installFlags |= PackageManager.INSTALL_EXTERNAL; 14673 } 14674 if (ps.isForwardLocked()) { 14675 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14676 } 14677 return installFlags; 14678 } 14679 14680 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14681 if (isExternal(pkg)) { 14682 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14683 return StorageManager.UUID_PRIMARY_PHYSICAL; 14684 } else { 14685 return pkg.volumeUuid; 14686 } 14687 } else { 14688 return StorageManager.UUID_PRIVATE_INTERNAL; 14689 } 14690 } 14691 14692 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14693 if (isExternal(pkg)) { 14694 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14695 return mSettings.getExternalVersion(); 14696 } else { 14697 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14698 } 14699 } else { 14700 return mSettings.getInternalVersion(); 14701 } 14702 } 14703 14704 private void deleteTempPackageFiles() { 14705 final FilenameFilter filter = new FilenameFilter() { 14706 public boolean accept(File dir, String name) { 14707 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14708 } 14709 }; 14710 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14711 file.delete(); 14712 } 14713 } 14714 14715 @Override 14716 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14717 int flags) { 14718 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14719 flags); 14720 } 14721 14722 @Override 14723 public void deletePackage(final String packageName, 14724 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14725 mContext.enforceCallingOrSelfPermission( 14726 android.Manifest.permission.DELETE_PACKAGES, null); 14727 Preconditions.checkNotNull(packageName); 14728 Preconditions.checkNotNull(observer); 14729 final int uid = Binder.getCallingUid(); 14730 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14731 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14732 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14733 mContext.enforceCallingOrSelfPermission( 14734 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14735 "deletePackage for user " + userId); 14736 } 14737 14738 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14739 try { 14740 observer.onPackageDeleted(packageName, 14741 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14742 } catch (RemoteException re) { 14743 } 14744 return; 14745 } 14746 14747 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14748 try { 14749 observer.onPackageDeleted(packageName, 14750 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14751 } catch (RemoteException re) { 14752 } 14753 return; 14754 } 14755 14756 if (DEBUG_REMOVE) { 14757 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14758 + " deleteAllUsers: " + deleteAllUsers ); 14759 } 14760 // Queue up an async operation since the package deletion may take a little while. 14761 mHandler.post(new Runnable() { 14762 public void run() { 14763 mHandler.removeCallbacks(this); 14764 int returnCode; 14765 if (!deleteAllUsers) { 14766 returnCode = deletePackageX(packageName, userId, flags); 14767 } else { 14768 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14769 // If nobody is blocking uninstall, proceed with delete for all users 14770 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14771 returnCode = deletePackageX(packageName, userId, flags); 14772 } else { 14773 // Otherwise uninstall individually for users with blockUninstalls=false 14774 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14775 for (int userId : users) { 14776 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14777 returnCode = deletePackageX(packageName, userId, userFlags); 14778 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14779 Slog.w(TAG, "Package delete failed for user " + userId 14780 + ", returnCode " + returnCode); 14781 } 14782 } 14783 } 14784 // The app has only been marked uninstalled for certain users. 14785 // We still need to report that delete was blocked 14786 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14787 } 14788 } 14789 try { 14790 observer.onPackageDeleted(packageName, returnCode, null); 14791 } catch (RemoteException e) { 14792 Log.i(TAG, "Observer no longer exists."); 14793 } //end catch 14794 } //end run 14795 }); 14796 } 14797 14798 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14799 int[] result = EMPTY_INT_ARRAY; 14800 for (int userId : userIds) { 14801 if (getBlockUninstallForUser(packageName, userId)) { 14802 result = ArrayUtils.appendInt(result, userId); 14803 } 14804 } 14805 return result; 14806 } 14807 14808 @Override 14809 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14810 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14811 } 14812 14813 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14814 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14815 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14816 try { 14817 if (dpm != null) { 14818 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14819 /* callingUserOnly =*/ false); 14820 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14821 : deviceOwnerComponentName.getPackageName(); 14822 // Does the package contains the device owner? 14823 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14824 // this check is probably not needed, since DO should be registered as a device 14825 // admin on some user too. (Original bug for this: b/17657954) 14826 if (packageName.equals(deviceOwnerPackageName)) { 14827 return true; 14828 } 14829 // Does it contain a device admin for any user? 14830 int[] users; 14831 if (userId == UserHandle.USER_ALL) { 14832 users = sUserManager.getUserIds(); 14833 } else { 14834 users = new int[]{userId}; 14835 } 14836 for (int i = 0; i < users.length; ++i) { 14837 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14838 return true; 14839 } 14840 } 14841 } 14842 } catch (RemoteException e) { 14843 } 14844 return false; 14845 } 14846 14847 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14848 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14849 } 14850 14851 /** 14852 * This method is an internal method that could be get invoked either 14853 * to delete an installed package or to clean up a failed installation. 14854 * After deleting an installed package, a broadcast is sent to notify any 14855 * listeners that the package has been installed. For cleaning up a failed 14856 * installation, the broadcast is not necessary since the package's 14857 * installation wouldn't have sent the initial broadcast either 14858 * The key steps in deleting a package are 14859 * deleting the package information in internal structures like mPackages, 14860 * deleting the packages base directories through installd 14861 * updating mSettings to reflect current status 14862 * persisting settings for later use 14863 * sending a broadcast if necessary 14864 */ 14865 private int deletePackageX(String packageName, int userId, int flags) { 14866 final PackageRemovedInfo info = new PackageRemovedInfo(); 14867 final boolean res; 14868 14869 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14870 ? UserHandle.ALL : new UserHandle(userId); 14871 14872 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14873 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14874 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14875 } 14876 14877 PackageSetting uninstalledPs = null; 14878 14879 // for the uninstall-updates case and restricted profiles, remember the per- 14880 // user handle installed state 14881 int[] allUsers; 14882 synchronized (mPackages) { 14883 uninstalledPs = mSettings.mPackages.get(packageName); 14884 if (uninstalledPs == null) { 14885 Slog.w(TAG, "Not removing non-existent package " + packageName); 14886 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14887 } 14888 allUsers = sUserManager.getUserIds(); 14889 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14890 } 14891 14892 synchronized (mInstallLock) { 14893 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14894 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14895 flags | REMOVE_CHATTY, info, true, null); 14896 synchronized (mPackages) { 14897 if (res) { 14898 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14899 } 14900 } 14901 } 14902 14903 if (res) { 14904 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14905 info.sendPackageRemovedBroadcasts(killApp); 14906 info.sendSystemPackageUpdatedBroadcasts(); 14907 info.sendSystemPackageAppearedBroadcasts(); 14908 } 14909 // Force a gc here. 14910 Runtime.getRuntime().gc(); 14911 // Delete the resources here after sending the broadcast to let 14912 // other processes clean up before deleting resources. 14913 if (info.args != null) { 14914 synchronized (mInstallLock) { 14915 info.args.doPostDeleteLI(true); 14916 } 14917 } 14918 14919 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14920 } 14921 14922 class PackageRemovedInfo { 14923 String removedPackage; 14924 int uid = -1; 14925 int removedAppId = -1; 14926 int[] origUsers; 14927 int[] removedUsers = null; 14928 boolean isRemovedPackageSystemUpdate = false; 14929 boolean isUpdate; 14930 boolean dataRemoved; 14931 boolean removedForAllUsers; 14932 // Clean up resources deleted packages. 14933 InstallArgs args = null; 14934 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14935 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14936 14937 void sendPackageRemovedBroadcasts(boolean killApp) { 14938 sendPackageRemovedBroadcastInternal(killApp); 14939 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14940 for (int i = 0; i < childCount; i++) { 14941 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14942 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14943 } 14944 } 14945 14946 void sendSystemPackageUpdatedBroadcasts() { 14947 if (isRemovedPackageSystemUpdate) { 14948 sendSystemPackageUpdatedBroadcastsInternal(); 14949 final int childCount = (removedChildPackages != null) 14950 ? removedChildPackages.size() : 0; 14951 for (int i = 0; i < childCount; i++) { 14952 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14953 if (childInfo.isRemovedPackageSystemUpdate) { 14954 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14955 } 14956 } 14957 } 14958 } 14959 14960 void sendSystemPackageAppearedBroadcasts() { 14961 final int packageCount = (appearedChildPackages != null) 14962 ? appearedChildPackages.size() : 0; 14963 for (int i = 0; i < packageCount; i++) { 14964 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14965 for (int userId : installedInfo.newUsers) { 14966 sendPackageAddedForUser(installedInfo.name, true, 14967 UserHandle.getAppId(installedInfo.uid), userId); 14968 } 14969 } 14970 } 14971 14972 private void sendSystemPackageUpdatedBroadcastsInternal() { 14973 Bundle extras = new Bundle(2); 14974 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14975 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14976 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14977 extras, 0, null, null, null); 14978 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14979 extras, 0, null, null, null); 14980 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14981 null, 0, removedPackage, null, null); 14982 } 14983 14984 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14985 Bundle extras = new Bundle(2); 14986 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14987 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14988 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14989 if (isUpdate || isRemovedPackageSystemUpdate) { 14990 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14991 } 14992 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14993 if (removedPackage != null) { 14994 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14995 extras, 0, null, null, removedUsers); 14996 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14997 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14998 removedPackage, extras, 0, null, null, removedUsers); 14999 } 15000 } 15001 if (removedAppId >= 0) { 15002 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15003 removedUsers); 15004 } 15005 } 15006 } 15007 15008 /* 15009 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15010 * flag is not set, the data directory is removed as well. 15011 * make sure this flag is set for partially installed apps. If not its meaningless to 15012 * delete a partially installed application. 15013 */ 15014 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 15015 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15016 String packageName = ps.name; 15017 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15018 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 15019 // Retrieve object to delete permissions for shared user later on 15020 final PackageSetting deletedPs; 15021 // reader 15022 synchronized (mPackages) { 15023 deletedPs = mSettings.mPackages.get(packageName); 15024 if (outInfo != null) { 15025 outInfo.removedPackage = packageName; 15026 outInfo.removedUsers = deletedPs != null 15027 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15028 : null; 15029 } 15030 } 15031 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15032 removeDataDirsLI(ps.volumeUuid, packageName); 15033 if (outInfo != null) { 15034 outInfo.dataRemoved = true; 15035 } 15036 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15037 } 15038 // writer 15039 synchronized (mPackages) { 15040 if (deletedPs != null) { 15041 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15042 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15043 clearDefaultBrowserIfNeeded(packageName); 15044 if (outInfo != null) { 15045 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15046 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15047 } 15048 updatePermissionsLPw(deletedPs.name, null, 0); 15049 if (deletedPs.sharedUser != null) { 15050 // Remove permissions associated with package. Since runtime 15051 // permissions are per user we have to kill the removed package 15052 // or packages running under the shared user of the removed 15053 // package if revoking the permissions requested only by the removed 15054 // package is successful and this causes a change in gids. 15055 for (int userId : UserManagerService.getInstance().getUserIds()) { 15056 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15057 userId); 15058 if (userIdToKill == UserHandle.USER_ALL 15059 || userIdToKill >= UserHandle.USER_SYSTEM) { 15060 // If gids changed for this user, kill all affected packages. 15061 mHandler.post(new Runnable() { 15062 @Override 15063 public void run() { 15064 // This has to happen with no lock held. 15065 killApplication(deletedPs.name, deletedPs.appId, 15066 KILL_APP_REASON_GIDS_CHANGED); 15067 } 15068 }); 15069 break; 15070 } 15071 } 15072 } 15073 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15074 } 15075 // make sure to preserve per-user disabled state if this removal was just 15076 // a downgrade of a system app to the factory package 15077 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15078 if (DEBUG_REMOVE) { 15079 Slog.d(TAG, "Propagating install state across downgrade"); 15080 } 15081 for (int userId : allUserHandles) { 15082 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15083 if (DEBUG_REMOVE) { 15084 Slog.d(TAG, " user " + userId + " => " + installed); 15085 } 15086 ps.setInstalled(installed, userId); 15087 } 15088 } 15089 } 15090 // can downgrade to reader 15091 if (writeSettings) { 15092 // Save settings now 15093 mSettings.writeLPr(); 15094 } 15095 } 15096 if (outInfo != null) { 15097 // A user ID was deleted here. Go through all users and remove it 15098 // from KeyStore. 15099 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15100 } 15101 } 15102 15103 static boolean locationIsPrivileged(File path) { 15104 try { 15105 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15106 .getCanonicalPath(); 15107 return path.getCanonicalPath().startsWith(privilegedAppDir); 15108 } catch (IOException e) { 15109 Slog.e(TAG, "Unable to access code path " + path); 15110 } 15111 return false; 15112 } 15113 15114 /* 15115 * Tries to delete system package. 15116 */ 15117 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 15118 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15119 boolean writeSettings) { 15120 if (deletedPs.parentPackageName != null) { 15121 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15122 return false; 15123 } 15124 15125 final boolean applyUserRestrictions 15126 = (allUserHandles != null) && (outInfo.origUsers != null); 15127 final PackageSetting disabledPs; 15128 // Confirm if the system package has been updated 15129 // An updated system app can be deleted. This will also have to restore 15130 // the system pkg from system partition 15131 // reader 15132 synchronized (mPackages) { 15133 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15134 } 15135 15136 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15137 + " disabledPs=" + disabledPs); 15138 15139 if (disabledPs == null) { 15140 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15141 return false; 15142 } else if (DEBUG_REMOVE) { 15143 Slog.d(TAG, "Deleting system pkg from data partition"); 15144 } 15145 15146 if (DEBUG_REMOVE) { 15147 if (applyUserRestrictions) { 15148 Slog.d(TAG, "Remembering install states:"); 15149 for (int userId : allUserHandles) { 15150 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15151 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15152 } 15153 } 15154 } 15155 15156 // Delete the updated package 15157 outInfo.isRemovedPackageSystemUpdate = true; 15158 if (outInfo.removedChildPackages != null) { 15159 final int childCount = (deletedPs.childPackageNames != null) 15160 ? deletedPs.childPackageNames.size() : 0; 15161 for (int i = 0; i < childCount; i++) { 15162 String childPackageName = deletedPs.childPackageNames.get(i); 15163 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15164 .contains(childPackageName)) { 15165 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15166 childPackageName); 15167 if (childInfo != null) { 15168 childInfo.isRemovedPackageSystemUpdate = true; 15169 } 15170 } 15171 } 15172 } 15173 15174 if (disabledPs.versionCode < deletedPs.versionCode) { 15175 // Delete data for downgrades 15176 flags &= ~PackageManager.DELETE_KEEP_DATA; 15177 } else { 15178 // Preserve data by setting flag 15179 flags |= PackageManager.DELETE_KEEP_DATA; 15180 } 15181 15182 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 15183 outInfo, writeSettings, disabledPs.pkg); 15184 if (!ret) { 15185 return false; 15186 } 15187 15188 // writer 15189 synchronized (mPackages) { 15190 // Reinstate the old system package 15191 enableSystemPackageLPw(disabledPs.pkg); 15192 // Remove any native libraries from the upgraded package. 15193 removeNativeBinariesLI(deletedPs); 15194 } 15195 15196 // Install the system package 15197 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15198 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15199 if (locationIsPrivileged(disabledPs.codePath)) { 15200 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15201 } 15202 15203 final PackageParser.Package newPkg; 15204 try { 15205 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15206 } catch (PackageManagerException e) { 15207 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15208 + e.getMessage()); 15209 return false; 15210 } 15211 15212 prepareAppDataAfterInstall(newPkg); 15213 15214 // writer 15215 synchronized (mPackages) { 15216 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15217 15218 // Propagate the permissions state as we do not want to drop on the floor 15219 // runtime permissions. The update permissions method below will take 15220 // care of removing obsolete permissions and grant install permissions. 15221 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15222 updatePermissionsLPw(newPkg.packageName, newPkg, 15223 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15224 15225 if (applyUserRestrictions) { 15226 if (DEBUG_REMOVE) { 15227 Slog.d(TAG, "Propagating install state across reinstall"); 15228 } 15229 for (int userId : allUserHandles) { 15230 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15231 if (DEBUG_REMOVE) { 15232 Slog.d(TAG, " user " + userId + " => " + installed); 15233 } 15234 ps.setInstalled(installed, userId); 15235 15236 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15237 } 15238 // Regardless of writeSettings we need to ensure that this restriction 15239 // state propagation is persisted 15240 mSettings.writeAllUsersPackageRestrictionsLPr(); 15241 } 15242 // can downgrade to reader here 15243 if (writeSettings) { 15244 mSettings.writeLPr(); 15245 } 15246 } 15247 return true; 15248 } 15249 15250 private boolean deleteInstalledPackageLI(PackageSetting ps, 15251 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15252 PackageRemovedInfo outInfo, boolean writeSettings, 15253 PackageParser.Package replacingPackage) { 15254 synchronized (mPackages) { 15255 if (outInfo != null) { 15256 outInfo.uid = ps.appId; 15257 } 15258 15259 if (outInfo != null && outInfo.removedChildPackages != null) { 15260 final int childCount = (ps.childPackageNames != null) 15261 ? ps.childPackageNames.size() : 0; 15262 for (int i = 0; i < childCount; i++) { 15263 String childPackageName = ps.childPackageNames.get(i); 15264 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15265 if (childPs == null) { 15266 return false; 15267 } 15268 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15269 childPackageName); 15270 if (childInfo != null) { 15271 childInfo.uid = childPs.appId; 15272 } 15273 } 15274 } 15275 } 15276 15277 // Delete package data from internal structures and also remove data if flag is set 15278 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 15279 15280 // Delete the child packages data 15281 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15282 for (int i = 0; i < childCount; i++) { 15283 PackageSetting childPs; 15284 synchronized (mPackages) { 15285 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15286 } 15287 if (childPs != null) { 15288 PackageRemovedInfo childOutInfo = (outInfo != null 15289 && outInfo.removedChildPackages != null) 15290 ? outInfo.removedChildPackages.get(childPs.name) : null; 15291 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15292 && (replacingPackage != null 15293 && !replacingPackage.hasChildPackage(childPs.name)) 15294 ? flags & ~DELETE_KEEP_DATA : flags; 15295 removePackageDataLI(childPs, allUserHandles, childOutInfo, 15296 deleteFlags, writeSettings); 15297 } 15298 } 15299 15300 // Delete application code and resources only for parent packages 15301 if (ps.parentPackageName == null) { 15302 if (deleteCodeAndResources && (outInfo != null)) { 15303 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15304 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15305 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15306 } 15307 } 15308 15309 return true; 15310 } 15311 15312 @Override 15313 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15314 int userId) { 15315 mContext.enforceCallingOrSelfPermission( 15316 android.Manifest.permission.DELETE_PACKAGES, null); 15317 synchronized (mPackages) { 15318 PackageSetting ps = mSettings.mPackages.get(packageName); 15319 if (ps == null) { 15320 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15321 return false; 15322 } 15323 if (!ps.getInstalled(userId)) { 15324 // Can't block uninstall for an app that is not installed or enabled. 15325 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15326 return false; 15327 } 15328 ps.setBlockUninstall(blockUninstall, userId); 15329 mSettings.writePackageRestrictionsLPr(userId); 15330 } 15331 return true; 15332 } 15333 15334 @Override 15335 public boolean getBlockUninstallForUser(String packageName, int userId) { 15336 synchronized (mPackages) { 15337 PackageSetting ps = mSettings.mPackages.get(packageName); 15338 if (ps == null) { 15339 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15340 return false; 15341 } 15342 return ps.getBlockUninstall(userId); 15343 } 15344 } 15345 15346 @Override 15347 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15348 int callingUid = Binder.getCallingUid(); 15349 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15350 throw new SecurityException( 15351 "setRequiredForSystemUser can only be run by the system or root"); 15352 } 15353 synchronized (mPackages) { 15354 PackageSetting ps = mSettings.mPackages.get(packageName); 15355 if (ps == null) { 15356 Log.w(TAG, "Package doesn't exist: " + packageName); 15357 return false; 15358 } 15359 if (systemUserApp) { 15360 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15361 } else { 15362 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15363 } 15364 mSettings.writeLPr(); 15365 } 15366 return true; 15367 } 15368 15369 /* 15370 * This method handles package deletion in general 15371 */ 15372 private boolean deletePackageLI(String packageName, UserHandle user, 15373 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15374 PackageRemovedInfo outInfo, boolean writeSettings, 15375 PackageParser.Package replacingPackage) { 15376 if (packageName == null) { 15377 Slog.w(TAG, "Attempt to delete null packageName."); 15378 return false; 15379 } 15380 15381 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15382 15383 PackageSetting ps; 15384 15385 synchronized (mPackages) { 15386 ps = mSettings.mPackages.get(packageName); 15387 if (ps == null) { 15388 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15389 return false; 15390 } 15391 15392 if (ps.parentPackageName != null && (!isSystemApp(ps) 15393 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15394 if (DEBUG_REMOVE) { 15395 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15396 + ((user == null) ? UserHandle.USER_ALL : user)); 15397 } 15398 final int removedUserId = (user != null) ? user.getIdentifier() 15399 : UserHandle.USER_ALL; 15400 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 15401 return false; 15402 } 15403 markPackageUninstalledForUserLPw(ps, user); 15404 scheduleWritePackageRestrictionsLocked(user); 15405 return true; 15406 } 15407 } 15408 15409 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15410 && user.getIdentifier() != UserHandle.USER_ALL)) { 15411 // The caller is asking that the package only be deleted for a single 15412 // user. To do this, we just mark its uninstalled state and delete 15413 // its data. If this is a system app, we only allow this to happen if 15414 // they have set the special DELETE_SYSTEM_APP which requests different 15415 // semantics than normal for uninstalling system apps. 15416 markPackageUninstalledForUserLPw(ps, user); 15417 15418 if (!isSystemApp(ps)) { 15419 // Do not uninstall the APK if an app should be cached 15420 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15421 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15422 // Other user still have this package installed, so all 15423 // we need to do is clear this user's data and save that 15424 // it is uninstalled. 15425 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15426 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15427 return false; 15428 } 15429 scheduleWritePackageRestrictionsLocked(user); 15430 return true; 15431 } else { 15432 // We need to set it back to 'installed' so the uninstall 15433 // broadcasts will be sent correctly. 15434 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15435 ps.setInstalled(true, user.getIdentifier()); 15436 } 15437 } else { 15438 // This is a system app, so we assume that the 15439 // other users still have this package installed, so all 15440 // we need to do is clear this user's data and save that 15441 // it is uninstalled. 15442 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15443 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 15444 return false; 15445 } 15446 scheduleWritePackageRestrictionsLocked(user); 15447 return true; 15448 } 15449 } 15450 15451 // If we are deleting a composite package for all users, keep track 15452 // of result for each child. 15453 if (ps.childPackageNames != null && outInfo != null) { 15454 synchronized (mPackages) { 15455 final int childCount = ps.childPackageNames.size(); 15456 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15457 for (int i = 0; i < childCount; i++) { 15458 String childPackageName = ps.childPackageNames.get(i); 15459 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15460 childInfo.removedPackage = childPackageName; 15461 outInfo.removedChildPackages.put(childPackageName, childInfo); 15462 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15463 if (childPs != null) { 15464 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15465 } 15466 } 15467 } 15468 } 15469 15470 boolean ret = false; 15471 if (isSystemApp(ps)) { 15472 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15473 // When an updated system application is deleted we delete the existing resources 15474 // as well and fall back to existing code in system partition 15475 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15476 } else { 15477 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15478 // Kill application pre-emptively especially for apps on sd. 15479 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15480 if (killApp) { 15481 killApplication(packageName, ps.appId, "uninstall pkg"); 15482 } 15483 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 15484 outInfo, writeSettings, replacingPackage); 15485 } 15486 15487 // Take a note whether we deleted the package for all users 15488 if (outInfo != null) { 15489 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15490 if (outInfo.removedChildPackages != null) { 15491 synchronized (mPackages) { 15492 final int childCount = outInfo.removedChildPackages.size(); 15493 for (int i = 0; i < childCount; i++) { 15494 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15495 if (childInfo != null) { 15496 childInfo.removedForAllUsers = mPackages.get( 15497 childInfo.removedPackage) == null; 15498 } 15499 } 15500 } 15501 } 15502 // If we uninstalled an update to a system app there may be some 15503 // child packages that appeared as they are declared in the system 15504 // app but were not declared in the update. 15505 if (isSystemApp(ps)) { 15506 synchronized (mPackages) { 15507 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15508 final int childCount = (updatedPs.childPackageNames != null) 15509 ? updatedPs.childPackageNames.size() : 0; 15510 for (int i = 0; i < childCount; i++) { 15511 String childPackageName = updatedPs.childPackageNames.get(i); 15512 if (outInfo.removedChildPackages == null 15513 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15514 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15515 if (childPs == null) { 15516 continue; 15517 } 15518 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15519 installRes.name = childPackageName; 15520 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15521 installRes.pkg = mPackages.get(childPackageName); 15522 installRes.uid = childPs.pkg.applicationInfo.uid; 15523 if (outInfo.appearedChildPackages == null) { 15524 outInfo.appearedChildPackages = new ArrayMap<>(); 15525 } 15526 outInfo.appearedChildPackages.put(childPackageName, installRes); 15527 } 15528 } 15529 } 15530 } 15531 } 15532 15533 return ret; 15534 } 15535 15536 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15537 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15538 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15539 for (int nextUserId : userIds) { 15540 if (DEBUG_REMOVE) { 15541 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15542 } 15543 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15544 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15545 false /*hidden*/, false /*suspended*/, null, null, null, 15546 false /*blockUninstall*/, 15547 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15548 } 15549 } 15550 15551 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15552 PackageRemovedInfo outInfo) { 15553 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15554 : new int[] {userId}; 15555 for (int nextUserId : userIds) { 15556 if (DEBUG_REMOVE) { 15557 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15558 + nextUserId); 15559 } 15560 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15561 try { 15562 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15563 } catch (InstallerException e) { 15564 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15565 return false; 15566 } 15567 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15568 schedulePackageCleaning(ps.name, nextUserId, false); 15569 synchronized (mPackages) { 15570 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15571 scheduleWritePackageRestrictionsLocked(nextUserId); 15572 } 15573 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15574 } 15575 } 15576 15577 if (outInfo != null) { 15578 outInfo.removedPackage = ps.name; 15579 outInfo.removedAppId = ps.appId; 15580 outInfo.removedUsers = userIds; 15581 } 15582 15583 return true; 15584 } 15585 15586 private final class ClearStorageConnection implements ServiceConnection { 15587 IMediaContainerService mContainerService; 15588 15589 @Override 15590 public void onServiceConnected(ComponentName name, IBinder service) { 15591 synchronized (this) { 15592 mContainerService = IMediaContainerService.Stub.asInterface(service); 15593 notifyAll(); 15594 } 15595 } 15596 15597 @Override 15598 public void onServiceDisconnected(ComponentName name) { 15599 } 15600 } 15601 15602 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15603 final boolean mounted; 15604 if (Environment.isExternalStorageEmulated()) { 15605 mounted = true; 15606 } else { 15607 final String status = Environment.getExternalStorageState(); 15608 15609 mounted = status.equals(Environment.MEDIA_MOUNTED) 15610 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15611 } 15612 15613 if (!mounted) { 15614 return; 15615 } 15616 15617 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15618 int[] users; 15619 if (userId == UserHandle.USER_ALL) { 15620 users = sUserManager.getUserIds(); 15621 } else { 15622 users = new int[] { userId }; 15623 } 15624 final ClearStorageConnection conn = new ClearStorageConnection(); 15625 if (mContext.bindServiceAsUser( 15626 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15627 try { 15628 for (int curUser : users) { 15629 long timeout = SystemClock.uptimeMillis() + 5000; 15630 synchronized (conn) { 15631 long now = SystemClock.uptimeMillis(); 15632 while (conn.mContainerService == null && now < timeout) { 15633 try { 15634 conn.wait(timeout - now); 15635 } catch (InterruptedException e) { 15636 } 15637 } 15638 } 15639 if (conn.mContainerService == null) { 15640 return; 15641 } 15642 15643 final UserEnvironment userEnv = new UserEnvironment(curUser); 15644 clearDirectory(conn.mContainerService, 15645 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15646 if (allData) { 15647 clearDirectory(conn.mContainerService, 15648 userEnv.buildExternalStorageAppDataDirs(packageName)); 15649 clearDirectory(conn.mContainerService, 15650 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15651 } 15652 } 15653 } finally { 15654 mContext.unbindService(conn); 15655 } 15656 } 15657 } 15658 15659 @Override 15660 public void clearApplicationProfileData(String packageName) { 15661 enforceSystemOrRoot("Only the system can clear all profile data"); 15662 try { 15663 mInstaller.clearAppProfiles(packageName); 15664 } catch (InstallerException ex) { 15665 Log.e(TAG, "Could not clear profile data of package " + packageName); 15666 } 15667 } 15668 15669 @Override 15670 public void clearApplicationUserData(final String packageName, 15671 final IPackageDataObserver observer, final int userId) { 15672 mContext.enforceCallingOrSelfPermission( 15673 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15674 15675 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15676 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15677 15678 final DevicePolicyManagerInternal dpmi = LocalServices 15679 .getService(DevicePolicyManagerInternal.class); 15680 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15681 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15682 } 15683 // Queue up an async operation since the package deletion may take a little while. 15684 mHandler.post(new Runnable() { 15685 public void run() { 15686 mHandler.removeCallbacks(this); 15687 final boolean succeeded; 15688 synchronized (mInstallLock) { 15689 succeeded = clearApplicationUserDataLI(packageName, userId); 15690 } 15691 clearExternalStorageDataSync(packageName, userId, true); 15692 if (succeeded) { 15693 // invoke DeviceStorageMonitor's update method to clear any notifications 15694 DeviceStorageMonitorInternal dsm = LocalServices 15695 .getService(DeviceStorageMonitorInternal.class); 15696 if (dsm != null) { 15697 dsm.checkMemory(); 15698 } 15699 } 15700 if(observer != null) { 15701 try { 15702 observer.onRemoveCompleted(packageName, succeeded); 15703 } catch (RemoteException e) { 15704 Log.i(TAG, "Observer no longer exists."); 15705 } 15706 } //end if observer 15707 } //end run 15708 }); 15709 } 15710 15711 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15712 if (packageName == null) { 15713 Slog.w(TAG, "Attempt to delete null packageName."); 15714 return false; 15715 } 15716 15717 // Try finding details about the requested package 15718 PackageParser.Package pkg; 15719 synchronized (mPackages) { 15720 pkg = mPackages.get(packageName); 15721 if (pkg == null) { 15722 final PackageSetting ps = mSettings.mPackages.get(packageName); 15723 if (ps != null) { 15724 pkg = ps.pkg; 15725 } 15726 } 15727 15728 if (pkg == null) { 15729 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15730 return false; 15731 } 15732 15733 PackageSetting ps = (PackageSetting) pkg.mExtras; 15734 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15735 } 15736 15737 // Always delete data directories for package, even if we found no other 15738 // record of app. This helps users recover from UID mismatches without 15739 // resorting to a full data wipe. 15740 // TODO: triage flags as part of 26466827 15741 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15742 try { 15743 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15744 } catch (InstallerException e) { 15745 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15746 return false; 15747 } 15748 15749 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15750 removeKeystoreDataIfNeeded(userId, appId); 15751 15752 // Create a native library symlink only if we have native libraries 15753 // and if the native libraries are 32 bit libraries. We do not provide 15754 // this symlink for 64 bit libraries. 15755 if (pkg.applicationInfo.primaryCpuAbi != null && 15756 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15757 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15758 try { 15759 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15760 nativeLibPath, userId); 15761 } catch (InstallerException e) { 15762 Slog.w(TAG, "Failed linking native library dir", e); 15763 return false; 15764 } 15765 } 15766 15767 return true; 15768 } 15769 15770 /** 15771 * Reverts user permission state changes (permissions and flags) in 15772 * all packages for a given user. 15773 * 15774 * @param userId The device user for which to do a reset. 15775 */ 15776 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15777 final int packageCount = mPackages.size(); 15778 for (int i = 0; i < packageCount; i++) { 15779 PackageParser.Package pkg = mPackages.valueAt(i); 15780 PackageSetting ps = (PackageSetting) pkg.mExtras; 15781 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15782 } 15783 } 15784 15785 /** 15786 * Reverts user permission state changes (permissions and flags). 15787 * 15788 * @param ps The package for which to reset. 15789 * @param userId The device user for which to do a reset. 15790 */ 15791 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15792 final PackageSetting ps, final int userId) { 15793 if (ps.pkg == null) { 15794 return; 15795 } 15796 15797 // These are flags that can change base on user actions. 15798 final int userSettableMask = FLAG_PERMISSION_USER_SET 15799 | FLAG_PERMISSION_USER_FIXED 15800 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15801 | FLAG_PERMISSION_REVIEW_REQUIRED; 15802 15803 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15804 | FLAG_PERMISSION_POLICY_FIXED; 15805 15806 boolean writeInstallPermissions = false; 15807 boolean writeRuntimePermissions = false; 15808 15809 final int permissionCount = ps.pkg.requestedPermissions.size(); 15810 for (int i = 0; i < permissionCount; i++) { 15811 String permission = ps.pkg.requestedPermissions.get(i); 15812 15813 BasePermission bp = mSettings.mPermissions.get(permission); 15814 if (bp == null) { 15815 continue; 15816 } 15817 15818 // If shared user we just reset the state to which only this app contributed. 15819 if (ps.sharedUser != null) { 15820 boolean used = false; 15821 final int packageCount = ps.sharedUser.packages.size(); 15822 for (int j = 0; j < packageCount; j++) { 15823 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15824 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15825 && pkg.pkg.requestedPermissions.contains(permission)) { 15826 used = true; 15827 break; 15828 } 15829 } 15830 if (used) { 15831 continue; 15832 } 15833 } 15834 15835 PermissionsState permissionsState = ps.getPermissionsState(); 15836 15837 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15838 15839 // Always clear the user settable flags. 15840 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15841 bp.name) != null; 15842 // If permission review is enabled and this is a legacy app, mark the 15843 // permission as requiring a review as this is the initial state. 15844 int flags = 0; 15845 if (Build.PERMISSIONS_REVIEW_REQUIRED 15846 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15847 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15848 } 15849 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15850 if (hasInstallState) { 15851 writeInstallPermissions = true; 15852 } else { 15853 writeRuntimePermissions = true; 15854 } 15855 } 15856 15857 // Below is only runtime permission handling. 15858 if (!bp.isRuntime()) { 15859 continue; 15860 } 15861 15862 // Never clobber system or policy. 15863 if ((oldFlags & policyOrSystemFlags) != 0) { 15864 continue; 15865 } 15866 15867 // If this permission was granted by default, make sure it is. 15868 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15869 if (permissionsState.grantRuntimePermission(bp, userId) 15870 != PERMISSION_OPERATION_FAILURE) { 15871 writeRuntimePermissions = true; 15872 } 15873 // If permission review is enabled the permissions for a legacy apps 15874 // are represented as constantly granted runtime ones, so don't revoke. 15875 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15876 // Otherwise, reset the permission. 15877 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15878 switch (revokeResult) { 15879 case PERMISSION_OPERATION_SUCCESS: 15880 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15881 writeRuntimePermissions = true; 15882 final int appId = ps.appId; 15883 mHandler.post(new Runnable() { 15884 @Override 15885 public void run() { 15886 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15887 } 15888 }); 15889 } break; 15890 } 15891 } 15892 } 15893 15894 // Synchronously write as we are taking permissions away. 15895 if (writeRuntimePermissions) { 15896 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15897 } 15898 15899 // Synchronously write as we are taking permissions away. 15900 if (writeInstallPermissions) { 15901 mSettings.writeLPr(); 15902 } 15903 } 15904 15905 /** 15906 * Remove entries from the keystore daemon. Will only remove it if the 15907 * {@code appId} is valid. 15908 */ 15909 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15910 if (appId < 0) { 15911 return; 15912 } 15913 15914 final KeyStore keyStore = KeyStore.getInstance(); 15915 if (keyStore != null) { 15916 if (userId == UserHandle.USER_ALL) { 15917 for (final int individual : sUserManager.getUserIds()) { 15918 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15919 } 15920 } else { 15921 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15922 } 15923 } else { 15924 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15925 } 15926 } 15927 15928 @Override 15929 public void deleteApplicationCacheFiles(final String packageName, 15930 final IPackageDataObserver observer) { 15931 mContext.enforceCallingOrSelfPermission( 15932 android.Manifest.permission.DELETE_CACHE_FILES, null); 15933 // Queue up an async operation since the package deletion may take a little while. 15934 final int userId = UserHandle.getCallingUserId(); 15935 mHandler.post(new Runnable() { 15936 public void run() { 15937 mHandler.removeCallbacks(this); 15938 final boolean succeded; 15939 synchronized (mInstallLock) { 15940 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15941 } 15942 clearExternalStorageDataSync(packageName, userId, false); 15943 if (observer != null) { 15944 try { 15945 observer.onRemoveCompleted(packageName, succeded); 15946 } catch (RemoteException e) { 15947 Log.i(TAG, "Observer no longer exists."); 15948 } 15949 } //end if observer 15950 } //end run 15951 }); 15952 } 15953 15954 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15955 if (packageName == null) { 15956 Slog.w(TAG, "Attempt to delete null packageName."); 15957 return false; 15958 } 15959 PackageParser.Package p; 15960 synchronized (mPackages) { 15961 p = mPackages.get(packageName); 15962 } 15963 if (p == null) { 15964 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15965 return false; 15966 } 15967 final ApplicationInfo applicationInfo = p.applicationInfo; 15968 if (applicationInfo == null) { 15969 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15970 return false; 15971 } 15972 // TODO: triage flags as part of 26466827 15973 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15974 try { 15975 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15976 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15977 } catch (InstallerException e) { 15978 Slog.w(TAG, "Couldn't remove cache files for package " 15979 + packageName + " u" + userId, e); 15980 return false; 15981 } 15982 return true; 15983 } 15984 15985 @Override 15986 public void getPackageSizeInfo(final String packageName, int userHandle, 15987 final IPackageStatsObserver observer) { 15988 mContext.enforceCallingOrSelfPermission( 15989 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15990 if (packageName == null) { 15991 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15992 } 15993 15994 PackageStats stats = new PackageStats(packageName, userHandle); 15995 15996 /* 15997 * Queue up an async operation since the package measurement may take a 15998 * little while. 15999 */ 16000 Message msg = mHandler.obtainMessage(INIT_COPY); 16001 msg.obj = new MeasureParams(stats, observer); 16002 mHandler.sendMessage(msg); 16003 } 16004 16005 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 16006 PackageStats pStats) { 16007 if (packageName == null) { 16008 Slog.w(TAG, "Attempt to get size of null packageName."); 16009 return false; 16010 } 16011 PackageParser.Package p; 16012 boolean dataOnly = false; 16013 String libDirRoot = null; 16014 String asecPath = null; 16015 PackageSetting ps = null; 16016 synchronized (mPackages) { 16017 p = mPackages.get(packageName); 16018 ps = mSettings.mPackages.get(packageName); 16019 if(p == null) { 16020 dataOnly = true; 16021 if((ps == null) || (ps.pkg == null)) { 16022 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 16023 return false; 16024 } 16025 p = ps.pkg; 16026 } 16027 if (ps != null) { 16028 libDirRoot = ps.legacyNativeLibraryPathString; 16029 } 16030 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 16031 final long token = Binder.clearCallingIdentity(); 16032 try { 16033 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 16034 if (secureContainerId != null) { 16035 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 16036 } 16037 } finally { 16038 Binder.restoreCallingIdentity(token); 16039 } 16040 } 16041 } 16042 String publicSrcDir = null; 16043 if(!dataOnly) { 16044 final ApplicationInfo applicationInfo = p.applicationInfo; 16045 if (applicationInfo == null) { 16046 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 16047 return false; 16048 } 16049 if (p.isForwardLocked()) { 16050 publicSrcDir = applicationInfo.getBaseResourcePath(); 16051 } 16052 } 16053 // TODO: extend to measure size of split APKs 16054 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 16055 // not just the first level. 16056 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 16057 // just the primary. 16058 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 16059 16060 String apkPath; 16061 File packageDir = new File(p.codePath); 16062 16063 if (packageDir.isDirectory() && p.canHaveOatDir()) { 16064 apkPath = packageDir.getAbsolutePath(); 16065 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 16066 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 16067 libDirRoot = null; 16068 } 16069 } else { 16070 apkPath = p.baseCodePath; 16071 } 16072 16073 // TODO: triage flags as part of 26466827 16074 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 16075 try { 16076 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 16077 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 16078 } catch (InstallerException e) { 16079 return false; 16080 } 16081 16082 // Fix-up for forward-locked applications in ASEC containers. 16083 if (!isExternal(p)) { 16084 pStats.codeSize += pStats.externalCodeSize; 16085 pStats.externalCodeSize = 0L; 16086 } 16087 16088 return true; 16089 } 16090 16091 private int getUidTargetSdkVersionLockedLPr(int uid) { 16092 Object obj = mSettings.getUserIdLPr(uid); 16093 if (obj instanceof SharedUserSetting) { 16094 final SharedUserSetting sus = (SharedUserSetting) obj; 16095 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16096 final Iterator<PackageSetting> it = sus.packages.iterator(); 16097 while (it.hasNext()) { 16098 final PackageSetting ps = it.next(); 16099 if (ps.pkg != null) { 16100 int v = ps.pkg.applicationInfo.targetSdkVersion; 16101 if (v < vers) vers = v; 16102 } 16103 } 16104 return vers; 16105 } else if (obj instanceof PackageSetting) { 16106 final PackageSetting ps = (PackageSetting) obj; 16107 if (ps.pkg != null) { 16108 return ps.pkg.applicationInfo.targetSdkVersion; 16109 } 16110 } 16111 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16112 } 16113 16114 @Override 16115 public void addPreferredActivity(IntentFilter filter, int match, 16116 ComponentName[] set, ComponentName activity, int userId) { 16117 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16118 "Adding preferred"); 16119 } 16120 16121 private void addPreferredActivityInternal(IntentFilter filter, int match, 16122 ComponentName[] set, ComponentName activity, boolean always, int userId, 16123 String opname) { 16124 // writer 16125 int callingUid = Binder.getCallingUid(); 16126 enforceCrossUserPermission(callingUid, userId, 16127 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16128 if (filter.countActions() == 0) { 16129 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16130 return; 16131 } 16132 synchronized (mPackages) { 16133 if (mContext.checkCallingOrSelfPermission( 16134 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16135 != PackageManager.PERMISSION_GRANTED) { 16136 if (getUidTargetSdkVersionLockedLPr(callingUid) 16137 < Build.VERSION_CODES.FROYO) { 16138 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16139 + callingUid); 16140 return; 16141 } 16142 mContext.enforceCallingOrSelfPermission( 16143 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16144 } 16145 16146 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16147 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16148 + userId + ":"); 16149 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16150 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16151 scheduleWritePackageRestrictionsLocked(userId); 16152 } 16153 } 16154 16155 @Override 16156 public void replacePreferredActivity(IntentFilter filter, int match, 16157 ComponentName[] set, ComponentName activity, int userId) { 16158 if (filter.countActions() != 1) { 16159 throw new IllegalArgumentException( 16160 "replacePreferredActivity expects filter to have only 1 action."); 16161 } 16162 if (filter.countDataAuthorities() != 0 16163 || filter.countDataPaths() != 0 16164 || filter.countDataSchemes() > 1 16165 || filter.countDataTypes() != 0) { 16166 throw new IllegalArgumentException( 16167 "replacePreferredActivity expects filter to have no data authorities, " + 16168 "paths, or types; and at most one scheme."); 16169 } 16170 16171 final int callingUid = Binder.getCallingUid(); 16172 enforceCrossUserPermission(callingUid, userId, 16173 true /* requireFullPermission */, false /* checkShell */, 16174 "replace preferred activity"); 16175 synchronized (mPackages) { 16176 if (mContext.checkCallingOrSelfPermission( 16177 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16178 != PackageManager.PERMISSION_GRANTED) { 16179 if (getUidTargetSdkVersionLockedLPr(callingUid) 16180 < Build.VERSION_CODES.FROYO) { 16181 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16182 + Binder.getCallingUid()); 16183 return; 16184 } 16185 mContext.enforceCallingOrSelfPermission( 16186 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16187 } 16188 16189 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16190 if (pir != null) { 16191 // Get all of the existing entries that exactly match this filter. 16192 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16193 if (existing != null && existing.size() == 1) { 16194 PreferredActivity cur = existing.get(0); 16195 if (DEBUG_PREFERRED) { 16196 Slog.i(TAG, "Checking replace of preferred:"); 16197 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16198 if (!cur.mPref.mAlways) { 16199 Slog.i(TAG, " -- CUR; not mAlways!"); 16200 } else { 16201 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16202 Slog.i(TAG, " -- CUR: mSet=" 16203 + Arrays.toString(cur.mPref.mSetComponents)); 16204 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16205 Slog.i(TAG, " -- NEW: mMatch=" 16206 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16207 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16208 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16209 } 16210 } 16211 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16212 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16213 && cur.mPref.sameSet(set)) { 16214 // Setting the preferred activity to what it happens to be already 16215 if (DEBUG_PREFERRED) { 16216 Slog.i(TAG, "Replacing with same preferred activity " 16217 + cur.mPref.mShortComponent + " for user " 16218 + userId + ":"); 16219 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16220 } 16221 return; 16222 } 16223 } 16224 16225 if (existing != null) { 16226 if (DEBUG_PREFERRED) { 16227 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16228 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16229 } 16230 for (int i = 0; i < existing.size(); i++) { 16231 PreferredActivity pa = existing.get(i); 16232 if (DEBUG_PREFERRED) { 16233 Slog.i(TAG, "Removing existing preferred activity " 16234 + pa.mPref.mComponent + ":"); 16235 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16236 } 16237 pir.removeFilter(pa); 16238 } 16239 } 16240 } 16241 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16242 "Replacing preferred"); 16243 } 16244 } 16245 16246 @Override 16247 public void clearPackagePreferredActivities(String packageName) { 16248 final int uid = Binder.getCallingUid(); 16249 // writer 16250 synchronized (mPackages) { 16251 PackageParser.Package pkg = mPackages.get(packageName); 16252 if (pkg == null || pkg.applicationInfo.uid != uid) { 16253 if (mContext.checkCallingOrSelfPermission( 16254 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16255 != PackageManager.PERMISSION_GRANTED) { 16256 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16257 < Build.VERSION_CODES.FROYO) { 16258 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16259 + Binder.getCallingUid()); 16260 return; 16261 } 16262 mContext.enforceCallingOrSelfPermission( 16263 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16264 } 16265 } 16266 16267 int user = UserHandle.getCallingUserId(); 16268 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16269 scheduleWritePackageRestrictionsLocked(user); 16270 } 16271 } 16272 } 16273 16274 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16275 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16276 ArrayList<PreferredActivity> removed = null; 16277 boolean changed = false; 16278 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16279 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16280 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16281 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16282 continue; 16283 } 16284 Iterator<PreferredActivity> it = pir.filterIterator(); 16285 while (it.hasNext()) { 16286 PreferredActivity pa = it.next(); 16287 // Mark entry for removal only if it matches the package name 16288 // and the entry is of type "always". 16289 if (packageName == null || 16290 (pa.mPref.mComponent.getPackageName().equals(packageName) 16291 && pa.mPref.mAlways)) { 16292 if (removed == null) { 16293 removed = new ArrayList<PreferredActivity>(); 16294 } 16295 removed.add(pa); 16296 } 16297 } 16298 if (removed != null) { 16299 for (int j=0; j<removed.size(); j++) { 16300 PreferredActivity pa = removed.get(j); 16301 pir.removeFilter(pa); 16302 } 16303 changed = true; 16304 } 16305 } 16306 return changed; 16307 } 16308 16309 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16310 private void clearIntentFilterVerificationsLPw(int userId) { 16311 final int packageCount = mPackages.size(); 16312 for (int i = 0; i < packageCount; i++) { 16313 PackageParser.Package pkg = mPackages.valueAt(i); 16314 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16315 } 16316 } 16317 16318 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16319 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16320 if (userId == UserHandle.USER_ALL) { 16321 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16322 sUserManager.getUserIds())) { 16323 for (int oneUserId : sUserManager.getUserIds()) { 16324 scheduleWritePackageRestrictionsLocked(oneUserId); 16325 } 16326 } 16327 } else { 16328 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16329 scheduleWritePackageRestrictionsLocked(userId); 16330 } 16331 } 16332 } 16333 16334 void clearDefaultBrowserIfNeeded(String packageName) { 16335 for (int oneUserId : sUserManager.getUserIds()) { 16336 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16337 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16338 if (packageName.equals(defaultBrowserPackageName)) { 16339 setDefaultBrowserPackageName(null, oneUserId); 16340 } 16341 } 16342 } 16343 16344 @Override 16345 public void resetApplicationPreferences(int userId) { 16346 mContext.enforceCallingOrSelfPermission( 16347 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16348 // writer 16349 synchronized (mPackages) { 16350 final long identity = Binder.clearCallingIdentity(); 16351 try { 16352 clearPackagePreferredActivitiesLPw(null, userId); 16353 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16354 // TODO: We have to reset the default SMS and Phone. This requires 16355 // significant refactoring to keep all default apps in the package 16356 // manager (cleaner but more work) or have the services provide 16357 // callbacks to the package manager to request a default app reset. 16358 applyFactoryDefaultBrowserLPw(userId); 16359 clearIntentFilterVerificationsLPw(userId); 16360 primeDomainVerificationsLPw(userId); 16361 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16362 scheduleWritePackageRestrictionsLocked(userId); 16363 } finally { 16364 Binder.restoreCallingIdentity(identity); 16365 } 16366 } 16367 } 16368 16369 @Override 16370 public int getPreferredActivities(List<IntentFilter> outFilters, 16371 List<ComponentName> outActivities, String packageName) { 16372 16373 int num = 0; 16374 final int userId = UserHandle.getCallingUserId(); 16375 // reader 16376 synchronized (mPackages) { 16377 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16378 if (pir != null) { 16379 final Iterator<PreferredActivity> it = pir.filterIterator(); 16380 while (it.hasNext()) { 16381 final PreferredActivity pa = it.next(); 16382 if (packageName == null 16383 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16384 && pa.mPref.mAlways)) { 16385 if (outFilters != null) { 16386 outFilters.add(new IntentFilter(pa)); 16387 } 16388 if (outActivities != null) { 16389 outActivities.add(pa.mPref.mComponent); 16390 } 16391 } 16392 } 16393 } 16394 } 16395 16396 return num; 16397 } 16398 16399 @Override 16400 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16401 int userId) { 16402 int callingUid = Binder.getCallingUid(); 16403 if (callingUid != Process.SYSTEM_UID) { 16404 throw new SecurityException( 16405 "addPersistentPreferredActivity can only be run by the system"); 16406 } 16407 if (filter.countActions() == 0) { 16408 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16409 return; 16410 } 16411 synchronized (mPackages) { 16412 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16413 ":"); 16414 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16415 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16416 new PersistentPreferredActivity(filter, activity)); 16417 scheduleWritePackageRestrictionsLocked(userId); 16418 } 16419 } 16420 16421 @Override 16422 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16423 int callingUid = Binder.getCallingUid(); 16424 if (callingUid != Process.SYSTEM_UID) { 16425 throw new SecurityException( 16426 "clearPackagePersistentPreferredActivities can only be run by the system"); 16427 } 16428 ArrayList<PersistentPreferredActivity> removed = null; 16429 boolean changed = false; 16430 synchronized (mPackages) { 16431 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16432 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16433 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16434 .valueAt(i); 16435 if (userId != thisUserId) { 16436 continue; 16437 } 16438 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16439 while (it.hasNext()) { 16440 PersistentPreferredActivity ppa = it.next(); 16441 // Mark entry for removal only if it matches the package name. 16442 if (ppa.mComponent.getPackageName().equals(packageName)) { 16443 if (removed == null) { 16444 removed = new ArrayList<PersistentPreferredActivity>(); 16445 } 16446 removed.add(ppa); 16447 } 16448 } 16449 if (removed != null) { 16450 for (int j=0; j<removed.size(); j++) { 16451 PersistentPreferredActivity ppa = removed.get(j); 16452 ppir.removeFilter(ppa); 16453 } 16454 changed = true; 16455 } 16456 } 16457 16458 if (changed) { 16459 scheduleWritePackageRestrictionsLocked(userId); 16460 } 16461 } 16462 } 16463 16464 /** 16465 * Common machinery for picking apart a restored XML blob and passing 16466 * it to a caller-supplied functor to be applied to the running system. 16467 */ 16468 private void restoreFromXml(XmlPullParser parser, int userId, 16469 String expectedStartTag, BlobXmlRestorer functor) 16470 throws IOException, XmlPullParserException { 16471 int type; 16472 while ((type = parser.next()) != XmlPullParser.START_TAG 16473 && type != XmlPullParser.END_DOCUMENT) { 16474 } 16475 if (type != XmlPullParser.START_TAG) { 16476 // oops didn't find a start tag?! 16477 if (DEBUG_BACKUP) { 16478 Slog.e(TAG, "Didn't find start tag during restore"); 16479 } 16480 return; 16481 } 16482Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16483 // this is supposed to be TAG_PREFERRED_BACKUP 16484 if (!expectedStartTag.equals(parser.getName())) { 16485 if (DEBUG_BACKUP) { 16486 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16487 } 16488 return; 16489 } 16490 16491 // skip interfering stuff, then we're aligned with the backing implementation 16492 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16493Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16494 functor.apply(parser, userId); 16495 } 16496 16497 private interface BlobXmlRestorer { 16498 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16499 } 16500 16501 /** 16502 * Non-Binder method, support for the backup/restore mechanism: write the 16503 * full set of preferred activities in its canonical XML format. Returns the 16504 * XML output as a byte array, or null if there is none. 16505 */ 16506 @Override 16507 public byte[] getPreferredActivityBackup(int userId) { 16508 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16509 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16510 } 16511 16512 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16513 try { 16514 final XmlSerializer serializer = new FastXmlSerializer(); 16515 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16516 serializer.startDocument(null, true); 16517 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16518 16519 synchronized (mPackages) { 16520 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16521 } 16522 16523 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16524 serializer.endDocument(); 16525 serializer.flush(); 16526 } catch (Exception e) { 16527 if (DEBUG_BACKUP) { 16528 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16529 } 16530 return null; 16531 } 16532 16533 return dataStream.toByteArray(); 16534 } 16535 16536 @Override 16537 public void restorePreferredActivities(byte[] backup, int userId) { 16538 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16539 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16540 } 16541 16542 try { 16543 final XmlPullParser parser = Xml.newPullParser(); 16544 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16545 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16546 new BlobXmlRestorer() { 16547 @Override 16548 public void apply(XmlPullParser parser, int userId) 16549 throws XmlPullParserException, IOException { 16550 synchronized (mPackages) { 16551 mSettings.readPreferredActivitiesLPw(parser, userId); 16552 } 16553 } 16554 } ); 16555 } catch (Exception e) { 16556 if (DEBUG_BACKUP) { 16557 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16558 } 16559 } 16560 } 16561 16562 /** 16563 * Non-Binder method, support for the backup/restore mechanism: write the 16564 * default browser (etc) settings in its canonical XML format. Returns the default 16565 * browser XML representation as a byte array, or null if there is none. 16566 */ 16567 @Override 16568 public byte[] getDefaultAppsBackup(int userId) { 16569 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16570 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16571 } 16572 16573 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16574 try { 16575 final XmlSerializer serializer = new FastXmlSerializer(); 16576 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16577 serializer.startDocument(null, true); 16578 serializer.startTag(null, TAG_DEFAULT_APPS); 16579 16580 synchronized (mPackages) { 16581 mSettings.writeDefaultAppsLPr(serializer, userId); 16582 } 16583 16584 serializer.endTag(null, TAG_DEFAULT_APPS); 16585 serializer.endDocument(); 16586 serializer.flush(); 16587 } catch (Exception e) { 16588 if (DEBUG_BACKUP) { 16589 Slog.e(TAG, "Unable to write default apps for backup", e); 16590 } 16591 return null; 16592 } 16593 16594 return dataStream.toByteArray(); 16595 } 16596 16597 @Override 16598 public void restoreDefaultApps(byte[] backup, int userId) { 16599 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16600 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16601 } 16602 16603 try { 16604 final XmlPullParser parser = Xml.newPullParser(); 16605 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16606 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16607 new BlobXmlRestorer() { 16608 @Override 16609 public void apply(XmlPullParser parser, int userId) 16610 throws XmlPullParserException, IOException { 16611 synchronized (mPackages) { 16612 mSettings.readDefaultAppsLPw(parser, userId); 16613 } 16614 } 16615 } ); 16616 } catch (Exception e) { 16617 if (DEBUG_BACKUP) { 16618 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16619 } 16620 } 16621 } 16622 16623 @Override 16624 public byte[] getIntentFilterVerificationBackup(int userId) { 16625 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16626 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16627 } 16628 16629 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16630 try { 16631 final XmlSerializer serializer = new FastXmlSerializer(); 16632 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16633 serializer.startDocument(null, true); 16634 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16635 16636 synchronized (mPackages) { 16637 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16638 } 16639 16640 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16641 serializer.endDocument(); 16642 serializer.flush(); 16643 } catch (Exception e) { 16644 if (DEBUG_BACKUP) { 16645 Slog.e(TAG, "Unable to write default apps for backup", e); 16646 } 16647 return null; 16648 } 16649 16650 return dataStream.toByteArray(); 16651 } 16652 16653 @Override 16654 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16655 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16656 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16657 } 16658 16659 try { 16660 final XmlPullParser parser = Xml.newPullParser(); 16661 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16662 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16663 new BlobXmlRestorer() { 16664 @Override 16665 public void apply(XmlPullParser parser, int userId) 16666 throws XmlPullParserException, IOException { 16667 synchronized (mPackages) { 16668 mSettings.readAllDomainVerificationsLPr(parser, userId); 16669 mSettings.writeLPr(); 16670 } 16671 } 16672 } ); 16673 } catch (Exception e) { 16674 if (DEBUG_BACKUP) { 16675 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16676 } 16677 } 16678 } 16679 16680 @Override 16681 public byte[] getPermissionGrantBackup(int userId) { 16682 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16683 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16684 } 16685 16686 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16687 try { 16688 final XmlSerializer serializer = new FastXmlSerializer(); 16689 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16690 serializer.startDocument(null, true); 16691 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16692 16693 synchronized (mPackages) { 16694 serializeRuntimePermissionGrantsLPr(serializer, userId); 16695 } 16696 16697 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16698 serializer.endDocument(); 16699 serializer.flush(); 16700 } catch (Exception e) { 16701 if (DEBUG_BACKUP) { 16702 Slog.e(TAG, "Unable to write default apps for backup", e); 16703 } 16704 return null; 16705 } 16706 16707 return dataStream.toByteArray(); 16708 } 16709 16710 @Override 16711 public void restorePermissionGrants(byte[] backup, int userId) { 16712 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16713 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16714 } 16715 16716 try { 16717 final XmlPullParser parser = Xml.newPullParser(); 16718 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16719 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16720 new BlobXmlRestorer() { 16721 @Override 16722 public void apply(XmlPullParser parser, int userId) 16723 throws XmlPullParserException, IOException { 16724 synchronized (mPackages) { 16725 processRestoredPermissionGrantsLPr(parser, userId); 16726 } 16727 } 16728 } ); 16729 } catch (Exception e) { 16730 if (DEBUG_BACKUP) { 16731 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16732 } 16733 } 16734 } 16735 16736 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16737 throws IOException { 16738 serializer.startTag(null, TAG_ALL_GRANTS); 16739 16740 final int N = mSettings.mPackages.size(); 16741 for (int i = 0; i < N; i++) { 16742 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16743 boolean pkgGrantsKnown = false; 16744 16745 PermissionsState packagePerms = ps.getPermissionsState(); 16746 16747 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16748 final int grantFlags = state.getFlags(); 16749 // only look at grants that are not system/policy fixed 16750 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16751 final boolean isGranted = state.isGranted(); 16752 // And only back up the user-twiddled state bits 16753 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16754 final String packageName = mSettings.mPackages.keyAt(i); 16755 if (!pkgGrantsKnown) { 16756 serializer.startTag(null, TAG_GRANT); 16757 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16758 pkgGrantsKnown = true; 16759 } 16760 16761 final boolean userSet = 16762 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16763 final boolean userFixed = 16764 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16765 final boolean revoke = 16766 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16767 16768 serializer.startTag(null, TAG_PERMISSION); 16769 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16770 if (isGranted) { 16771 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16772 } 16773 if (userSet) { 16774 serializer.attribute(null, ATTR_USER_SET, "true"); 16775 } 16776 if (userFixed) { 16777 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16778 } 16779 if (revoke) { 16780 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16781 } 16782 serializer.endTag(null, TAG_PERMISSION); 16783 } 16784 } 16785 } 16786 16787 if (pkgGrantsKnown) { 16788 serializer.endTag(null, TAG_GRANT); 16789 } 16790 } 16791 16792 serializer.endTag(null, TAG_ALL_GRANTS); 16793 } 16794 16795 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16796 throws XmlPullParserException, IOException { 16797 String pkgName = null; 16798 int outerDepth = parser.getDepth(); 16799 int type; 16800 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16801 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16802 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16803 continue; 16804 } 16805 16806 final String tagName = parser.getName(); 16807 if (tagName.equals(TAG_GRANT)) { 16808 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16809 if (DEBUG_BACKUP) { 16810 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16811 } 16812 } else if (tagName.equals(TAG_PERMISSION)) { 16813 16814 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16815 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16816 16817 int newFlagSet = 0; 16818 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16819 newFlagSet |= FLAG_PERMISSION_USER_SET; 16820 } 16821 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16822 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16823 } 16824 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16825 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16826 } 16827 if (DEBUG_BACKUP) { 16828 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16829 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16830 } 16831 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16832 if (ps != null) { 16833 // Already installed so we apply the grant immediately 16834 if (DEBUG_BACKUP) { 16835 Slog.v(TAG, " + already installed; applying"); 16836 } 16837 PermissionsState perms = ps.getPermissionsState(); 16838 BasePermission bp = mSettings.mPermissions.get(permName); 16839 if (bp != null) { 16840 if (isGranted) { 16841 perms.grantRuntimePermission(bp, userId); 16842 } 16843 if (newFlagSet != 0) { 16844 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16845 } 16846 } 16847 } else { 16848 // Need to wait for post-restore install to apply the grant 16849 if (DEBUG_BACKUP) { 16850 Slog.v(TAG, " - not yet installed; saving for later"); 16851 } 16852 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16853 isGranted, newFlagSet, userId); 16854 } 16855 } else { 16856 PackageManagerService.reportSettingsProblem(Log.WARN, 16857 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16858 XmlUtils.skipCurrentTag(parser); 16859 } 16860 } 16861 16862 scheduleWriteSettingsLocked(); 16863 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16864 } 16865 16866 @Override 16867 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16868 int sourceUserId, int targetUserId, int flags) { 16869 mContext.enforceCallingOrSelfPermission( 16870 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16871 int callingUid = Binder.getCallingUid(); 16872 enforceOwnerRights(ownerPackage, callingUid); 16873 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16874 if (intentFilter.countActions() == 0) { 16875 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16876 return; 16877 } 16878 synchronized (mPackages) { 16879 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16880 ownerPackage, targetUserId, flags); 16881 CrossProfileIntentResolver resolver = 16882 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16883 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16884 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16885 if (existing != null) { 16886 int size = existing.size(); 16887 for (int i = 0; i < size; i++) { 16888 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16889 return; 16890 } 16891 } 16892 } 16893 resolver.addFilter(newFilter); 16894 scheduleWritePackageRestrictionsLocked(sourceUserId); 16895 } 16896 } 16897 16898 @Override 16899 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16900 mContext.enforceCallingOrSelfPermission( 16901 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16902 int callingUid = Binder.getCallingUid(); 16903 enforceOwnerRights(ownerPackage, callingUid); 16904 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16905 synchronized (mPackages) { 16906 CrossProfileIntentResolver resolver = 16907 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16908 ArraySet<CrossProfileIntentFilter> set = 16909 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16910 for (CrossProfileIntentFilter filter : set) { 16911 if (filter.getOwnerPackage().equals(ownerPackage)) { 16912 resolver.removeFilter(filter); 16913 } 16914 } 16915 scheduleWritePackageRestrictionsLocked(sourceUserId); 16916 } 16917 } 16918 16919 // Enforcing that callingUid is owning pkg on userId 16920 private void enforceOwnerRights(String pkg, int callingUid) { 16921 // The system owns everything. 16922 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16923 return; 16924 } 16925 int callingUserId = UserHandle.getUserId(callingUid); 16926 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16927 if (pi == null) { 16928 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16929 + callingUserId); 16930 } 16931 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16932 throw new SecurityException("Calling uid " + callingUid 16933 + " does not own package " + pkg); 16934 } 16935 } 16936 16937 @Override 16938 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16939 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16940 } 16941 16942 private Intent getHomeIntent() { 16943 Intent intent = new Intent(Intent.ACTION_MAIN); 16944 intent.addCategory(Intent.CATEGORY_HOME); 16945 return intent; 16946 } 16947 16948 private IntentFilter getHomeFilter() { 16949 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16950 filter.addCategory(Intent.CATEGORY_HOME); 16951 filter.addCategory(Intent.CATEGORY_DEFAULT); 16952 return filter; 16953 } 16954 16955 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16956 int userId) { 16957 Intent intent = getHomeIntent(); 16958 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16959 PackageManager.GET_META_DATA, userId); 16960 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16961 true, false, false, userId); 16962 16963 allHomeCandidates.clear(); 16964 if (list != null) { 16965 for (ResolveInfo ri : list) { 16966 allHomeCandidates.add(ri); 16967 } 16968 } 16969 return (preferred == null || preferred.activityInfo == null) 16970 ? null 16971 : new ComponentName(preferred.activityInfo.packageName, 16972 preferred.activityInfo.name); 16973 } 16974 16975 @Override 16976 public void setHomeActivity(ComponentName comp, int userId) { 16977 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16978 getHomeActivitiesAsUser(homeActivities, userId); 16979 16980 boolean found = false; 16981 16982 final int size = homeActivities.size(); 16983 final ComponentName[] set = new ComponentName[size]; 16984 for (int i = 0; i < size; i++) { 16985 final ResolveInfo candidate = homeActivities.get(i); 16986 final ActivityInfo info = candidate.activityInfo; 16987 final ComponentName activityName = new ComponentName(info.packageName, info.name); 16988 set[i] = activityName; 16989 if (!found && activityName.equals(comp)) { 16990 found = true; 16991 } 16992 } 16993 if (!found) { 16994 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 16995 + userId); 16996 } 16997 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 16998 set, comp, userId); 16999 } 17000 17001 private @Nullable String getSetupWizardPackageName() { 17002 final Intent intent = new Intent(Intent.ACTION_MAIN); 17003 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17004 17005 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17006 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17007 | MATCH_DISABLED_COMPONENTS, 17008 UserHandle.myUserId()); 17009 if (matches.size() == 1) { 17010 return matches.get(0).getComponentInfo().packageName; 17011 } else { 17012 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17013 + ": matches=" + matches); 17014 return null; 17015 } 17016 } 17017 17018 @Override 17019 public void setApplicationEnabledSetting(String appPackageName, 17020 int newState, int flags, int userId, String callingPackage) { 17021 if (!sUserManager.exists(userId)) return; 17022 if (callingPackage == null) { 17023 callingPackage = Integer.toString(Binder.getCallingUid()); 17024 } 17025 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17026 } 17027 17028 @Override 17029 public void setComponentEnabledSetting(ComponentName componentName, 17030 int newState, int flags, int userId) { 17031 if (!sUserManager.exists(userId)) return; 17032 setEnabledSetting(componentName.getPackageName(), 17033 componentName.getClassName(), newState, flags, userId, null); 17034 } 17035 17036 private void setEnabledSetting(final String packageName, String className, int newState, 17037 final int flags, int userId, String callingPackage) { 17038 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17039 || newState == COMPONENT_ENABLED_STATE_ENABLED 17040 || newState == COMPONENT_ENABLED_STATE_DISABLED 17041 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17042 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17043 throw new IllegalArgumentException("Invalid new component state: " 17044 + newState); 17045 } 17046 PackageSetting pkgSetting; 17047 final int uid = Binder.getCallingUid(); 17048 final int permission = mContext.checkCallingOrSelfPermission( 17049 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17050 enforceCrossUserPermission(uid, userId, 17051 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17052 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17053 boolean sendNow = false; 17054 boolean isApp = (className == null); 17055 String componentName = isApp ? packageName : className; 17056 int packageUid = -1; 17057 ArrayList<String> components; 17058 17059 // writer 17060 synchronized (mPackages) { 17061 pkgSetting = mSettings.mPackages.get(packageName); 17062 if (pkgSetting == null) { 17063 if (className == null) { 17064 throw new IllegalArgumentException("Unknown package: " + packageName); 17065 } 17066 throw new IllegalArgumentException( 17067 "Unknown component: " + packageName + "/" + className); 17068 } 17069 // Allow root and verify that userId is not being specified by a different user 17070 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17071 throw new SecurityException( 17072 "Permission Denial: attempt to change component state from pid=" 17073 + Binder.getCallingPid() 17074 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17075 } 17076 if (className == null) { 17077 // We're dealing with an application/package level state change 17078 if (pkgSetting.getEnabled(userId) == newState) { 17079 // Nothing to do 17080 return; 17081 } 17082 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17083 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17084 // Don't care about who enables an app. 17085 callingPackage = null; 17086 } 17087 pkgSetting.setEnabled(newState, userId, callingPackage); 17088 // pkgSetting.pkg.mSetEnabled = newState; 17089 } else { 17090 // We're dealing with a component level state change 17091 // First, verify that this is a valid class name. 17092 PackageParser.Package pkg = pkgSetting.pkg; 17093 if (pkg == null || !pkg.hasComponentClassName(className)) { 17094 if (pkg != null && 17095 pkg.applicationInfo.targetSdkVersion >= 17096 Build.VERSION_CODES.JELLY_BEAN) { 17097 throw new IllegalArgumentException("Component class " + className 17098 + " does not exist in " + packageName); 17099 } else { 17100 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17101 + className + " does not exist in " + packageName); 17102 } 17103 } 17104 switch (newState) { 17105 case COMPONENT_ENABLED_STATE_ENABLED: 17106 if (!pkgSetting.enableComponentLPw(className, userId)) { 17107 return; 17108 } 17109 break; 17110 case COMPONENT_ENABLED_STATE_DISABLED: 17111 if (!pkgSetting.disableComponentLPw(className, userId)) { 17112 return; 17113 } 17114 break; 17115 case COMPONENT_ENABLED_STATE_DEFAULT: 17116 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17117 return; 17118 } 17119 break; 17120 default: 17121 Slog.e(TAG, "Invalid new component state: " + newState); 17122 return; 17123 } 17124 } 17125 scheduleWritePackageRestrictionsLocked(userId); 17126 components = mPendingBroadcasts.get(userId, packageName); 17127 final boolean newPackage = components == null; 17128 if (newPackage) { 17129 components = new ArrayList<String>(); 17130 } 17131 if (!components.contains(componentName)) { 17132 components.add(componentName); 17133 } 17134 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17135 sendNow = true; 17136 // Purge entry from pending broadcast list if another one exists already 17137 // since we are sending one right away. 17138 mPendingBroadcasts.remove(userId, packageName); 17139 } else { 17140 if (newPackage) { 17141 mPendingBroadcasts.put(userId, packageName, components); 17142 } 17143 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17144 // Schedule a message 17145 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17146 } 17147 } 17148 } 17149 17150 long callingId = Binder.clearCallingIdentity(); 17151 try { 17152 if (sendNow) { 17153 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17154 sendPackageChangedBroadcast(packageName, 17155 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17156 } 17157 } finally { 17158 Binder.restoreCallingIdentity(callingId); 17159 } 17160 } 17161 17162 @Override 17163 public void flushPackageRestrictionsAsUser(int userId) { 17164 if (!sUserManager.exists(userId)) { 17165 return; 17166 } 17167 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17168 false /* checkShell */, "flushPackageRestrictions"); 17169 synchronized (mPackages) { 17170 mSettings.writePackageRestrictionsLPr(userId); 17171 mDirtyUsers.remove(userId); 17172 if (mDirtyUsers.isEmpty()) { 17173 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17174 } 17175 } 17176 } 17177 17178 private void sendPackageChangedBroadcast(String packageName, 17179 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17180 if (DEBUG_INSTALL) 17181 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17182 + componentNames); 17183 Bundle extras = new Bundle(4); 17184 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17185 String nameList[] = new String[componentNames.size()]; 17186 componentNames.toArray(nameList); 17187 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17188 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17189 extras.putInt(Intent.EXTRA_UID, packageUid); 17190 // If this is not reporting a change of the overall package, then only send it 17191 // to registered receivers. We don't want to launch a swath of apps for every 17192 // little component state change. 17193 final int flags = !componentNames.contains(packageName) 17194 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17195 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17196 new int[] {UserHandle.getUserId(packageUid)}); 17197 } 17198 17199 @Override 17200 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17201 if (!sUserManager.exists(userId)) return; 17202 final int uid = Binder.getCallingUid(); 17203 final int permission = mContext.checkCallingOrSelfPermission( 17204 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17205 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17206 enforceCrossUserPermission(uid, userId, 17207 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17208 // writer 17209 synchronized (mPackages) { 17210 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17211 allowedByPermission, uid, userId)) { 17212 scheduleWritePackageRestrictionsLocked(userId); 17213 } 17214 } 17215 } 17216 17217 @Override 17218 public String getInstallerPackageName(String packageName) { 17219 // reader 17220 synchronized (mPackages) { 17221 return mSettings.getInstallerPackageNameLPr(packageName); 17222 } 17223 } 17224 17225 @Override 17226 public int getApplicationEnabledSetting(String packageName, int userId) { 17227 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17228 int uid = Binder.getCallingUid(); 17229 enforceCrossUserPermission(uid, userId, 17230 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17231 // reader 17232 synchronized (mPackages) { 17233 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17234 } 17235 } 17236 17237 @Override 17238 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17239 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17240 int uid = Binder.getCallingUid(); 17241 enforceCrossUserPermission(uid, userId, 17242 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17243 // reader 17244 synchronized (mPackages) { 17245 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17246 } 17247 } 17248 17249 @Override 17250 public void enterSafeMode() { 17251 enforceSystemOrRoot("Only the system can request entering safe mode"); 17252 17253 if (!mSystemReady) { 17254 mSafeMode = true; 17255 } 17256 } 17257 17258 @Override 17259 public void systemReady() { 17260 mSystemReady = true; 17261 17262 // Read the compatibilty setting when the system is ready. 17263 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17264 mContext.getContentResolver(), 17265 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17266 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17267 if (DEBUG_SETTINGS) { 17268 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17269 } 17270 17271 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17272 17273 synchronized (mPackages) { 17274 // Verify that all of the preferred activity components actually 17275 // exist. It is possible for applications to be updated and at 17276 // that point remove a previously declared activity component that 17277 // had been set as a preferred activity. We try to clean this up 17278 // the next time we encounter that preferred activity, but it is 17279 // possible for the user flow to never be able to return to that 17280 // situation so here we do a sanity check to make sure we haven't 17281 // left any junk around. 17282 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17283 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17284 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17285 removed.clear(); 17286 for (PreferredActivity pa : pir.filterSet()) { 17287 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17288 removed.add(pa); 17289 } 17290 } 17291 if (removed.size() > 0) { 17292 for (int r=0; r<removed.size(); r++) { 17293 PreferredActivity pa = removed.get(r); 17294 Slog.w(TAG, "Removing dangling preferred activity: " 17295 + pa.mPref.mComponent); 17296 pir.removeFilter(pa); 17297 } 17298 mSettings.writePackageRestrictionsLPr( 17299 mSettings.mPreferredActivities.keyAt(i)); 17300 } 17301 } 17302 17303 for (int userId : UserManagerService.getInstance().getUserIds()) { 17304 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17305 grantPermissionsUserIds = ArrayUtils.appendInt( 17306 grantPermissionsUserIds, userId); 17307 } 17308 } 17309 } 17310 sUserManager.systemReady(); 17311 17312 // If we upgraded grant all default permissions before kicking off. 17313 for (int userId : grantPermissionsUserIds) { 17314 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17315 } 17316 17317 // Kick off any messages waiting for system ready 17318 if (mPostSystemReadyMessages != null) { 17319 for (Message msg : mPostSystemReadyMessages) { 17320 msg.sendToTarget(); 17321 } 17322 mPostSystemReadyMessages = null; 17323 } 17324 17325 // Watch for external volumes that come and go over time 17326 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17327 storage.registerListener(mStorageListener); 17328 17329 mInstallerService.systemReady(); 17330 mPackageDexOptimizer.systemReady(); 17331 17332 MountServiceInternal mountServiceInternal = LocalServices.getService( 17333 MountServiceInternal.class); 17334 mountServiceInternal.addExternalStoragePolicy( 17335 new MountServiceInternal.ExternalStorageMountPolicy() { 17336 @Override 17337 public int getMountMode(int uid, String packageName) { 17338 if (Process.isIsolated(uid)) { 17339 return Zygote.MOUNT_EXTERNAL_NONE; 17340 } 17341 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17342 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17343 } 17344 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17345 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17346 } 17347 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17348 return Zygote.MOUNT_EXTERNAL_READ; 17349 } 17350 return Zygote.MOUNT_EXTERNAL_WRITE; 17351 } 17352 17353 @Override 17354 public boolean hasExternalStorage(int uid, String packageName) { 17355 return true; 17356 } 17357 }); 17358 } 17359 17360 @Override 17361 public boolean isSafeMode() { 17362 return mSafeMode; 17363 } 17364 17365 @Override 17366 public boolean hasSystemUidErrors() { 17367 return mHasSystemUidErrors; 17368 } 17369 17370 static String arrayToString(int[] array) { 17371 StringBuffer buf = new StringBuffer(128); 17372 buf.append('['); 17373 if (array != null) { 17374 for (int i=0; i<array.length; i++) { 17375 if (i > 0) buf.append(", "); 17376 buf.append(array[i]); 17377 } 17378 } 17379 buf.append(']'); 17380 return buf.toString(); 17381 } 17382 17383 static class DumpState { 17384 public static final int DUMP_LIBS = 1 << 0; 17385 public static final int DUMP_FEATURES = 1 << 1; 17386 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17387 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17388 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17389 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17390 public static final int DUMP_PERMISSIONS = 1 << 6; 17391 public static final int DUMP_PACKAGES = 1 << 7; 17392 public static final int DUMP_SHARED_USERS = 1 << 8; 17393 public static final int DUMP_MESSAGES = 1 << 9; 17394 public static final int DUMP_PROVIDERS = 1 << 10; 17395 public static final int DUMP_VERIFIERS = 1 << 11; 17396 public static final int DUMP_PREFERRED = 1 << 12; 17397 public static final int DUMP_PREFERRED_XML = 1 << 13; 17398 public static final int DUMP_KEYSETS = 1 << 14; 17399 public static final int DUMP_VERSION = 1 << 15; 17400 public static final int DUMP_INSTALLS = 1 << 16; 17401 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17402 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17403 17404 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17405 17406 private int mTypes; 17407 17408 private int mOptions; 17409 17410 private boolean mTitlePrinted; 17411 17412 private SharedUserSetting mSharedUser; 17413 17414 public boolean isDumping(int type) { 17415 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17416 return true; 17417 } 17418 17419 return (mTypes & type) != 0; 17420 } 17421 17422 public void setDump(int type) { 17423 mTypes |= type; 17424 } 17425 17426 public boolean isOptionEnabled(int option) { 17427 return (mOptions & option) != 0; 17428 } 17429 17430 public void setOptionEnabled(int option) { 17431 mOptions |= option; 17432 } 17433 17434 public boolean onTitlePrinted() { 17435 final boolean printed = mTitlePrinted; 17436 mTitlePrinted = true; 17437 return printed; 17438 } 17439 17440 public boolean getTitlePrinted() { 17441 return mTitlePrinted; 17442 } 17443 17444 public void setTitlePrinted(boolean enabled) { 17445 mTitlePrinted = enabled; 17446 } 17447 17448 public SharedUserSetting getSharedUser() { 17449 return mSharedUser; 17450 } 17451 17452 public void setSharedUser(SharedUserSetting user) { 17453 mSharedUser = user; 17454 } 17455 } 17456 17457 @Override 17458 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17459 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17460 (new PackageManagerShellCommand(this)).exec( 17461 this, in, out, err, args, resultReceiver); 17462 } 17463 17464 @Override 17465 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17466 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17467 != PackageManager.PERMISSION_GRANTED) { 17468 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17469 + Binder.getCallingPid() 17470 + ", uid=" + Binder.getCallingUid() 17471 + " without permission " 17472 + android.Manifest.permission.DUMP); 17473 return; 17474 } 17475 17476 DumpState dumpState = new DumpState(); 17477 boolean fullPreferred = false; 17478 boolean checkin = false; 17479 17480 String packageName = null; 17481 ArraySet<String> permissionNames = null; 17482 17483 int opti = 0; 17484 while (opti < args.length) { 17485 String opt = args[opti]; 17486 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17487 break; 17488 } 17489 opti++; 17490 17491 if ("-a".equals(opt)) { 17492 // Right now we only know how to print all. 17493 } else if ("-h".equals(opt)) { 17494 pw.println("Package manager dump options:"); 17495 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17496 pw.println(" --checkin: dump for a checkin"); 17497 pw.println(" -f: print details of intent filters"); 17498 pw.println(" -h: print this help"); 17499 pw.println(" cmd may be one of:"); 17500 pw.println(" l[ibraries]: list known shared libraries"); 17501 pw.println(" f[eatures]: list device features"); 17502 pw.println(" k[eysets]: print known keysets"); 17503 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17504 pw.println(" perm[issions]: dump permissions"); 17505 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17506 pw.println(" pref[erred]: print preferred package settings"); 17507 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17508 pw.println(" prov[iders]: dump content providers"); 17509 pw.println(" p[ackages]: dump installed packages"); 17510 pw.println(" s[hared-users]: dump shared user IDs"); 17511 pw.println(" m[essages]: print collected runtime messages"); 17512 pw.println(" v[erifiers]: print package verifier info"); 17513 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17514 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17515 pw.println(" version: print database version info"); 17516 pw.println(" write: write current settings now"); 17517 pw.println(" installs: details about install sessions"); 17518 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17519 pw.println(" <package.name>: info about given package"); 17520 return; 17521 } else if ("--checkin".equals(opt)) { 17522 checkin = true; 17523 } else if ("-f".equals(opt)) { 17524 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17525 } else { 17526 pw.println("Unknown argument: " + opt + "; use -h for help"); 17527 } 17528 } 17529 17530 // Is the caller requesting to dump a particular piece of data? 17531 if (opti < args.length) { 17532 String cmd = args[opti]; 17533 opti++; 17534 // Is this a package name? 17535 if ("android".equals(cmd) || cmd.contains(".")) { 17536 packageName = cmd; 17537 // When dumping a single package, we always dump all of its 17538 // filter information since the amount of data will be reasonable. 17539 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17540 } else if ("check-permission".equals(cmd)) { 17541 if (opti >= args.length) { 17542 pw.println("Error: check-permission missing permission argument"); 17543 return; 17544 } 17545 String perm = args[opti]; 17546 opti++; 17547 if (opti >= args.length) { 17548 pw.println("Error: check-permission missing package argument"); 17549 return; 17550 } 17551 String pkg = args[opti]; 17552 opti++; 17553 int user = UserHandle.getUserId(Binder.getCallingUid()); 17554 if (opti < args.length) { 17555 try { 17556 user = Integer.parseInt(args[opti]); 17557 } catch (NumberFormatException e) { 17558 pw.println("Error: check-permission user argument is not a number: " 17559 + args[opti]); 17560 return; 17561 } 17562 } 17563 pw.println(checkPermission(perm, pkg, user)); 17564 return; 17565 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17566 dumpState.setDump(DumpState.DUMP_LIBS); 17567 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17568 dumpState.setDump(DumpState.DUMP_FEATURES); 17569 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17570 if (opti >= args.length) { 17571 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17572 | DumpState.DUMP_SERVICE_RESOLVERS 17573 | DumpState.DUMP_RECEIVER_RESOLVERS 17574 | DumpState.DUMP_CONTENT_RESOLVERS); 17575 } else { 17576 while (opti < args.length) { 17577 String name = args[opti]; 17578 if ("a".equals(name) || "activity".equals(name)) { 17579 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17580 } else if ("s".equals(name) || "service".equals(name)) { 17581 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17582 } else if ("r".equals(name) || "receiver".equals(name)) { 17583 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17584 } else if ("c".equals(name) || "content".equals(name)) { 17585 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17586 } else { 17587 pw.println("Error: unknown resolver table type: " + name); 17588 return; 17589 } 17590 opti++; 17591 } 17592 } 17593 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17594 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17595 } else if ("permission".equals(cmd)) { 17596 if (opti >= args.length) { 17597 pw.println("Error: permission requires permission name"); 17598 return; 17599 } 17600 permissionNames = new ArraySet<>(); 17601 while (opti < args.length) { 17602 permissionNames.add(args[opti]); 17603 opti++; 17604 } 17605 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17606 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17607 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17608 dumpState.setDump(DumpState.DUMP_PREFERRED); 17609 } else if ("preferred-xml".equals(cmd)) { 17610 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17611 if (opti < args.length && "--full".equals(args[opti])) { 17612 fullPreferred = true; 17613 opti++; 17614 } 17615 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17616 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17617 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17618 dumpState.setDump(DumpState.DUMP_PACKAGES); 17619 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17620 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17621 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17622 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17623 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17624 dumpState.setDump(DumpState.DUMP_MESSAGES); 17625 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17626 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17627 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17628 || "intent-filter-verifiers".equals(cmd)) { 17629 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17630 } else if ("version".equals(cmd)) { 17631 dumpState.setDump(DumpState.DUMP_VERSION); 17632 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17633 dumpState.setDump(DumpState.DUMP_KEYSETS); 17634 } else if ("installs".equals(cmd)) { 17635 dumpState.setDump(DumpState.DUMP_INSTALLS); 17636 } else if ("write".equals(cmd)) { 17637 synchronized (mPackages) { 17638 mSettings.writeLPr(); 17639 pw.println("Settings written."); 17640 return; 17641 } 17642 } 17643 } 17644 17645 if (checkin) { 17646 pw.println("vers,1"); 17647 } 17648 17649 // reader 17650 synchronized (mPackages) { 17651 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17652 if (!checkin) { 17653 if (dumpState.onTitlePrinted()) 17654 pw.println(); 17655 pw.println("Database versions:"); 17656 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17657 } 17658 } 17659 17660 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17661 if (!checkin) { 17662 if (dumpState.onTitlePrinted()) 17663 pw.println(); 17664 pw.println("Verifiers:"); 17665 pw.print(" Required: "); 17666 pw.print(mRequiredVerifierPackage); 17667 pw.print(" (uid="); 17668 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17669 UserHandle.USER_SYSTEM)); 17670 pw.println(")"); 17671 } else if (mRequiredVerifierPackage != null) { 17672 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17673 pw.print(","); 17674 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17675 UserHandle.USER_SYSTEM)); 17676 } 17677 } 17678 17679 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17680 packageName == null) { 17681 if (mIntentFilterVerifierComponent != null) { 17682 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17683 if (!checkin) { 17684 if (dumpState.onTitlePrinted()) 17685 pw.println(); 17686 pw.println("Intent Filter Verifier:"); 17687 pw.print(" Using: "); 17688 pw.print(verifierPackageName); 17689 pw.print(" (uid="); 17690 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17691 UserHandle.USER_SYSTEM)); 17692 pw.println(")"); 17693 } else if (verifierPackageName != null) { 17694 pw.print("ifv,"); pw.print(verifierPackageName); 17695 pw.print(","); 17696 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17697 UserHandle.USER_SYSTEM)); 17698 } 17699 } else { 17700 pw.println(); 17701 pw.println("No Intent Filter Verifier available!"); 17702 } 17703 } 17704 17705 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17706 boolean printedHeader = false; 17707 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17708 while (it.hasNext()) { 17709 String name = it.next(); 17710 SharedLibraryEntry ent = mSharedLibraries.get(name); 17711 if (!checkin) { 17712 if (!printedHeader) { 17713 if (dumpState.onTitlePrinted()) 17714 pw.println(); 17715 pw.println("Libraries:"); 17716 printedHeader = true; 17717 } 17718 pw.print(" "); 17719 } else { 17720 pw.print("lib,"); 17721 } 17722 pw.print(name); 17723 if (!checkin) { 17724 pw.print(" -> "); 17725 } 17726 if (ent.path != null) { 17727 if (!checkin) { 17728 pw.print("(jar) "); 17729 pw.print(ent.path); 17730 } else { 17731 pw.print(",jar,"); 17732 pw.print(ent.path); 17733 } 17734 } else { 17735 if (!checkin) { 17736 pw.print("(apk) "); 17737 pw.print(ent.apk); 17738 } else { 17739 pw.print(",apk,"); 17740 pw.print(ent.apk); 17741 } 17742 } 17743 pw.println(); 17744 } 17745 } 17746 17747 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17748 if (dumpState.onTitlePrinted()) 17749 pw.println(); 17750 if (!checkin) { 17751 pw.println("Features:"); 17752 } 17753 17754 for (FeatureInfo feat : mAvailableFeatures.values()) { 17755 if (checkin) { 17756 pw.print("feat,"); 17757 pw.print(feat.name); 17758 pw.print(","); 17759 pw.println(feat.version); 17760 } else { 17761 pw.print(" "); 17762 pw.print(feat.name); 17763 if (feat.version > 0) { 17764 pw.print(" version="); 17765 pw.print(feat.version); 17766 } 17767 pw.println(); 17768 } 17769 } 17770 } 17771 17772 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17773 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17774 : "Activity Resolver Table:", " ", packageName, 17775 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17776 dumpState.setTitlePrinted(true); 17777 } 17778 } 17779 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17780 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17781 : "Receiver Resolver Table:", " ", packageName, 17782 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17783 dumpState.setTitlePrinted(true); 17784 } 17785 } 17786 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17787 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17788 : "Service Resolver Table:", " ", packageName, 17789 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17790 dumpState.setTitlePrinted(true); 17791 } 17792 } 17793 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17794 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17795 : "Provider Resolver Table:", " ", packageName, 17796 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17797 dumpState.setTitlePrinted(true); 17798 } 17799 } 17800 17801 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17802 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17803 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17804 int user = mSettings.mPreferredActivities.keyAt(i); 17805 if (pir.dump(pw, 17806 dumpState.getTitlePrinted() 17807 ? "\nPreferred Activities User " + user + ":" 17808 : "Preferred Activities User " + user + ":", " ", 17809 packageName, true, false)) { 17810 dumpState.setTitlePrinted(true); 17811 } 17812 } 17813 } 17814 17815 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17816 pw.flush(); 17817 FileOutputStream fout = new FileOutputStream(fd); 17818 BufferedOutputStream str = new BufferedOutputStream(fout); 17819 XmlSerializer serializer = new FastXmlSerializer(); 17820 try { 17821 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17822 serializer.startDocument(null, true); 17823 serializer.setFeature( 17824 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17825 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17826 serializer.endDocument(); 17827 serializer.flush(); 17828 } catch (IllegalArgumentException e) { 17829 pw.println("Failed writing: " + e); 17830 } catch (IllegalStateException e) { 17831 pw.println("Failed writing: " + e); 17832 } catch (IOException e) { 17833 pw.println("Failed writing: " + e); 17834 } 17835 } 17836 17837 if (!checkin 17838 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17839 && packageName == null) { 17840 pw.println(); 17841 int count = mSettings.mPackages.size(); 17842 if (count == 0) { 17843 pw.println("No applications!"); 17844 pw.println(); 17845 } else { 17846 final String prefix = " "; 17847 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17848 if (allPackageSettings.size() == 0) { 17849 pw.println("No domain preferred apps!"); 17850 pw.println(); 17851 } else { 17852 pw.println("App verification status:"); 17853 pw.println(); 17854 count = 0; 17855 for (PackageSetting ps : allPackageSettings) { 17856 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17857 if (ivi == null || ivi.getPackageName() == null) continue; 17858 pw.println(prefix + "Package: " + ivi.getPackageName()); 17859 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17860 pw.println(prefix + "Status: " + ivi.getStatusString()); 17861 pw.println(); 17862 count++; 17863 } 17864 if (count == 0) { 17865 pw.println(prefix + "No app verification established."); 17866 pw.println(); 17867 } 17868 for (int userId : sUserManager.getUserIds()) { 17869 pw.println("App linkages for user " + userId + ":"); 17870 pw.println(); 17871 count = 0; 17872 for (PackageSetting ps : allPackageSettings) { 17873 final long status = ps.getDomainVerificationStatusForUser(userId); 17874 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17875 continue; 17876 } 17877 pw.println(prefix + "Package: " + ps.name); 17878 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17879 String statusStr = IntentFilterVerificationInfo. 17880 getStatusStringFromValue(status); 17881 pw.println(prefix + "Status: " + statusStr); 17882 pw.println(); 17883 count++; 17884 } 17885 if (count == 0) { 17886 pw.println(prefix + "No configured app linkages."); 17887 pw.println(); 17888 } 17889 } 17890 } 17891 } 17892 } 17893 17894 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17895 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17896 if (packageName == null && permissionNames == null) { 17897 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17898 if (iperm == 0) { 17899 if (dumpState.onTitlePrinted()) 17900 pw.println(); 17901 pw.println("AppOp Permissions:"); 17902 } 17903 pw.print(" AppOp Permission "); 17904 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17905 pw.println(":"); 17906 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17907 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17908 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17909 } 17910 } 17911 } 17912 } 17913 17914 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17915 boolean printedSomething = false; 17916 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17917 if (packageName != null && !packageName.equals(p.info.packageName)) { 17918 continue; 17919 } 17920 if (!printedSomething) { 17921 if (dumpState.onTitlePrinted()) 17922 pw.println(); 17923 pw.println("Registered ContentProviders:"); 17924 printedSomething = true; 17925 } 17926 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17927 pw.print(" "); pw.println(p.toString()); 17928 } 17929 printedSomething = false; 17930 for (Map.Entry<String, PackageParser.Provider> entry : 17931 mProvidersByAuthority.entrySet()) { 17932 PackageParser.Provider p = entry.getValue(); 17933 if (packageName != null && !packageName.equals(p.info.packageName)) { 17934 continue; 17935 } 17936 if (!printedSomething) { 17937 if (dumpState.onTitlePrinted()) 17938 pw.println(); 17939 pw.println("ContentProvider Authorities:"); 17940 printedSomething = true; 17941 } 17942 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17943 pw.print(" "); pw.println(p.toString()); 17944 if (p.info != null && p.info.applicationInfo != null) { 17945 final String appInfo = p.info.applicationInfo.toString(); 17946 pw.print(" applicationInfo="); pw.println(appInfo); 17947 } 17948 } 17949 } 17950 17951 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17952 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17953 } 17954 17955 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17956 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17957 } 17958 17959 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17960 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17961 } 17962 17963 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17964 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17965 } 17966 17967 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17968 // XXX should handle packageName != null by dumping only install data that 17969 // the given package is involved with. 17970 if (dumpState.onTitlePrinted()) pw.println(); 17971 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17972 } 17973 17974 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17975 if (dumpState.onTitlePrinted()) pw.println(); 17976 mSettings.dumpReadMessagesLPr(pw, dumpState); 17977 17978 pw.println(); 17979 pw.println("Package warning messages:"); 17980 BufferedReader in = null; 17981 String line = null; 17982 try { 17983 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17984 while ((line = in.readLine()) != null) { 17985 if (line.contains("ignored: updated version")) continue; 17986 pw.println(line); 17987 } 17988 } catch (IOException ignored) { 17989 } finally { 17990 IoUtils.closeQuietly(in); 17991 } 17992 } 17993 17994 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17995 BufferedReader in = null; 17996 String line = null; 17997 try { 17998 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17999 while ((line = in.readLine()) != null) { 18000 if (line.contains("ignored: updated version")) continue; 18001 pw.print("msg,"); 18002 pw.println(line); 18003 } 18004 } catch (IOException ignored) { 18005 } finally { 18006 IoUtils.closeQuietly(in); 18007 } 18008 } 18009 } 18010 } 18011 18012 private String dumpDomainString(String packageName) { 18013 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18014 .getList(); 18015 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18016 18017 ArraySet<String> result = new ArraySet<>(); 18018 if (iviList.size() > 0) { 18019 for (IntentFilterVerificationInfo ivi : iviList) { 18020 for (String host : ivi.getDomains()) { 18021 result.add(host); 18022 } 18023 } 18024 } 18025 if (filters != null && filters.size() > 0) { 18026 for (IntentFilter filter : filters) { 18027 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18028 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18029 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18030 result.addAll(filter.getHostsList()); 18031 } 18032 } 18033 } 18034 18035 StringBuilder sb = new StringBuilder(result.size() * 16); 18036 for (String domain : result) { 18037 if (sb.length() > 0) sb.append(" "); 18038 sb.append(domain); 18039 } 18040 return sb.toString(); 18041 } 18042 18043 // ------- apps on sdcard specific code ------- 18044 static final boolean DEBUG_SD_INSTALL = false; 18045 18046 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18047 18048 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18049 18050 private boolean mMediaMounted = false; 18051 18052 static String getEncryptKey() { 18053 try { 18054 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18055 SD_ENCRYPTION_KEYSTORE_NAME); 18056 if (sdEncKey == null) { 18057 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18058 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18059 if (sdEncKey == null) { 18060 Slog.e(TAG, "Failed to create encryption keys"); 18061 return null; 18062 } 18063 } 18064 return sdEncKey; 18065 } catch (NoSuchAlgorithmException nsae) { 18066 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18067 return null; 18068 } catch (IOException ioe) { 18069 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18070 return null; 18071 } 18072 } 18073 18074 /* 18075 * Update media status on PackageManager. 18076 */ 18077 @Override 18078 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18079 int callingUid = Binder.getCallingUid(); 18080 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18081 throw new SecurityException("Media status can only be updated by the system"); 18082 } 18083 // reader; this apparently protects mMediaMounted, but should probably 18084 // be a different lock in that case. 18085 synchronized (mPackages) { 18086 Log.i(TAG, "Updating external media status from " 18087 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18088 + (mediaStatus ? "mounted" : "unmounted")); 18089 if (DEBUG_SD_INSTALL) 18090 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18091 + ", mMediaMounted=" + mMediaMounted); 18092 if (mediaStatus == mMediaMounted) { 18093 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18094 : 0, -1); 18095 mHandler.sendMessage(msg); 18096 return; 18097 } 18098 mMediaMounted = mediaStatus; 18099 } 18100 // Queue up an async operation since the package installation may take a 18101 // little while. 18102 mHandler.post(new Runnable() { 18103 public void run() { 18104 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18105 } 18106 }); 18107 } 18108 18109 /** 18110 * Called by MountService when the initial ASECs to scan are available. 18111 * Should block until all the ASEC containers are finished being scanned. 18112 */ 18113 public void scanAvailableAsecs() { 18114 updateExternalMediaStatusInner(true, false, false); 18115 } 18116 18117 /* 18118 * Collect information of applications on external media, map them against 18119 * existing containers and update information based on current mount status. 18120 * Please note that we always have to report status if reportStatus has been 18121 * set to true especially when unloading packages. 18122 */ 18123 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18124 boolean externalStorage) { 18125 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18126 int[] uidArr = EmptyArray.INT; 18127 18128 final String[] list = PackageHelper.getSecureContainerList(); 18129 if (ArrayUtils.isEmpty(list)) { 18130 Log.i(TAG, "No secure containers found"); 18131 } else { 18132 // Process list of secure containers and categorize them 18133 // as active or stale based on their package internal state. 18134 18135 // reader 18136 synchronized (mPackages) { 18137 for (String cid : list) { 18138 // Leave stages untouched for now; installer service owns them 18139 if (PackageInstallerService.isStageName(cid)) continue; 18140 18141 if (DEBUG_SD_INSTALL) 18142 Log.i(TAG, "Processing container " + cid); 18143 String pkgName = getAsecPackageName(cid); 18144 if (pkgName == null) { 18145 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18146 continue; 18147 } 18148 if (DEBUG_SD_INSTALL) 18149 Log.i(TAG, "Looking for pkg : " + pkgName); 18150 18151 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18152 if (ps == null) { 18153 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18154 continue; 18155 } 18156 18157 /* 18158 * Skip packages that are not external if we're unmounting 18159 * external storage. 18160 */ 18161 if (externalStorage && !isMounted && !isExternal(ps)) { 18162 continue; 18163 } 18164 18165 final AsecInstallArgs args = new AsecInstallArgs(cid, 18166 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18167 // The package status is changed only if the code path 18168 // matches between settings and the container id. 18169 if (ps.codePathString != null 18170 && ps.codePathString.startsWith(args.getCodePath())) { 18171 if (DEBUG_SD_INSTALL) { 18172 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18173 + " at code path: " + ps.codePathString); 18174 } 18175 18176 // We do have a valid package installed on sdcard 18177 processCids.put(args, ps.codePathString); 18178 final int uid = ps.appId; 18179 if (uid != -1) { 18180 uidArr = ArrayUtils.appendInt(uidArr, uid); 18181 } 18182 } else { 18183 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18184 + ps.codePathString); 18185 } 18186 } 18187 } 18188 18189 Arrays.sort(uidArr); 18190 } 18191 18192 // Process packages with valid entries. 18193 if (isMounted) { 18194 if (DEBUG_SD_INSTALL) 18195 Log.i(TAG, "Loading packages"); 18196 loadMediaPackages(processCids, uidArr, externalStorage); 18197 startCleaningPackages(); 18198 mInstallerService.onSecureContainersAvailable(); 18199 } else { 18200 if (DEBUG_SD_INSTALL) 18201 Log.i(TAG, "Unloading packages"); 18202 unloadMediaPackages(processCids, uidArr, reportStatus); 18203 } 18204 } 18205 18206 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18207 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18208 final int size = infos.size(); 18209 final String[] packageNames = new String[size]; 18210 final int[] packageUids = new int[size]; 18211 for (int i = 0; i < size; i++) { 18212 final ApplicationInfo info = infos.get(i); 18213 packageNames[i] = info.packageName; 18214 packageUids[i] = info.uid; 18215 } 18216 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18217 finishedReceiver); 18218 } 18219 18220 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18221 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18222 sendResourcesChangedBroadcast(mediaStatus, replacing, 18223 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18224 } 18225 18226 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18227 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18228 int size = pkgList.length; 18229 if (size > 0) { 18230 // Send broadcasts here 18231 Bundle extras = new Bundle(); 18232 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18233 if (uidArr != null) { 18234 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18235 } 18236 if (replacing) { 18237 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18238 } 18239 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18240 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18241 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18242 } 18243 } 18244 18245 /* 18246 * Look at potentially valid container ids from processCids If package 18247 * information doesn't match the one on record or package scanning fails, 18248 * the cid is added to list of removeCids. We currently don't delete stale 18249 * containers. 18250 */ 18251 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18252 boolean externalStorage) { 18253 ArrayList<String> pkgList = new ArrayList<String>(); 18254 Set<AsecInstallArgs> keys = processCids.keySet(); 18255 18256 for (AsecInstallArgs args : keys) { 18257 String codePath = processCids.get(args); 18258 if (DEBUG_SD_INSTALL) 18259 Log.i(TAG, "Loading container : " + args.cid); 18260 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18261 try { 18262 // Make sure there are no container errors first. 18263 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18264 Slog.e(TAG, "Failed to mount cid : " + args.cid 18265 + " when installing from sdcard"); 18266 continue; 18267 } 18268 // Check code path here. 18269 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18270 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18271 + " does not match one in settings " + codePath); 18272 continue; 18273 } 18274 // Parse package 18275 int parseFlags = mDefParseFlags; 18276 if (args.isExternalAsec()) { 18277 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18278 } 18279 if (args.isFwdLocked()) { 18280 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18281 } 18282 18283 synchronized (mInstallLock) { 18284 PackageParser.Package pkg = null; 18285 try { 18286 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 18287 } catch (PackageManagerException e) { 18288 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18289 } 18290 // Scan the package 18291 if (pkg != null) { 18292 /* 18293 * TODO why is the lock being held? doPostInstall is 18294 * called in other places without the lock. This needs 18295 * to be straightened out. 18296 */ 18297 // writer 18298 synchronized (mPackages) { 18299 retCode = PackageManager.INSTALL_SUCCEEDED; 18300 pkgList.add(pkg.packageName); 18301 // Post process args 18302 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18303 pkg.applicationInfo.uid); 18304 } 18305 } else { 18306 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18307 } 18308 } 18309 18310 } finally { 18311 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18312 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18313 } 18314 } 18315 } 18316 // writer 18317 synchronized (mPackages) { 18318 // If the platform SDK has changed since the last time we booted, 18319 // we need to re-grant app permission to catch any new ones that 18320 // appear. This is really a hack, and means that apps can in some 18321 // cases get permissions that the user didn't initially explicitly 18322 // allow... it would be nice to have some better way to handle 18323 // this situation. 18324 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18325 : mSettings.getInternalVersion(); 18326 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18327 : StorageManager.UUID_PRIVATE_INTERNAL; 18328 18329 int updateFlags = UPDATE_PERMISSIONS_ALL; 18330 if (ver.sdkVersion != mSdkVersion) { 18331 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18332 + mSdkVersion + "; regranting permissions for external"); 18333 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18334 } 18335 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18336 18337 // Yay, everything is now upgraded 18338 ver.forceCurrent(); 18339 18340 // can downgrade to reader 18341 // Persist settings 18342 mSettings.writeLPr(); 18343 } 18344 // Send a broadcast to let everyone know we are done processing 18345 if (pkgList.size() > 0) { 18346 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18347 } 18348 } 18349 18350 /* 18351 * Utility method to unload a list of specified containers 18352 */ 18353 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18354 // Just unmount all valid containers. 18355 for (AsecInstallArgs arg : cidArgs) { 18356 synchronized (mInstallLock) { 18357 arg.doPostDeleteLI(false); 18358 } 18359 } 18360 } 18361 18362 /* 18363 * Unload packages mounted on external media. This involves deleting package 18364 * data from internal structures, sending broadcasts about disabled packages, 18365 * gc'ing to free up references, unmounting all secure containers 18366 * corresponding to packages on external media, and posting a 18367 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18368 * that we always have to post this message if status has been requested no 18369 * matter what. 18370 */ 18371 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18372 final boolean reportStatus) { 18373 if (DEBUG_SD_INSTALL) 18374 Log.i(TAG, "unloading media packages"); 18375 ArrayList<String> pkgList = new ArrayList<String>(); 18376 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18377 final Set<AsecInstallArgs> keys = processCids.keySet(); 18378 for (AsecInstallArgs args : keys) { 18379 String pkgName = args.getPackageName(); 18380 if (DEBUG_SD_INSTALL) 18381 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18382 // Delete package internally 18383 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18384 synchronized (mInstallLock) { 18385 boolean res = deletePackageLI(pkgName, null, false, null, 18386 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 18387 if (res) { 18388 pkgList.add(pkgName); 18389 } else { 18390 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18391 failedList.add(args); 18392 } 18393 } 18394 } 18395 18396 // reader 18397 synchronized (mPackages) { 18398 // We didn't update the settings after removing each package; 18399 // write them now for all packages. 18400 mSettings.writeLPr(); 18401 } 18402 18403 // We have to absolutely send UPDATED_MEDIA_STATUS only 18404 // after confirming that all the receivers processed the ordered 18405 // broadcast when packages get disabled, force a gc to clean things up. 18406 // and unload all the containers. 18407 if (pkgList.size() > 0) { 18408 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18409 new IIntentReceiver.Stub() { 18410 public void performReceive(Intent intent, int resultCode, String data, 18411 Bundle extras, boolean ordered, boolean sticky, 18412 int sendingUser) throws RemoteException { 18413 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18414 reportStatus ? 1 : 0, 1, keys); 18415 mHandler.sendMessage(msg); 18416 } 18417 }); 18418 } else { 18419 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18420 keys); 18421 mHandler.sendMessage(msg); 18422 } 18423 } 18424 18425 private void loadPrivatePackages(final VolumeInfo vol) { 18426 mHandler.post(new Runnable() { 18427 @Override 18428 public void run() { 18429 loadPrivatePackagesInner(vol); 18430 } 18431 }); 18432 } 18433 18434 private void loadPrivatePackagesInner(VolumeInfo vol) { 18435 final String volumeUuid = vol.fsUuid; 18436 if (TextUtils.isEmpty(volumeUuid)) { 18437 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18438 return; 18439 } 18440 18441 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18442 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18443 18444 final VersionInfo ver; 18445 final List<PackageSetting> packages; 18446 synchronized (mPackages) { 18447 ver = mSettings.findOrCreateVersion(volumeUuid); 18448 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18449 } 18450 18451 // TODO: introduce a new concept similar to "frozen" to prevent these 18452 // apps from being launched until after data has been fully reconciled 18453 for (PackageSetting ps : packages) { 18454 synchronized (mInstallLock) { 18455 final PackageParser.Package pkg; 18456 try { 18457 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18458 loaded.add(pkg.applicationInfo); 18459 18460 } catch (PackageManagerException e) { 18461 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18462 } 18463 18464 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18465 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 18466 } 18467 } 18468 } 18469 18470 // Reconcile app data for all started/unlocked users 18471 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18472 final UserManager um = mContext.getSystemService(UserManager.class); 18473 for (UserInfo user : um.getUsers()) { 18474 final int flags; 18475 if (um.isUserUnlocked(user.id)) { 18476 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18477 } else if (um.isUserRunning(user.id)) { 18478 flags = StorageManager.FLAG_STORAGE_DE; 18479 } else { 18480 continue; 18481 } 18482 18483 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18484 reconcileAppsData(volumeUuid, user.id, flags); 18485 } 18486 18487 synchronized (mPackages) { 18488 int updateFlags = UPDATE_PERMISSIONS_ALL; 18489 if (ver.sdkVersion != mSdkVersion) { 18490 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18491 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18492 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18493 } 18494 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18495 18496 // Yay, everything is now upgraded 18497 ver.forceCurrent(); 18498 18499 mSettings.writeLPr(); 18500 } 18501 18502 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18503 sendResourcesChangedBroadcast(true, false, loaded, null); 18504 } 18505 18506 private void unloadPrivatePackages(final VolumeInfo vol) { 18507 mHandler.post(new Runnable() { 18508 @Override 18509 public void run() { 18510 unloadPrivatePackagesInner(vol); 18511 } 18512 }); 18513 } 18514 18515 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18516 final String volumeUuid = vol.fsUuid; 18517 if (TextUtils.isEmpty(volumeUuid)) { 18518 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18519 return; 18520 } 18521 18522 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18523 synchronized (mInstallLock) { 18524 synchronized (mPackages) { 18525 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18526 for (PackageSetting ps : packages) { 18527 if (ps.pkg == null) continue; 18528 18529 final ApplicationInfo info = ps.pkg.applicationInfo; 18530 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18531 if (deletePackageLI(ps.name, null, false, null, 18532 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 18533 unloaded.add(info); 18534 } else { 18535 Slog.w(TAG, "Failed to unload " + ps.codePath); 18536 } 18537 } 18538 18539 mSettings.writeLPr(); 18540 } 18541 } 18542 18543 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18544 sendResourcesChangedBroadcast(false, false, unloaded, null); 18545 } 18546 18547 /** 18548 * Examine all users present on given mounted volume, and destroy data 18549 * belonging to users that are no longer valid, or whose user ID has been 18550 * recycled. 18551 */ 18552 private void reconcileUsers(String volumeUuid) { 18553 // TODO: also reconcile DE directories 18554 final File[] files = FileUtils 18555 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18556 for (File file : files) { 18557 if (!file.isDirectory()) continue; 18558 18559 final int userId; 18560 final UserInfo info; 18561 try { 18562 userId = Integer.parseInt(file.getName()); 18563 info = sUserManager.getUserInfo(userId); 18564 } catch (NumberFormatException e) { 18565 Slog.w(TAG, "Invalid user directory " + file); 18566 continue; 18567 } 18568 18569 boolean destroyUser = false; 18570 if (info == null) { 18571 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18572 + " because no matching user was found"); 18573 destroyUser = true; 18574 } else { 18575 try { 18576 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18577 } catch (IOException e) { 18578 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18579 + " because we failed to enforce serial number: " + e); 18580 destroyUser = true; 18581 } 18582 } 18583 18584 if (destroyUser) { 18585 synchronized (mInstallLock) { 18586 try { 18587 mInstaller.removeUserDataDirs(volumeUuid, userId); 18588 } catch (InstallerException e) { 18589 Slog.w(TAG, "Failed to clean up user dirs", e); 18590 } 18591 } 18592 } 18593 } 18594 } 18595 18596 private void assertPackageKnown(String volumeUuid, String packageName) 18597 throws PackageManagerException { 18598 synchronized (mPackages) { 18599 final PackageSetting ps = mSettings.mPackages.get(packageName); 18600 if (ps == null) { 18601 throw new PackageManagerException("Package " + packageName + " is unknown"); 18602 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18603 throw new PackageManagerException( 18604 "Package " + packageName + " found on unknown volume " + volumeUuid 18605 + "; expected volume " + ps.volumeUuid); 18606 } 18607 } 18608 } 18609 18610 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18611 throws PackageManagerException { 18612 synchronized (mPackages) { 18613 final PackageSetting ps = mSettings.mPackages.get(packageName); 18614 if (ps == null) { 18615 throw new PackageManagerException("Package " + packageName + " is unknown"); 18616 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18617 throw new PackageManagerException( 18618 "Package " + packageName + " found on unknown volume " + volumeUuid 18619 + "; expected volume " + ps.volumeUuid); 18620 } else if (!ps.getInstalled(userId)) { 18621 throw new PackageManagerException( 18622 "Package " + packageName + " not installed for user " + userId); 18623 } 18624 } 18625 } 18626 18627 /** 18628 * Examine all apps present on given mounted volume, and destroy apps that 18629 * aren't expected, either due to uninstallation or reinstallation on 18630 * another volume. 18631 */ 18632 private void reconcileApps(String volumeUuid) { 18633 final File[] files = FileUtils 18634 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18635 for (File file : files) { 18636 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18637 && !PackageInstallerService.isStageName(file.getName()); 18638 if (!isPackage) { 18639 // Ignore entries which are not packages 18640 continue; 18641 } 18642 18643 try { 18644 final PackageLite pkg = PackageParser.parsePackageLite(file, 18645 PackageParser.PARSE_MUST_BE_APK); 18646 assertPackageKnown(volumeUuid, pkg.packageName); 18647 18648 } catch (PackageParserException | PackageManagerException e) { 18649 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18650 synchronized (mInstallLock) { 18651 removeCodePathLI(file); 18652 } 18653 } 18654 } 18655 } 18656 18657 /** 18658 * Reconcile all app data for the given user. 18659 * <p> 18660 * Verifies that directories exist and that ownership and labeling is 18661 * correct for all installed apps on all mounted volumes. 18662 */ 18663 void reconcileAppsData(int userId, int flags) { 18664 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18665 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18666 final String volumeUuid = vol.getFsUuid(); 18667 reconcileAppsData(volumeUuid, userId, flags); 18668 } 18669 } 18670 18671 /** 18672 * Reconcile all app data on given mounted volume. 18673 * <p> 18674 * Destroys app data that isn't expected, either due to uninstallation or 18675 * reinstallation on another volume. 18676 * <p> 18677 * Verifies that directories exist and that ownership and labeling is 18678 * correct for all installed apps. 18679 */ 18680 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18681 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18682 + Integer.toHexString(flags)); 18683 18684 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18685 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18686 18687 boolean restoreconNeeded = false; 18688 18689 // First look for stale data that doesn't belong, and check if things 18690 // have changed since we did our last restorecon 18691 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18692 if (!isUserKeyUnlocked(userId)) { 18693 throw new RuntimeException( 18694 "Yikes, someone asked us to reconcile CE storage while " + userId 18695 + " was still locked; this would have caused massive data loss!"); 18696 } 18697 18698 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18699 18700 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18701 for (File file : files) { 18702 final String packageName = file.getName(); 18703 try { 18704 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18705 } catch (PackageManagerException e) { 18706 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18707 synchronized (mInstallLock) { 18708 destroyAppDataLI(volumeUuid, packageName, userId, 18709 StorageManager.FLAG_STORAGE_CE); 18710 } 18711 } 18712 } 18713 } 18714 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18715 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18716 18717 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18718 for (File file : files) { 18719 final String packageName = file.getName(); 18720 try { 18721 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18722 } catch (PackageManagerException e) { 18723 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18724 synchronized (mInstallLock) { 18725 destroyAppDataLI(volumeUuid, packageName, userId, 18726 StorageManager.FLAG_STORAGE_DE); 18727 } 18728 } 18729 } 18730 } 18731 18732 // Ensure that data directories are ready to roll for all packages 18733 // installed for this volume and user 18734 final List<PackageSetting> packages; 18735 synchronized (mPackages) { 18736 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18737 } 18738 int preparedCount = 0; 18739 for (PackageSetting ps : packages) { 18740 final String packageName = ps.name; 18741 if (ps.pkg == null) { 18742 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18743 // TODO: might be due to legacy ASEC apps; we should circle back 18744 // and reconcile again once they're scanned 18745 continue; 18746 } 18747 18748 if (ps.getInstalled(userId)) { 18749 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18750 18751 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18752 // We may have just shuffled around app data directories, so 18753 // prepare them one more time 18754 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18755 } 18756 18757 preparedCount++; 18758 } 18759 } 18760 18761 if (restoreconNeeded) { 18762 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18763 SELinuxMMAC.setRestoreconDone(ceDir); 18764 } 18765 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18766 SELinuxMMAC.setRestoreconDone(deDir); 18767 } 18768 } 18769 18770 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18771 + " packages; restoreconNeeded was " + restoreconNeeded); 18772 } 18773 18774 /** 18775 * Prepare app data for the given app just after it was installed or 18776 * upgraded. This method carefully only touches users that it's installed 18777 * for, and it forces a restorecon to handle any seinfo changes. 18778 * <p> 18779 * Verifies that directories exist and that ownership and labeling is 18780 * correct for all installed apps. If there is an ownership mismatch, it 18781 * will try recovering system apps by wiping data; third-party app data is 18782 * left intact. 18783 * <p> 18784 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18785 */ 18786 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18787 prepareAppDataAfterInstallInternal(pkg); 18788 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18789 for (int i = 0; i < childCount; i++) { 18790 PackageParser.Package childPackage = pkg.childPackages.get(i); 18791 prepareAppDataAfterInstallInternal(childPackage); 18792 } 18793 } 18794 18795 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18796 final PackageSetting ps; 18797 synchronized (mPackages) { 18798 ps = mSettings.mPackages.get(pkg.packageName); 18799 mSettings.writeKernelMappingLPr(ps); 18800 } 18801 18802 final UserManager um = mContext.getSystemService(UserManager.class); 18803 for (UserInfo user : um.getUsers()) { 18804 final int flags; 18805 if (um.isUserUnlocked(user.id)) { 18806 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18807 } else if (um.isUserRunning(user.id)) { 18808 flags = StorageManager.FLAG_STORAGE_DE; 18809 } else { 18810 continue; 18811 } 18812 18813 if (ps.getInstalled(user.id)) { 18814 // Whenever an app changes, force a restorecon of its data 18815 // TODO: when user data is locked, mark that we're still dirty 18816 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18817 } 18818 } 18819 } 18820 18821 /** 18822 * Prepare app data for the given app. 18823 * <p> 18824 * Verifies that directories exist and that ownership and labeling is 18825 * correct for all installed apps. If there is an ownership mismatch, this 18826 * will try recovering system apps by wiping data; third-party app data is 18827 * left intact. 18828 */ 18829 private void prepareAppData(String volumeUuid, int userId, int flags, 18830 PackageParser.Package pkg, boolean restoreconNeeded) { 18831 if (DEBUG_APP_DATA) { 18832 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18833 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18834 } 18835 18836 final String packageName = pkg.packageName; 18837 final ApplicationInfo app = pkg.applicationInfo; 18838 final int appId = UserHandle.getAppId(app.uid); 18839 18840 Preconditions.checkNotNull(app.seinfo); 18841 18842 synchronized (mInstallLock) { 18843 try { 18844 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18845 appId, app.seinfo, app.targetSdkVersion); 18846 } catch (InstallerException e) { 18847 if (app.isSystemApp()) { 18848 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18849 + ", but trying to recover: " + e); 18850 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18851 try { 18852 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18853 appId, app.seinfo, app.targetSdkVersion); 18854 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18855 } catch (InstallerException e2) { 18856 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18857 } 18858 } else { 18859 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18860 } 18861 } 18862 18863 if (restoreconNeeded) { 18864 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18865 } 18866 18867 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18868 // Create a native library symlink only if we have native libraries 18869 // and if the native libraries are 32 bit libraries. We do not provide 18870 // this symlink for 64 bit libraries. 18871 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18872 final String nativeLibPath = app.nativeLibraryDir; 18873 try { 18874 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18875 nativeLibPath, userId); 18876 } catch (InstallerException e) { 18877 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18878 } 18879 } 18880 } 18881 } 18882 } 18883 18884 /** 18885 * For system apps on non-FBE devices, this method migrates any existing 18886 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 18887 * requested by the app. 18888 */ 18889 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18890 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 18891 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 18892 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 18893 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18894 synchronized (mInstallLock) { 18895 try { 18896 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18897 } catch (InstallerException e) { 18898 logCriticalInfo(Log.WARN, 18899 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18900 } 18901 } 18902 return true; 18903 } else { 18904 return false; 18905 } 18906 } 18907 18908 private void unfreezePackage(String packageName) { 18909 synchronized (mPackages) { 18910 final PackageSetting ps = mSettings.mPackages.get(packageName); 18911 if (ps != null) { 18912 ps.frozen = false; 18913 } 18914 } 18915 } 18916 18917 @Override 18918 public int movePackage(final String packageName, final String volumeUuid) { 18919 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18920 18921 final int moveId = mNextMoveId.getAndIncrement(); 18922 mHandler.post(new Runnable() { 18923 @Override 18924 public void run() { 18925 try { 18926 movePackageInternal(packageName, volumeUuid, moveId); 18927 } catch (PackageManagerException e) { 18928 Slog.w(TAG, "Failed to move " + packageName, e); 18929 mMoveCallbacks.notifyStatusChanged(moveId, 18930 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18931 } 18932 } 18933 }); 18934 return moveId; 18935 } 18936 18937 private void movePackageInternal(final String packageName, final String volumeUuid, 18938 final int moveId) throws PackageManagerException { 18939 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18940 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18941 final PackageManager pm = mContext.getPackageManager(); 18942 18943 final boolean currentAsec; 18944 final String currentVolumeUuid; 18945 final File codeFile; 18946 final String installerPackageName; 18947 final String packageAbiOverride; 18948 final int appId; 18949 final String seinfo; 18950 final String label; 18951 final int targetSdkVersion; 18952 18953 // reader 18954 synchronized (mPackages) { 18955 final PackageParser.Package pkg = mPackages.get(packageName); 18956 final PackageSetting ps = mSettings.mPackages.get(packageName); 18957 if (pkg == null || ps == null) { 18958 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18959 } 18960 18961 if (pkg.applicationInfo.isSystemApp()) { 18962 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18963 "Cannot move system application"); 18964 } 18965 18966 if (pkg.applicationInfo.isExternalAsec()) { 18967 currentAsec = true; 18968 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18969 } else if (pkg.applicationInfo.isForwardLocked()) { 18970 currentAsec = true; 18971 currentVolumeUuid = "forward_locked"; 18972 } else { 18973 currentAsec = false; 18974 currentVolumeUuid = ps.volumeUuid; 18975 18976 final File probe = new File(pkg.codePath); 18977 final File probeOat = new File(probe, "oat"); 18978 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18979 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18980 "Move only supported for modern cluster style installs"); 18981 } 18982 } 18983 18984 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18985 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18986 "Package already moved to " + volumeUuid); 18987 } 18988 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18989 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18990 "Device admin cannot be moved"); 18991 } 18992 18993 if (ps.frozen) { 18994 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18995 "Failed to move already frozen package"); 18996 } 18997 ps.frozen = true; 18998 18999 codeFile = new File(pkg.codePath); 19000 installerPackageName = ps.installerPackageName; 19001 packageAbiOverride = ps.cpuAbiOverrideString; 19002 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19003 seinfo = pkg.applicationInfo.seinfo; 19004 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19005 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19006 } 19007 19008 // Now that we're guarded by frozen state, kill app during move 19009 final long token = Binder.clearCallingIdentity(); 19010 try { 19011 killApplication(packageName, appId, "move pkg"); 19012 } finally { 19013 Binder.restoreCallingIdentity(token); 19014 } 19015 19016 final Bundle extras = new Bundle(); 19017 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19018 extras.putString(Intent.EXTRA_TITLE, label); 19019 mMoveCallbacks.notifyCreated(moveId, extras); 19020 19021 int installFlags; 19022 final boolean moveCompleteApp; 19023 final File measurePath; 19024 19025 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19026 installFlags = INSTALL_INTERNAL; 19027 moveCompleteApp = !currentAsec; 19028 measurePath = Environment.getDataAppDirectory(volumeUuid); 19029 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19030 installFlags = INSTALL_EXTERNAL; 19031 moveCompleteApp = false; 19032 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19033 } else { 19034 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19035 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19036 || !volume.isMountedWritable()) { 19037 unfreezePackage(packageName); 19038 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19039 "Move location not mounted private volume"); 19040 } 19041 19042 Preconditions.checkState(!currentAsec); 19043 19044 installFlags = INSTALL_INTERNAL; 19045 moveCompleteApp = true; 19046 measurePath = Environment.getDataAppDirectory(volumeUuid); 19047 } 19048 19049 final PackageStats stats = new PackageStats(null, -1); 19050 synchronized (mInstaller) { 19051 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19052 unfreezePackage(packageName); 19053 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19054 "Failed to measure package size"); 19055 } 19056 } 19057 19058 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19059 + stats.dataSize); 19060 19061 final long startFreeBytes = measurePath.getFreeSpace(); 19062 final long sizeBytes; 19063 if (moveCompleteApp) { 19064 sizeBytes = stats.codeSize + stats.dataSize; 19065 } else { 19066 sizeBytes = stats.codeSize; 19067 } 19068 19069 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19070 unfreezePackage(packageName); 19071 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19072 "Not enough free space to move"); 19073 } 19074 19075 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19076 19077 final CountDownLatch installedLatch = new CountDownLatch(1); 19078 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19079 @Override 19080 public void onUserActionRequired(Intent intent) throws RemoteException { 19081 throw new IllegalStateException(); 19082 } 19083 19084 @Override 19085 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19086 Bundle extras) throws RemoteException { 19087 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19088 + PackageManager.installStatusToString(returnCode, msg)); 19089 19090 installedLatch.countDown(); 19091 19092 // Regardless of success or failure of the move operation, 19093 // always unfreeze the package 19094 unfreezePackage(packageName); 19095 19096 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19097 switch (status) { 19098 case PackageInstaller.STATUS_SUCCESS: 19099 mMoveCallbacks.notifyStatusChanged(moveId, 19100 PackageManager.MOVE_SUCCEEDED); 19101 break; 19102 case PackageInstaller.STATUS_FAILURE_STORAGE: 19103 mMoveCallbacks.notifyStatusChanged(moveId, 19104 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19105 break; 19106 default: 19107 mMoveCallbacks.notifyStatusChanged(moveId, 19108 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19109 break; 19110 } 19111 } 19112 }; 19113 19114 final MoveInfo move; 19115 if (moveCompleteApp) { 19116 // Kick off a thread to report progress estimates 19117 new Thread() { 19118 @Override 19119 public void run() { 19120 while (true) { 19121 try { 19122 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19123 break; 19124 } 19125 } catch (InterruptedException ignored) { 19126 } 19127 19128 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19129 final int progress = 10 + (int) MathUtils.constrain( 19130 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19131 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19132 } 19133 } 19134 }.start(); 19135 19136 final String dataAppName = codeFile.getName(); 19137 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19138 dataAppName, appId, seinfo, targetSdkVersion); 19139 } else { 19140 move = null; 19141 } 19142 19143 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19144 19145 final Message msg = mHandler.obtainMessage(INIT_COPY); 19146 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19147 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19148 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19149 packageAbiOverride, null); 19150 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19151 msg.obj = params; 19152 19153 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19154 System.identityHashCode(msg.obj)); 19155 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19156 System.identityHashCode(msg.obj)); 19157 19158 mHandler.sendMessage(msg); 19159 } 19160 19161 @Override 19162 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19163 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19164 19165 final int realMoveId = mNextMoveId.getAndIncrement(); 19166 final Bundle extras = new Bundle(); 19167 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19168 mMoveCallbacks.notifyCreated(realMoveId, extras); 19169 19170 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19171 @Override 19172 public void onCreated(int moveId, Bundle extras) { 19173 // Ignored 19174 } 19175 19176 @Override 19177 public void onStatusChanged(int moveId, int status, long estMillis) { 19178 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19179 } 19180 }; 19181 19182 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19183 storage.setPrimaryStorageUuid(volumeUuid, callback); 19184 return realMoveId; 19185 } 19186 19187 @Override 19188 public int getMoveStatus(int moveId) { 19189 mContext.enforceCallingOrSelfPermission( 19190 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19191 return mMoveCallbacks.mLastStatus.get(moveId); 19192 } 19193 19194 @Override 19195 public void registerMoveCallback(IPackageMoveObserver callback) { 19196 mContext.enforceCallingOrSelfPermission( 19197 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19198 mMoveCallbacks.register(callback); 19199 } 19200 19201 @Override 19202 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19203 mContext.enforceCallingOrSelfPermission( 19204 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19205 mMoveCallbacks.unregister(callback); 19206 } 19207 19208 @Override 19209 public boolean setInstallLocation(int loc) { 19210 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19211 null); 19212 if (getInstallLocation() == loc) { 19213 return true; 19214 } 19215 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19216 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19217 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19218 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19219 return true; 19220 } 19221 return false; 19222 } 19223 19224 @Override 19225 public int getInstallLocation() { 19226 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19227 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19228 PackageHelper.APP_INSTALL_AUTO); 19229 } 19230 19231 /** Called by UserManagerService */ 19232 void cleanUpUser(UserManagerService userManager, int userHandle) { 19233 synchronized (mPackages) { 19234 mDirtyUsers.remove(userHandle); 19235 mUserNeedsBadging.delete(userHandle); 19236 mSettings.removeUserLPw(userHandle); 19237 mPendingBroadcasts.remove(userHandle); 19238 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19239 } 19240 synchronized (mInstallLock) { 19241 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19242 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19243 final String volumeUuid = vol.getFsUuid(); 19244 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19245 try { 19246 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19247 } catch (InstallerException e) { 19248 Slog.w(TAG, "Failed to remove user data", e); 19249 } 19250 } 19251 synchronized (mPackages) { 19252 removeUnusedPackagesLILPw(userManager, userHandle); 19253 } 19254 } 19255 } 19256 19257 /** 19258 * We're removing userHandle and would like to remove any downloaded packages 19259 * that are no longer in use by any other user. 19260 * @param userHandle the user being removed 19261 */ 19262 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19263 final boolean DEBUG_CLEAN_APKS = false; 19264 int [] users = userManager.getUserIds(); 19265 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19266 while (psit.hasNext()) { 19267 PackageSetting ps = psit.next(); 19268 if (ps.pkg == null) { 19269 continue; 19270 } 19271 final String packageName = ps.pkg.packageName; 19272 // Skip over if system app 19273 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19274 continue; 19275 } 19276 if (DEBUG_CLEAN_APKS) { 19277 Slog.i(TAG, "Checking package " + packageName); 19278 } 19279 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19280 if (keep) { 19281 if (DEBUG_CLEAN_APKS) { 19282 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19283 } 19284 } else { 19285 for (int i = 0; i < users.length; i++) { 19286 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19287 keep = true; 19288 if (DEBUG_CLEAN_APKS) { 19289 Slog.i(TAG, " Keeping package " + packageName + " for user " 19290 + users[i]); 19291 } 19292 break; 19293 } 19294 } 19295 } 19296 if (!keep) { 19297 if (DEBUG_CLEAN_APKS) { 19298 Slog.i(TAG, " Removing package " + packageName); 19299 } 19300 mHandler.post(new Runnable() { 19301 public void run() { 19302 deletePackageX(packageName, userHandle, 0); 19303 } //end run 19304 }); 19305 } 19306 } 19307 } 19308 19309 /** Called by UserManagerService */ 19310 void createNewUser(int userHandle) { 19311 synchronized (mInstallLock) { 19312 try { 19313 mInstaller.createUserConfig(userHandle); 19314 } catch (InstallerException e) { 19315 Slog.w(TAG, "Failed to create user config", e); 19316 } 19317 mSettings.createNewUserLI(this, mInstaller, userHandle); 19318 } 19319 synchronized (mPackages) { 19320 applyFactoryDefaultBrowserLPw(userHandle); 19321 primeDomainVerificationsLPw(userHandle); 19322 } 19323 } 19324 19325 void newUserCreated(final int userHandle) { 19326 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19327 // If permission review for legacy apps is required, we represent 19328 // dagerous permissions for such apps as always granted runtime 19329 // permissions to keep per user flag state whether review is needed. 19330 // Hence, if a new user is added we have to propagate dangerous 19331 // permission grants for these legacy apps. 19332 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19333 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19334 | UPDATE_PERMISSIONS_REPLACE_ALL); 19335 } 19336 } 19337 19338 @Override 19339 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19340 mContext.enforceCallingOrSelfPermission( 19341 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19342 "Only package verification agents can read the verifier device identity"); 19343 19344 synchronized (mPackages) { 19345 return mSettings.getVerifierDeviceIdentityLPw(); 19346 } 19347 } 19348 19349 @Override 19350 public void setPermissionEnforced(String permission, boolean enforced) { 19351 // TODO: Now that we no longer change GID for storage, this should to away. 19352 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19353 "setPermissionEnforced"); 19354 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19355 synchronized (mPackages) { 19356 if (mSettings.mReadExternalStorageEnforced == null 19357 || mSettings.mReadExternalStorageEnforced != enforced) { 19358 mSettings.mReadExternalStorageEnforced = enforced; 19359 mSettings.writeLPr(); 19360 } 19361 } 19362 // kill any non-foreground processes so we restart them and 19363 // grant/revoke the GID. 19364 final IActivityManager am = ActivityManagerNative.getDefault(); 19365 if (am != null) { 19366 final long token = Binder.clearCallingIdentity(); 19367 try { 19368 am.killProcessesBelowForeground("setPermissionEnforcement"); 19369 } catch (RemoteException e) { 19370 } finally { 19371 Binder.restoreCallingIdentity(token); 19372 } 19373 } 19374 } else { 19375 throw new IllegalArgumentException("No selective enforcement for " + permission); 19376 } 19377 } 19378 19379 @Override 19380 @Deprecated 19381 public boolean isPermissionEnforced(String permission) { 19382 return true; 19383 } 19384 19385 @Override 19386 public boolean isStorageLow() { 19387 final long token = Binder.clearCallingIdentity(); 19388 try { 19389 final DeviceStorageMonitorInternal 19390 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19391 if (dsm != null) { 19392 return dsm.isMemoryLow(); 19393 } else { 19394 return false; 19395 } 19396 } finally { 19397 Binder.restoreCallingIdentity(token); 19398 } 19399 } 19400 19401 @Override 19402 public IPackageInstaller getPackageInstaller() { 19403 return mInstallerService; 19404 } 19405 19406 private boolean userNeedsBadging(int userId) { 19407 int index = mUserNeedsBadging.indexOfKey(userId); 19408 if (index < 0) { 19409 final UserInfo userInfo; 19410 final long token = Binder.clearCallingIdentity(); 19411 try { 19412 userInfo = sUserManager.getUserInfo(userId); 19413 } finally { 19414 Binder.restoreCallingIdentity(token); 19415 } 19416 final boolean b; 19417 if (userInfo != null && userInfo.isManagedProfile()) { 19418 b = true; 19419 } else { 19420 b = false; 19421 } 19422 mUserNeedsBadging.put(userId, b); 19423 return b; 19424 } 19425 return mUserNeedsBadging.valueAt(index); 19426 } 19427 19428 @Override 19429 public KeySet getKeySetByAlias(String packageName, String alias) { 19430 if (packageName == null || alias == null) { 19431 return null; 19432 } 19433 synchronized(mPackages) { 19434 final PackageParser.Package pkg = mPackages.get(packageName); 19435 if (pkg == null) { 19436 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19437 throw new IllegalArgumentException("Unknown package: " + packageName); 19438 } 19439 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19440 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19441 } 19442 } 19443 19444 @Override 19445 public KeySet getSigningKeySet(String packageName) { 19446 if (packageName == null) { 19447 return null; 19448 } 19449 synchronized(mPackages) { 19450 final PackageParser.Package pkg = mPackages.get(packageName); 19451 if (pkg == null) { 19452 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19453 throw new IllegalArgumentException("Unknown package: " + packageName); 19454 } 19455 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19456 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19457 throw new SecurityException("May not access signing KeySet of other apps."); 19458 } 19459 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19460 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19461 } 19462 } 19463 19464 @Override 19465 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19466 if (packageName == null || ks == null) { 19467 return false; 19468 } 19469 synchronized(mPackages) { 19470 final PackageParser.Package pkg = mPackages.get(packageName); 19471 if (pkg == null) { 19472 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19473 throw new IllegalArgumentException("Unknown package: " + packageName); 19474 } 19475 IBinder ksh = ks.getToken(); 19476 if (ksh instanceof KeySetHandle) { 19477 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19478 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19479 } 19480 return false; 19481 } 19482 } 19483 19484 @Override 19485 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19486 if (packageName == null || ks == null) { 19487 return false; 19488 } 19489 synchronized(mPackages) { 19490 final PackageParser.Package pkg = mPackages.get(packageName); 19491 if (pkg == null) { 19492 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19493 throw new IllegalArgumentException("Unknown package: " + packageName); 19494 } 19495 IBinder ksh = ks.getToken(); 19496 if (ksh instanceof KeySetHandle) { 19497 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19498 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19499 } 19500 return false; 19501 } 19502 } 19503 19504 private void deletePackageIfUnusedLPr(final String packageName) { 19505 PackageSetting ps = mSettings.mPackages.get(packageName); 19506 if (ps == null) { 19507 return; 19508 } 19509 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19510 // TODO Implement atomic delete if package is unused 19511 // It is currently possible that the package will be deleted even if it is installed 19512 // after this method returns. 19513 mHandler.post(new Runnable() { 19514 public void run() { 19515 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19516 } 19517 }); 19518 } 19519 } 19520 19521 /** 19522 * Check and throw if the given before/after packages would be considered a 19523 * downgrade. 19524 */ 19525 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19526 throws PackageManagerException { 19527 if (after.versionCode < before.mVersionCode) { 19528 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19529 "Update version code " + after.versionCode + " is older than current " 19530 + before.mVersionCode); 19531 } else if (after.versionCode == before.mVersionCode) { 19532 if (after.baseRevisionCode < before.baseRevisionCode) { 19533 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19534 "Update base revision code " + after.baseRevisionCode 19535 + " is older than current " + before.baseRevisionCode); 19536 } 19537 19538 if (!ArrayUtils.isEmpty(after.splitNames)) { 19539 for (int i = 0; i < after.splitNames.length; i++) { 19540 final String splitName = after.splitNames[i]; 19541 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19542 if (j != -1) { 19543 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19544 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19545 "Update split " + splitName + " revision code " 19546 + after.splitRevisionCodes[i] + " is older than current " 19547 + before.splitRevisionCodes[j]); 19548 } 19549 } 19550 } 19551 } 19552 } 19553 } 19554 19555 private static class MoveCallbacks extends Handler { 19556 private static final int MSG_CREATED = 1; 19557 private static final int MSG_STATUS_CHANGED = 2; 19558 19559 private final RemoteCallbackList<IPackageMoveObserver> 19560 mCallbacks = new RemoteCallbackList<>(); 19561 19562 private final SparseIntArray mLastStatus = new SparseIntArray(); 19563 19564 public MoveCallbacks(Looper looper) { 19565 super(looper); 19566 } 19567 19568 public void register(IPackageMoveObserver callback) { 19569 mCallbacks.register(callback); 19570 } 19571 19572 public void unregister(IPackageMoveObserver callback) { 19573 mCallbacks.unregister(callback); 19574 } 19575 19576 @Override 19577 public void handleMessage(Message msg) { 19578 final SomeArgs args = (SomeArgs) msg.obj; 19579 final int n = mCallbacks.beginBroadcast(); 19580 for (int i = 0; i < n; i++) { 19581 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19582 try { 19583 invokeCallback(callback, msg.what, args); 19584 } catch (RemoteException ignored) { 19585 } 19586 } 19587 mCallbacks.finishBroadcast(); 19588 args.recycle(); 19589 } 19590 19591 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19592 throws RemoteException { 19593 switch (what) { 19594 case MSG_CREATED: { 19595 callback.onCreated(args.argi1, (Bundle) args.arg2); 19596 break; 19597 } 19598 case MSG_STATUS_CHANGED: { 19599 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19600 break; 19601 } 19602 } 19603 } 19604 19605 private void notifyCreated(int moveId, Bundle extras) { 19606 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19607 19608 final SomeArgs args = SomeArgs.obtain(); 19609 args.argi1 = moveId; 19610 args.arg2 = extras; 19611 obtainMessage(MSG_CREATED, args).sendToTarget(); 19612 } 19613 19614 private void notifyStatusChanged(int moveId, int status) { 19615 notifyStatusChanged(moveId, status, -1); 19616 } 19617 19618 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19619 Slog.v(TAG, "Move " + moveId + " status " + status); 19620 19621 final SomeArgs args = SomeArgs.obtain(); 19622 args.argi1 = moveId; 19623 args.argi2 = status; 19624 args.arg3 = estMillis; 19625 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19626 19627 synchronized (mLastStatus) { 19628 mLastStatus.put(moveId, status); 19629 } 19630 } 19631 } 19632 19633 private final static class OnPermissionChangeListeners extends Handler { 19634 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19635 19636 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19637 new RemoteCallbackList<>(); 19638 19639 public OnPermissionChangeListeners(Looper looper) { 19640 super(looper); 19641 } 19642 19643 @Override 19644 public void handleMessage(Message msg) { 19645 switch (msg.what) { 19646 case MSG_ON_PERMISSIONS_CHANGED: { 19647 final int uid = msg.arg1; 19648 handleOnPermissionsChanged(uid); 19649 } break; 19650 } 19651 } 19652 19653 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19654 mPermissionListeners.register(listener); 19655 19656 } 19657 19658 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19659 mPermissionListeners.unregister(listener); 19660 } 19661 19662 public void onPermissionsChanged(int uid) { 19663 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19664 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19665 } 19666 } 19667 19668 private void handleOnPermissionsChanged(int uid) { 19669 final int count = mPermissionListeners.beginBroadcast(); 19670 try { 19671 for (int i = 0; i < count; i++) { 19672 IOnPermissionsChangeListener callback = mPermissionListeners 19673 .getBroadcastItem(i); 19674 try { 19675 callback.onPermissionsChanged(uid); 19676 } catch (RemoteException e) { 19677 Log.e(TAG, "Permission listener is dead", e); 19678 } 19679 } 19680 } finally { 19681 mPermissionListeners.finishBroadcast(); 19682 } 19683 } 19684 } 19685 19686 private class PackageManagerInternalImpl extends PackageManagerInternal { 19687 @Override 19688 public void setLocationPackagesProvider(PackagesProvider provider) { 19689 synchronized (mPackages) { 19690 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19691 } 19692 } 19693 19694 @Override 19695 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19696 synchronized (mPackages) { 19697 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19698 } 19699 } 19700 19701 @Override 19702 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19703 synchronized (mPackages) { 19704 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19705 } 19706 } 19707 19708 @Override 19709 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19710 synchronized (mPackages) { 19711 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19712 } 19713 } 19714 19715 @Override 19716 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19717 synchronized (mPackages) { 19718 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19719 } 19720 } 19721 19722 @Override 19723 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19724 synchronized (mPackages) { 19725 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19726 } 19727 } 19728 19729 @Override 19730 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19731 synchronized (mPackages) { 19732 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19733 packageName, userId); 19734 } 19735 } 19736 19737 @Override 19738 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19739 synchronized (mPackages) { 19740 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19741 packageName, userId); 19742 } 19743 } 19744 19745 @Override 19746 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19747 synchronized (mPackages) { 19748 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19749 packageName, userId); 19750 } 19751 } 19752 19753 @Override 19754 public void setKeepUninstalledPackages(final List<String> packageList) { 19755 Preconditions.checkNotNull(packageList); 19756 List<String> removedFromList = null; 19757 synchronized (mPackages) { 19758 if (mKeepUninstalledPackages != null) { 19759 final int packagesCount = mKeepUninstalledPackages.size(); 19760 for (int i = 0; i < packagesCount; i++) { 19761 String oldPackage = mKeepUninstalledPackages.get(i); 19762 if (packageList != null && packageList.contains(oldPackage)) { 19763 continue; 19764 } 19765 if (removedFromList == null) { 19766 removedFromList = new ArrayList<>(); 19767 } 19768 removedFromList.add(oldPackage); 19769 } 19770 } 19771 mKeepUninstalledPackages = new ArrayList<>(packageList); 19772 if (removedFromList != null) { 19773 final int removedCount = removedFromList.size(); 19774 for (int i = 0; i < removedCount; i++) { 19775 deletePackageIfUnusedLPr(removedFromList.get(i)); 19776 } 19777 } 19778 } 19779 } 19780 19781 @Override 19782 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19783 synchronized (mPackages) { 19784 // If we do not support permission review, done. 19785 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19786 return false; 19787 } 19788 19789 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19790 if (packageSetting == null) { 19791 return false; 19792 } 19793 19794 // Permission review applies only to apps not supporting the new permission model. 19795 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19796 return false; 19797 } 19798 19799 // Legacy apps have the permission and get user consent on launch. 19800 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19801 return permissionsState.isPermissionReviewRequired(userId); 19802 } 19803 } 19804 19805 @Override 19806 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19807 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19808 } 19809 19810 @Override 19811 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19812 int userId) { 19813 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 19814 } 19815 } 19816 19817 @Override 19818 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19819 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19820 synchronized (mPackages) { 19821 final long identity = Binder.clearCallingIdentity(); 19822 try { 19823 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19824 packageNames, userId); 19825 } finally { 19826 Binder.restoreCallingIdentity(identity); 19827 } 19828 } 19829 } 19830 19831 private static void enforceSystemOrPhoneCaller(String tag) { 19832 int callingUid = Binder.getCallingUid(); 19833 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19834 throw new SecurityException( 19835 "Cannot call " + tag + " from UID " + callingUid); 19836 } 19837 } 19838 19839 boolean isHistoricalPackageUsageAvailable() { 19840 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19841 } 19842 19843 /** 19844 * Return a <b>copy</b> of the collection of packages known to the package manager. 19845 * @return A copy of the values of mPackages. 19846 */ 19847 Collection<PackageParser.Package> getPackages() { 19848 synchronized (mPackages) { 19849 return new ArrayList<>(mPackages.values()); 19850 } 19851 } 19852 19853 /** 19854 * Logs process start information (including base APK hash) to the security log. 19855 * @hide 19856 */ 19857 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 19858 String apkFile, int pid) { 19859 if (!SecurityLog.isLoggingEnabled()) { 19860 return; 19861 } 19862 Bundle data = new Bundle(); 19863 data.putLong("startTimestamp", System.currentTimeMillis()); 19864 data.putString("processName", processName); 19865 data.putInt("uid", uid); 19866 data.putString("seinfo", seinfo); 19867 data.putString("apkFile", apkFile); 19868 data.putInt("pid", pid); 19869 Message msg = mProcessLoggingHandler.obtainMessage( 19870 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 19871 msg.setData(data); 19872 mProcessLoggingHandler.sendMessage(msg); 19873 } 19874} 19875