PackageManagerService.java revision 0ba0d814b300e9dea70933885c1837695eda69da
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.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 105 106import android.Manifest; 107import android.annotation.NonNull; 108import android.annotation.Nullable; 109import android.app.ActivityManager; 110import android.app.AppOpsManager; 111import android.app.IActivityManager; 112import android.app.ResourcesManager; 113import android.app.admin.IDevicePolicyManager; 114import android.app.admin.SecurityLog; 115import android.app.backup.IBackupManager; 116import android.content.BroadcastReceiver; 117import android.content.ComponentName; 118import android.content.ContentResolver; 119import android.content.Context; 120import android.content.IIntentReceiver; 121import android.content.Intent; 122import android.content.IntentFilter; 123import android.content.IntentSender; 124import android.content.IntentSender.SendIntentException; 125import android.content.ServiceConnection; 126import android.content.pm.ActivityInfo; 127import android.content.pm.ApplicationInfo; 128import android.content.pm.AppsQueryHelper; 129import android.content.pm.ChangedPackages; 130import android.content.pm.ComponentInfo; 131import android.content.pm.InstantAppInfo; 132import android.content.pm.EphemeralRequest; 133import android.content.pm.EphemeralResolveInfo; 134import android.content.pm.AuxiliaryResolveInfo; 135import android.content.pm.FallbackCategoryProvider; 136import android.content.pm.FeatureInfo; 137import android.content.pm.IOnPermissionsChangeListener; 138import android.content.pm.IPackageDataObserver; 139import android.content.pm.IPackageDeleteObserver; 140import android.content.pm.IPackageDeleteObserver2; 141import android.content.pm.IPackageInstallObserver2; 142import android.content.pm.IPackageInstaller; 143import android.content.pm.IPackageManager; 144import android.content.pm.IPackageMoveObserver; 145import android.content.pm.IPackageStatsObserver; 146import android.content.pm.InstrumentationInfo; 147import android.content.pm.IntentFilterVerificationInfo; 148import android.content.pm.KeySet; 149import android.content.pm.PackageCleanItem; 150import android.content.pm.PackageInfo; 151import android.content.pm.PackageInfoLite; 152import android.content.pm.PackageInstaller; 153import android.content.pm.PackageManager; 154import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155import android.content.pm.PackageManagerInternal; 156import android.content.pm.PackageParser; 157import android.content.pm.PackageParser.ActivityIntentInfo; 158import android.content.pm.PackageParser.PackageLite; 159import android.content.pm.PackageParser.PackageParserException; 160import android.content.pm.PackageStats; 161import android.content.pm.PackageUserState; 162import android.content.pm.ParceledListSlice; 163import android.content.pm.PermissionGroupInfo; 164import android.content.pm.PermissionInfo; 165import android.content.pm.ProviderInfo; 166import android.content.pm.ResolveInfo; 167import android.content.pm.SELinuxUtil; 168import android.content.pm.ServiceInfo; 169import android.content.pm.SharedLibraryInfo; 170import android.content.pm.Signature; 171import android.content.pm.UserInfo; 172import android.content.pm.VerifierDeviceIdentity; 173import android.content.pm.VerifierInfo; 174import android.content.pm.VersionedPackage; 175import android.content.res.Resources; 176import android.graphics.Bitmap; 177import android.hardware.display.DisplayManager; 178import android.net.Uri; 179import android.os.Binder; 180import android.os.Build; 181import android.os.Bundle; 182import android.os.Debug; 183import android.os.Environment; 184import android.os.Environment.UserEnvironment; 185import android.os.FileUtils; 186import android.os.Handler; 187import android.os.IBinder; 188import android.os.Looper; 189import android.os.Message; 190import android.os.Parcel; 191import android.os.ParcelFileDescriptor; 192import android.os.PatternMatcher; 193import android.os.Process; 194import android.os.RemoteCallbackList; 195import android.os.RemoteException; 196import android.os.ResultReceiver; 197import android.os.SELinux; 198import android.os.ServiceManager; 199import android.os.ShellCallback; 200import android.os.SystemClock; 201import android.os.SystemProperties; 202import android.os.Trace; 203import android.os.UserHandle; 204import android.os.UserManager; 205import android.os.UserManagerInternal; 206import android.os.storage.IStorageManager; 207import android.os.storage.StorageManagerInternal; 208import android.os.storage.StorageEventListener; 209import android.os.storage.StorageManager; 210import android.os.storage.VolumeInfo; 211import android.os.storage.VolumeRecord; 212import android.provider.Settings.Global; 213import android.provider.Settings.Secure; 214import android.security.KeyStore; 215import android.security.SystemKeyStore; 216import android.system.ErrnoException; 217import android.system.Os; 218import android.text.TextUtils; 219import android.text.format.DateUtils; 220import android.util.ArrayMap; 221import android.util.ArraySet; 222import android.util.Base64; 223import android.util.DisplayMetrics; 224import android.util.EventLog; 225import android.util.ExceptionUtils; 226import android.util.Log; 227import android.util.LogPrinter; 228import android.util.MathUtils; 229import android.util.PackageUtils; 230import android.util.Pair; 231import android.util.PrintStreamPrinter; 232import android.util.Slog; 233import android.util.SparseArray; 234import android.util.SparseBooleanArray; 235import android.util.SparseIntArray; 236import android.util.Xml; 237import android.util.jar.StrictJarFile; 238import android.view.Display; 239 240import com.android.internal.R; 241import com.android.internal.annotations.GuardedBy; 242import com.android.internal.app.IMediaContainerService; 243import com.android.internal.app.ResolverActivity; 244import com.android.internal.content.NativeLibraryHelper; 245import com.android.internal.content.PackageHelper; 246import com.android.internal.logging.MetricsLogger; 247import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 248import com.android.internal.os.IParcelFileDescriptorFactory; 249import com.android.internal.os.RoSystemProperties; 250import com.android.internal.os.SomeArgs; 251import com.android.internal.os.Zygote; 252import com.android.internal.telephony.CarrierAppUtils; 253import com.android.internal.util.ArrayUtils; 254import com.android.internal.util.ConcurrentUtils; 255import com.android.internal.util.FastPrintWriter; 256import com.android.internal.util.FastXmlSerializer; 257import com.android.internal.util.IndentingPrintWriter; 258import com.android.internal.util.Preconditions; 259import com.android.internal.util.XmlUtils; 260import com.android.server.AttributeCache; 261import com.android.server.BackgroundDexOptJobService; 262import com.android.server.DeviceIdleController; 263import com.android.server.EventLogTags; 264import com.android.server.FgThread; 265import com.android.server.IntentResolver; 266import com.android.server.LocalServices; 267import com.android.server.ServiceThread; 268import com.android.server.SystemConfig; 269import com.android.server.SystemServerInitThreadPool; 270import com.android.server.Watchdog; 271import com.android.server.net.NetworkPolicyManagerInternal; 272import com.android.server.pm.Installer.InstallerException; 273import com.android.server.pm.PermissionsState.PermissionState; 274import com.android.server.pm.Settings.DatabaseVersion; 275import com.android.server.pm.Settings.VersionInfo; 276import com.android.server.pm.dex.DexManager; 277import com.android.server.storage.DeviceStorageMonitorInternal; 278 279import dalvik.system.CloseGuard; 280import dalvik.system.DexFile; 281import dalvik.system.VMRuntime; 282 283import libcore.io.IoUtils; 284import libcore.util.EmptyArray; 285 286import org.xmlpull.v1.XmlPullParser; 287import org.xmlpull.v1.XmlPullParserException; 288import org.xmlpull.v1.XmlSerializer; 289 290import java.io.BufferedOutputStream; 291import java.io.BufferedReader; 292import java.io.ByteArrayInputStream; 293import java.io.ByteArrayOutputStream; 294import java.io.File; 295import java.io.FileDescriptor; 296import java.io.FileInputStream; 297import java.io.FileNotFoundException; 298import java.io.FileOutputStream; 299import java.io.FileReader; 300import java.io.FilenameFilter; 301import java.io.IOException; 302import java.io.PrintWriter; 303import java.nio.charset.StandardCharsets; 304import java.security.DigestInputStream; 305import java.security.MessageDigest; 306import java.security.NoSuchAlgorithmException; 307import java.security.PublicKey; 308import java.security.SecureRandom; 309import java.security.cert.Certificate; 310import java.security.cert.CertificateEncodingException; 311import java.security.cert.CertificateException; 312import java.text.SimpleDateFormat; 313import java.util.ArrayList; 314import java.util.Arrays; 315import java.util.Collection; 316import java.util.Collections; 317import java.util.Comparator; 318import java.util.Date; 319import java.util.HashSet; 320import java.util.HashMap; 321import java.util.Iterator; 322import java.util.List; 323import java.util.Map; 324import java.util.Objects; 325import java.util.Set; 326import java.util.concurrent.CountDownLatch; 327import java.util.concurrent.Future; 328import java.util.concurrent.TimeUnit; 329import java.util.concurrent.atomic.AtomicBoolean; 330import java.util.concurrent.atomic.AtomicInteger; 331 332/** 333 * Keep track of all those APKs everywhere. 334 * <p> 335 * Internally there are two important locks: 336 * <ul> 337 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 338 * and other related state. It is a fine-grained lock that should only be held 339 * momentarily, as it's one of the most contended locks in the system. 340 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 341 * operations typically involve heavy lifting of application data on disk. Since 342 * {@code installd} is single-threaded, and it's operations can often be slow, 343 * this lock should never be acquired while already holding {@link #mPackages}. 344 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 345 * holding {@link #mInstallLock}. 346 * </ul> 347 * Many internal methods rely on the caller to hold the appropriate locks, and 348 * this contract is expressed through method name suffixes: 349 * <ul> 350 * <li>fooLI(): the caller must hold {@link #mInstallLock} 351 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 352 * being modified must be frozen 353 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 354 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 355 * </ul> 356 * <p> 357 * Because this class is very central to the platform's security; please run all 358 * CTS and unit tests whenever making modifications: 359 * 360 * <pre> 361 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 362 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 363 * </pre> 364 */ 365public class PackageManagerService extends IPackageManager.Stub { 366 static final String TAG = "PackageManager"; 367 static final boolean DEBUG_SETTINGS = false; 368 static final boolean DEBUG_PREFERRED = false; 369 static final boolean DEBUG_UPGRADE = false; 370 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 371 private static final boolean DEBUG_BACKUP = false; 372 private static final boolean DEBUG_INSTALL = false; 373 private static final boolean DEBUG_REMOVE = false; 374 private static final boolean DEBUG_BROADCASTS = false; 375 private static final boolean DEBUG_SHOW_INFO = false; 376 private static final boolean DEBUG_PACKAGE_INFO = false; 377 private static final boolean DEBUG_INTENT_MATCHING = false; 378 private static final boolean DEBUG_PACKAGE_SCANNING = false; 379 private static final boolean DEBUG_VERIFY = false; 380 private static final boolean DEBUG_FILTERS = false; 381 382 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 383 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 384 // user, but by default initialize to this. 385 public static final boolean DEBUG_DEXOPT = false; 386 387 private static final boolean DEBUG_ABI_SELECTION = false; 388 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 389 private static final boolean DEBUG_TRIAGED_MISSING = false; 390 private static final boolean DEBUG_APP_DATA = false; 391 392 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 393 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 394 395 private static final boolean DISABLE_EPHEMERAL_APPS = false; 396 private static final boolean HIDE_EPHEMERAL_APIS = false; 397 398 private static final boolean ENABLE_FREE_CACHE_V2 = 399 SystemProperties.getBoolean("fw.free_cache_v2", false); 400 401 private static final int RADIO_UID = Process.PHONE_UID; 402 private static final int LOG_UID = Process.LOG_UID; 403 private static final int NFC_UID = Process.NFC_UID; 404 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 405 private static final int SHELL_UID = Process.SHELL_UID; 406 407 // Cap the size of permission trees that 3rd party apps can define 408 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 409 410 // Suffix used during package installation when copying/moving 411 // package apks to install directory. 412 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 413 414 static final int SCAN_NO_DEX = 1<<1; 415 static final int SCAN_FORCE_DEX = 1<<2; 416 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 417 static final int SCAN_NEW_INSTALL = 1<<4; 418 static final int SCAN_UPDATE_TIME = 1<<5; 419 static final int SCAN_BOOTING = 1<<6; 420 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 421 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 422 static final int SCAN_REPLACING = 1<<9; 423 static final int SCAN_REQUIRE_KNOWN = 1<<10; 424 static final int SCAN_MOVE = 1<<11; 425 static final int SCAN_INITIAL = 1<<12; 426 static final int SCAN_CHECK_ONLY = 1<<13; 427 static final int SCAN_DONT_KILL_APP = 1<<14; 428 static final int SCAN_IGNORE_FROZEN = 1<<15; 429 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 430 static final int SCAN_AS_INSTANT_APP = 1<<17; 431 static final int SCAN_AS_FULL_APP = 1<<18; 432 /** Should not be with the scan flags */ 433 static final int FLAGS_REMOVE_CHATTY = 1<<31; 434 435 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 436 437 private static final int[] EMPTY_INT_ARRAY = new int[0]; 438 439 /** 440 * Timeout (in milliseconds) after which the watchdog should declare that 441 * our handler thread is wedged. The usual default for such things is one 442 * minute but we sometimes do very lengthy I/O operations on this thread, 443 * such as installing multi-gigabyte applications, so ours needs to be longer. 444 */ 445 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 446 447 /** 448 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 449 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 450 * settings entry if available, otherwise we use the hardcoded default. If it's been 451 * more than this long since the last fstrim, we force one during the boot sequence. 452 * 453 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 454 * one gets run at the next available charging+idle time. This final mandatory 455 * no-fstrim check kicks in only of the other scheduling criteria is never met. 456 */ 457 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 458 459 /** 460 * Whether verification is enabled by default. 461 */ 462 private static final boolean DEFAULT_VERIFY_ENABLE = true; 463 464 /** 465 * The default maximum time to wait for the verification agent to return in 466 * milliseconds. 467 */ 468 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 469 470 /** 471 * The default response for package verification timeout. 472 * 473 * This can be either PackageManager.VERIFICATION_ALLOW or 474 * PackageManager.VERIFICATION_REJECT. 475 */ 476 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 477 478 static final String PLATFORM_PACKAGE_NAME = "android"; 479 480 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 481 482 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 483 DEFAULT_CONTAINER_PACKAGE, 484 "com.android.defcontainer.DefaultContainerService"); 485 486 private static final String KILL_APP_REASON_GIDS_CHANGED = 487 "permission grant or revoke changed gids"; 488 489 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 490 "permissions revoked"; 491 492 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 493 494 private static final String PACKAGE_SCHEME = "package"; 495 496 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 497 /** 498 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 499 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 500 * VENDOR_OVERLAY_DIR. 501 */ 502 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 503 /** 504 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 505 * is in VENDOR_OVERLAY_THEME_PROPERTY. 506 */ 507 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 508 = "persist.vendor.overlay.theme"; 509 510 /** Permission grant: not grant the permission. */ 511 private static final int GRANT_DENIED = 1; 512 513 /** Permission grant: grant the permission as an install permission. */ 514 private static final int GRANT_INSTALL = 2; 515 516 /** Permission grant: grant the permission as a runtime one. */ 517 private static final int GRANT_RUNTIME = 3; 518 519 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 520 private static final int GRANT_UPGRADE = 4; 521 522 /** Canonical intent used to identify what counts as a "web browser" app */ 523 private static final Intent sBrowserIntent; 524 static { 525 sBrowserIntent = new Intent(); 526 sBrowserIntent.setAction(Intent.ACTION_VIEW); 527 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 528 sBrowserIntent.setData(Uri.parse("http:")); 529 } 530 531 /** 532 * The set of all protected actions [i.e. those actions for which a high priority 533 * intent filter is disallowed]. 534 */ 535 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 536 static { 537 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 538 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 539 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 540 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 541 } 542 543 // Compilation reasons. 544 public static final int REASON_FIRST_BOOT = 0; 545 public static final int REASON_BOOT = 1; 546 public static final int REASON_INSTALL = 2; 547 public static final int REASON_BACKGROUND_DEXOPT = 3; 548 public static final int REASON_AB_OTA = 4; 549 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 550 public static final int REASON_SHARED_APK = 6; 551 public static final int REASON_FORCED_DEXOPT = 7; 552 public static final int REASON_CORE_APP = 8; 553 554 public static final int REASON_LAST = REASON_CORE_APP; 555 556 /** All dangerous permission names in the same order as the events in MetricsEvent */ 557 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 558 Manifest.permission.READ_CALENDAR, 559 Manifest.permission.WRITE_CALENDAR, 560 Manifest.permission.CAMERA, 561 Manifest.permission.READ_CONTACTS, 562 Manifest.permission.WRITE_CONTACTS, 563 Manifest.permission.GET_ACCOUNTS, 564 Manifest.permission.ACCESS_FINE_LOCATION, 565 Manifest.permission.ACCESS_COARSE_LOCATION, 566 Manifest.permission.RECORD_AUDIO, 567 Manifest.permission.READ_PHONE_STATE, 568 Manifest.permission.CALL_PHONE, 569 Manifest.permission.READ_CALL_LOG, 570 Manifest.permission.WRITE_CALL_LOG, 571 Manifest.permission.ADD_VOICEMAIL, 572 Manifest.permission.USE_SIP, 573 Manifest.permission.PROCESS_OUTGOING_CALLS, 574 Manifest.permission.READ_CELL_BROADCASTS, 575 Manifest.permission.BODY_SENSORS, 576 Manifest.permission.SEND_SMS, 577 Manifest.permission.RECEIVE_SMS, 578 Manifest.permission.READ_SMS, 579 Manifest.permission.RECEIVE_WAP_PUSH, 580 Manifest.permission.RECEIVE_MMS, 581 Manifest.permission.READ_EXTERNAL_STORAGE, 582 Manifest.permission.WRITE_EXTERNAL_STORAGE, 583 Manifest.permission.READ_PHONE_NUMBER); 584 585 586 /** 587 * Version number for the package parser cache. Increment this whenever the format or 588 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 589 */ 590 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 591 592 /** 593 * Whether the package parser cache is enabled. 594 */ 595 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 596 597 final ServiceThread mHandlerThread; 598 599 final PackageHandler mHandler; 600 601 private final ProcessLoggingHandler mProcessLoggingHandler; 602 603 /** 604 * Messages for {@link #mHandler} that need to wait for system ready before 605 * being dispatched. 606 */ 607 private ArrayList<Message> mPostSystemReadyMessages; 608 609 final int mSdkVersion = Build.VERSION.SDK_INT; 610 611 final Context mContext; 612 final boolean mFactoryTest; 613 final boolean mOnlyCore; 614 final DisplayMetrics mMetrics; 615 final int mDefParseFlags; 616 final String[] mSeparateProcesses; 617 final boolean mIsUpgrade; 618 final boolean mIsPreNUpgrade; 619 final boolean mIsPreNMR1Upgrade; 620 621 @GuardedBy("mPackages") 622 private boolean mDexOptDialogShown; 623 624 /** The location for ASEC container files on internal storage. */ 625 final String mAsecInternalPath; 626 627 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 628 // LOCK HELD. Can be called with mInstallLock held. 629 @GuardedBy("mInstallLock") 630 final Installer mInstaller; 631 632 /** Directory where installed third-party apps stored */ 633 final File mAppInstallDir; 634 635 /** 636 * Directory to which applications installed internally have their 637 * 32 bit native libraries copied. 638 */ 639 private File mAppLib32InstallDir; 640 641 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 642 // apps. 643 final File mDrmAppPrivateInstallDir; 644 645 // ---------------------------------------------------------------- 646 647 // Lock for state used when installing and doing other long running 648 // operations. Methods that must be called with this lock held have 649 // the suffix "LI". 650 final Object mInstallLock = new Object(); 651 652 // ---------------------------------------------------------------- 653 654 // Keys are String (package name), values are Package. This also serves 655 // as the lock for the global state. Methods that must be called with 656 // this lock held have the prefix "LP". 657 @GuardedBy("mPackages") 658 final ArrayMap<String, PackageParser.Package> mPackages = 659 new ArrayMap<String, PackageParser.Package>(); 660 661 final ArrayMap<String, Set<String>> mKnownCodebase = 662 new ArrayMap<String, Set<String>>(); 663 664 // List of APK paths to load for each user and package. This data is never 665 // persisted by the package manager. Instead, the overlay manager will 666 // ensure the data is up-to-date in runtime. 667 @GuardedBy("mPackages") 668 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 669 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 670 671 /** 672 * Tracks new system packages [received in an OTA] that we expect to 673 * find updated user-installed versions. Keys are package name, values 674 * are package location. 675 */ 676 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 677 /** 678 * Tracks high priority intent filters for protected actions. During boot, certain 679 * filter actions are protected and should never be allowed to have a high priority 680 * intent filter for them. However, there is one, and only one exception -- the 681 * setup wizard. It must be able to define a high priority intent filter for these 682 * actions to ensure there are no escapes from the wizard. We need to delay processing 683 * of these during boot as we need to look at all of the system packages in order 684 * to know which component is the setup wizard. 685 */ 686 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 687 /** 688 * Whether or not processing protected filters should be deferred. 689 */ 690 private boolean mDeferProtectedFilters = true; 691 692 /** 693 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 694 */ 695 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 696 /** 697 * Whether or not system app permissions should be promoted from install to runtime. 698 */ 699 boolean mPromoteSystemApps; 700 701 @GuardedBy("mPackages") 702 final Settings mSettings; 703 704 /** 705 * Set of package names that are currently "frozen", which means active 706 * surgery is being done on the code/data for that package. The platform 707 * will refuse to launch frozen packages to avoid race conditions. 708 * 709 * @see PackageFreezer 710 */ 711 @GuardedBy("mPackages") 712 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 713 714 final ProtectedPackages mProtectedPackages; 715 716 boolean mFirstBoot; 717 718 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 719 720 // System configuration read by SystemConfig. 721 final int[] mGlobalGids; 722 final SparseArray<ArraySet<String>> mSystemPermissions; 723 @GuardedBy("mAvailableFeatures") 724 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 725 726 // If mac_permissions.xml was found for seinfo labeling. 727 boolean mFoundPolicyFile; 728 729 private final InstantAppRegistry mInstantAppRegistry; 730 731 @GuardedBy("mPackages") 732 int mChangedPackagesSequenceNumber; 733 /** 734 * List of changed [installed, removed or updated] packages. 735 * mapping from user id -> sequence number -> package name 736 */ 737 @GuardedBy("mPackages") 738 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 739 /** 740 * The sequence number of the last change to a package. 741 * mapping from user id -> package name -> sequence number 742 */ 743 @GuardedBy("mPackages") 744 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 745 746 public static final class SharedLibraryEntry { 747 public final String path; 748 public final String apk; 749 public final SharedLibraryInfo info; 750 751 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 752 String declaringPackageName, int declaringPackageVersionCode) { 753 path = _path; 754 apk = _apk; 755 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 756 declaringPackageName, declaringPackageVersionCode), null); 757 } 758 } 759 760 // Currently known shared libraries. 761 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 762 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 763 new ArrayMap<>(); 764 765 // All available activities, for your resolving pleasure. 766 final ActivityIntentResolver mActivities = 767 new ActivityIntentResolver(); 768 769 // All available receivers, for your resolving pleasure. 770 final ActivityIntentResolver mReceivers = 771 new ActivityIntentResolver(); 772 773 // All available services, for your resolving pleasure. 774 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 775 776 // All available providers, for your resolving pleasure. 777 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 778 779 // Mapping from provider base names (first directory in content URI codePath) 780 // to the provider information. 781 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 782 new ArrayMap<String, PackageParser.Provider>(); 783 784 // Mapping from instrumentation class names to info about them. 785 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 786 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 787 788 // Mapping from permission names to info about them. 789 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 790 new ArrayMap<String, PackageParser.PermissionGroup>(); 791 792 // Packages whose data we have transfered into another package, thus 793 // should no longer exist. 794 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 795 796 // Broadcast actions that are only available to the system. 797 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 798 799 /** List of packages waiting for verification. */ 800 final SparseArray<PackageVerificationState> mPendingVerification 801 = new SparseArray<PackageVerificationState>(); 802 803 /** Set of packages associated with each app op permission. */ 804 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 805 806 final PackageInstallerService mInstallerService; 807 808 private final PackageDexOptimizer mPackageDexOptimizer; 809 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 810 // is used by other apps). 811 private final DexManager mDexManager; 812 813 private AtomicInteger mNextMoveId = new AtomicInteger(); 814 private final MoveCallbacks mMoveCallbacks; 815 816 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 817 818 // Cache of users who need badging. 819 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 820 821 /** Token for keys in mPendingVerification. */ 822 private int mPendingVerificationToken = 0; 823 824 volatile boolean mSystemReady; 825 volatile boolean mSafeMode; 826 volatile boolean mHasSystemUidErrors; 827 828 ApplicationInfo mAndroidApplication; 829 final ActivityInfo mResolveActivity = new ActivityInfo(); 830 final ResolveInfo mResolveInfo = new ResolveInfo(); 831 ComponentName mResolveComponentName; 832 PackageParser.Package mPlatformPackage; 833 ComponentName mCustomResolverComponentName; 834 835 boolean mResolverReplaced = false; 836 837 private final @Nullable ComponentName mIntentFilterVerifierComponent; 838 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 839 840 private int mIntentFilterVerificationToken = 0; 841 842 /** The service connection to the ephemeral resolver */ 843 final EphemeralResolverConnection mInstantAppResolverConnection; 844 845 /** Component used to install ephemeral applications */ 846 ComponentName mInstantAppInstallerComponent; 847 final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo(); 848 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 849 850 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 851 = new SparseArray<IntentFilterVerificationState>(); 852 853 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 854 855 // List of packages names to keep cached, even if they are uninstalled for all users 856 private List<String> mKeepUninstalledPackages; 857 858 private UserManagerInternal mUserManagerInternal; 859 860 private DeviceIdleController.LocalService mDeviceIdleController; 861 862 private File mCacheDir; 863 864 private ArraySet<String> mPrivappPermissionsViolations; 865 866 private Future<?> mPrepareAppDataFuture; 867 868 private static class IFVerificationParams { 869 PackageParser.Package pkg; 870 boolean replacing; 871 int userId; 872 int verifierUid; 873 874 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 875 int _userId, int _verifierUid) { 876 pkg = _pkg; 877 replacing = _replacing; 878 userId = _userId; 879 replacing = _replacing; 880 verifierUid = _verifierUid; 881 } 882 } 883 884 private interface IntentFilterVerifier<T extends IntentFilter> { 885 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 886 T filter, String packageName); 887 void startVerifications(int userId); 888 void receiveVerificationResponse(int verificationId); 889 } 890 891 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 892 private Context mContext; 893 private ComponentName mIntentFilterVerifierComponent; 894 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 895 896 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 897 mContext = context; 898 mIntentFilterVerifierComponent = verifierComponent; 899 } 900 901 private String getDefaultScheme() { 902 return IntentFilter.SCHEME_HTTPS; 903 } 904 905 @Override 906 public void startVerifications(int userId) { 907 // Launch verifications requests 908 int count = mCurrentIntentFilterVerifications.size(); 909 for (int n=0; n<count; n++) { 910 int verificationId = mCurrentIntentFilterVerifications.get(n); 911 final IntentFilterVerificationState ivs = 912 mIntentFilterVerificationStates.get(verificationId); 913 914 String packageName = ivs.getPackageName(); 915 916 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 917 final int filterCount = filters.size(); 918 ArraySet<String> domainsSet = new ArraySet<>(); 919 for (int m=0; m<filterCount; m++) { 920 PackageParser.ActivityIntentInfo filter = filters.get(m); 921 domainsSet.addAll(filter.getHostsList()); 922 } 923 synchronized (mPackages) { 924 if (mSettings.createIntentFilterVerificationIfNeededLPw( 925 packageName, domainsSet) != null) { 926 scheduleWriteSettingsLocked(); 927 } 928 } 929 sendVerificationRequest(userId, verificationId, ivs); 930 } 931 mCurrentIntentFilterVerifications.clear(); 932 } 933 934 private void sendVerificationRequest(int userId, int verificationId, 935 IntentFilterVerificationState ivs) { 936 937 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 938 verificationIntent.putExtra( 939 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 940 verificationId); 941 verificationIntent.putExtra( 942 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 943 getDefaultScheme()); 944 verificationIntent.putExtra( 945 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 946 ivs.getHostsString()); 947 verificationIntent.putExtra( 948 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 949 ivs.getPackageName()); 950 verificationIntent.setComponent(mIntentFilterVerifierComponent); 951 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 952 953 UserHandle user = new UserHandle(userId); 954 mContext.sendBroadcastAsUser(verificationIntent, user); 955 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 956 "Sending IntentFilter verification broadcast"); 957 } 958 959 public void receiveVerificationResponse(int verificationId) { 960 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 961 962 final boolean verified = ivs.isVerified(); 963 964 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 965 final int count = filters.size(); 966 if (DEBUG_DOMAIN_VERIFICATION) { 967 Slog.i(TAG, "Received verification response " + verificationId 968 + " for " + count + " filters, verified=" + verified); 969 } 970 for (int n=0; n<count; n++) { 971 PackageParser.ActivityIntentInfo filter = filters.get(n); 972 filter.setVerified(verified); 973 974 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 975 + " verified with result:" + verified + " and hosts:" 976 + ivs.getHostsString()); 977 } 978 979 mIntentFilterVerificationStates.remove(verificationId); 980 981 final String packageName = ivs.getPackageName(); 982 IntentFilterVerificationInfo ivi = null; 983 984 synchronized (mPackages) { 985 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 986 } 987 if (ivi == null) { 988 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 989 + verificationId + " packageName:" + packageName); 990 return; 991 } 992 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 993 "Updating IntentFilterVerificationInfo for package " + packageName 994 +" verificationId:" + verificationId); 995 996 synchronized (mPackages) { 997 if (verified) { 998 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 999 } else { 1000 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1001 } 1002 scheduleWriteSettingsLocked(); 1003 1004 final int userId = ivs.getUserId(); 1005 if (userId != UserHandle.USER_ALL) { 1006 final int userStatus = 1007 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1008 1009 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1010 boolean needUpdate = false; 1011 1012 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1013 // already been set by the User thru the Disambiguation dialog 1014 switch (userStatus) { 1015 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1016 if (verified) { 1017 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1018 } else { 1019 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1020 } 1021 needUpdate = true; 1022 break; 1023 1024 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1025 if (verified) { 1026 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1027 needUpdate = true; 1028 } 1029 break; 1030 1031 default: 1032 // Nothing to do 1033 } 1034 1035 if (needUpdate) { 1036 mSettings.updateIntentFilterVerificationStatusLPw( 1037 packageName, updatedStatus, userId); 1038 scheduleWritePackageRestrictionsLocked(userId); 1039 } 1040 } 1041 } 1042 } 1043 1044 @Override 1045 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1046 ActivityIntentInfo filter, String packageName) { 1047 if (!hasValidDomains(filter)) { 1048 return false; 1049 } 1050 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1051 if (ivs == null) { 1052 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1053 packageName); 1054 } 1055 if (DEBUG_DOMAIN_VERIFICATION) { 1056 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1057 } 1058 ivs.addFilter(filter); 1059 return true; 1060 } 1061 1062 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1063 int userId, int verificationId, String packageName) { 1064 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1065 verifierUid, userId, packageName); 1066 ivs.setPendingState(); 1067 synchronized (mPackages) { 1068 mIntentFilterVerificationStates.append(verificationId, ivs); 1069 mCurrentIntentFilterVerifications.add(verificationId); 1070 } 1071 return ivs; 1072 } 1073 } 1074 1075 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1076 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1077 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1078 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1079 } 1080 1081 // Set of pending broadcasts for aggregating enable/disable of components. 1082 static class PendingPackageBroadcasts { 1083 // for each user id, a map of <package name -> components within that package> 1084 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1085 1086 public PendingPackageBroadcasts() { 1087 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1088 } 1089 1090 public ArrayList<String> get(int userId, String packageName) { 1091 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1092 return packages.get(packageName); 1093 } 1094 1095 public void put(int userId, String packageName, ArrayList<String> components) { 1096 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1097 packages.put(packageName, components); 1098 } 1099 1100 public void remove(int userId, String packageName) { 1101 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1102 if (packages != null) { 1103 packages.remove(packageName); 1104 } 1105 } 1106 1107 public void remove(int userId) { 1108 mUidMap.remove(userId); 1109 } 1110 1111 public int userIdCount() { 1112 return mUidMap.size(); 1113 } 1114 1115 public int userIdAt(int n) { 1116 return mUidMap.keyAt(n); 1117 } 1118 1119 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1120 return mUidMap.get(userId); 1121 } 1122 1123 public int size() { 1124 // total number of pending broadcast entries across all userIds 1125 int num = 0; 1126 for (int i = 0; i< mUidMap.size(); i++) { 1127 num += mUidMap.valueAt(i).size(); 1128 } 1129 return num; 1130 } 1131 1132 public void clear() { 1133 mUidMap.clear(); 1134 } 1135 1136 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1137 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1138 if (map == null) { 1139 map = new ArrayMap<String, ArrayList<String>>(); 1140 mUidMap.put(userId, map); 1141 } 1142 return map; 1143 } 1144 } 1145 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1146 1147 // Service Connection to remote media container service to copy 1148 // package uri's from external media onto secure containers 1149 // or internal storage. 1150 private IMediaContainerService mContainerService = null; 1151 1152 static final int SEND_PENDING_BROADCAST = 1; 1153 static final int MCS_BOUND = 3; 1154 static final int END_COPY = 4; 1155 static final int INIT_COPY = 5; 1156 static final int MCS_UNBIND = 6; 1157 static final int START_CLEANING_PACKAGE = 7; 1158 static final int FIND_INSTALL_LOC = 8; 1159 static final int POST_INSTALL = 9; 1160 static final int MCS_RECONNECT = 10; 1161 static final int MCS_GIVE_UP = 11; 1162 static final int UPDATED_MEDIA_STATUS = 12; 1163 static final int WRITE_SETTINGS = 13; 1164 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1165 static final int PACKAGE_VERIFIED = 15; 1166 static final int CHECK_PENDING_VERIFICATION = 16; 1167 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1168 static final int INTENT_FILTER_VERIFIED = 18; 1169 static final int WRITE_PACKAGE_LIST = 19; 1170 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1171 1172 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1173 1174 // Delay time in millisecs 1175 static final int BROADCAST_DELAY = 10 * 1000; 1176 1177 static UserManagerService sUserManager; 1178 1179 // Stores a list of users whose package restrictions file needs to be updated 1180 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1181 1182 final private DefaultContainerConnection mDefContainerConn = 1183 new DefaultContainerConnection(); 1184 class DefaultContainerConnection implements ServiceConnection { 1185 public void onServiceConnected(ComponentName name, IBinder service) { 1186 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1187 final IMediaContainerService imcs = IMediaContainerService.Stub 1188 .asInterface(Binder.allowBlocking(service)); 1189 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1190 } 1191 1192 public void onServiceDisconnected(ComponentName name) { 1193 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1194 } 1195 } 1196 1197 // Recordkeeping of restore-after-install operations that are currently in flight 1198 // between the Package Manager and the Backup Manager 1199 static class PostInstallData { 1200 public InstallArgs args; 1201 public PackageInstalledInfo res; 1202 1203 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1204 args = _a; 1205 res = _r; 1206 } 1207 } 1208 1209 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1210 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1211 1212 // XML tags for backup/restore of various bits of state 1213 private static final String TAG_PREFERRED_BACKUP = "pa"; 1214 private static final String TAG_DEFAULT_APPS = "da"; 1215 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1216 1217 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1218 private static final String TAG_ALL_GRANTS = "rt-grants"; 1219 private static final String TAG_GRANT = "grant"; 1220 private static final String ATTR_PACKAGE_NAME = "pkg"; 1221 1222 private static final String TAG_PERMISSION = "perm"; 1223 private static final String ATTR_PERMISSION_NAME = "name"; 1224 private static final String ATTR_IS_GRANTED = "g"; 1225 private static final String ATTR_USER_SET = "set"; 1226 private static final String ATTR_USER_FIXED = "fixed"; 1227 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1228 1229 // System/policy permission grants are not backed up 1230 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1231 FLAG_PERMISSION_POLICY_FIXED 1232 | FLAG_PERMISSION_SYSTEM_FIXED 1233 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1234 1235 // And we back up these user-adjusted states 1236 private static final int USER_RUNTIME_GRANT_MASK = 1237 FLAG_PERMISSION_USER_SET 1238 | FLAG_PERMISSION_USER_FIXED 1239 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1240 1241 final @Nullable String mRequiredVerifierPackage; 1242 final @NonNull String mRequiredInstallerPackage; 1243 final @NonNull String mRequiredUninstallerPackage; 1244 final @Nullable String mSetupWizardPackage; 1245 final @Nullable String mStorageManagerPackage; 1246 final @NonNull String mServicesSystemSharedLibraryPackageName; 1247 final @NonNull String mSharedSystemSharedLibraryPackageName; 1248 1249 final boolean mPermissionReviewRequired; 1250 1251 private final PackageUsage mPackageUsage = new PackageUsage(); 1252 private final CompilerStats mCompilerStats = new CompilerStats(); 1253 1254 class PackageHandler extends Handler { 1255 private boolean mBound = false; 1256 final ArrayList<HandlerParams> mPendingInstalls = 1257 new ArrayList<HandlerParams>(); 1258 1259 private boolean connectToService() { 1260 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1261 " DefaultContainerService"); 1262 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1264 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1265 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1266 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1267 mBound = true; 1268 return true; 1269 } 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1271 return false; 1272 } 1273 1274 private void disconnectService() { 1275 mContainerService = null; 1276 mBound = false; 1277 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1278 mContext.unbindService(mDefContainerConn); 1279 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1280 } 1281 1282 PackageHandler(Looper looper) { 1283 super(looper); 1284 } 1285 1286 public void handleMessage(Message msg) { 1287 try { 1288 doHandleMessage(msg); 1289 } finally { 1290 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1291 } 1292 } 1293 1294 void doHandleMessage(Message msg) { 1295 switch (msg.what) { 1296 case INIT_COPY: { 1297 HandlerParams params = (HandlerParams) msg.obj; 1298 int idx = mPendingInstalls.size(); 1299 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1300 // If a bind was already initiated we dont really 1301 // need to do anything. The pending install 1302 // will be processed later on. 1303 if (!mBound) { 1304 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1305 System.identityHashCode(mHandler)); 1306 // If this is the only one pending we might 1307 // have to bind to the service again. 1308 if (!connectToService()) { 1309 Slog.e(TAG, "Failed to bind to media container service"); 1310 params.serviceError(); 1311 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1312 System.identityHashCode(mHandler)); 1313 if (params.traceMethod != null) { 1314 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1315 params.traceCookie); 1316 } 1317 return; 1318 } else { 1319 // Once we bind to the service, the first 1320 // pending request will be processed. 1321 mPendingInstalls.add(idx, params); 1322 } 1323 } else { 1324 mPendingInstalls.add(idx, params); 1325 // Already bound to the service. Just make 1326 // sure we trigger off processing the first request. 1327 if (idx == 0) { 1328 mHandler.sendEmptyMessage(MCS_BOUND); 1329 } 1330 } 1331 break; 1332 } 1333 case MCS_BOUND: { 1334 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1335 if (msg.obj != null) { 1336 mContainerService = (IMediaContainerService) msg.obj; 1337 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1338 System.identityHashCode(mHandler)); 1339 } 1340 if (mContainerService == null) { 1341 if (!mBound) { 1342 // Something seriously wrong since we are not bound and we are not 1343 // waiting for connection. Bail out. 1344 Slog.e(TAG, "Cannot bind to media container service"); 1345 for (HandlerParams params : mPendingInstalls) { 1346 // Indicate service bind error 1347 params.serviceError(); 1348 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1349 System.identityHashCode(params)); 1350 if (params.traceMethod != null) { 1351 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1352 params.traceMethod, params.traceCookie); 1353 } 1354 return; 1355 } 1356 mPendingInstalls.clear(); 1357 } else { 1358 Slog.w(TAG, "Waiting to connect to media container service"); 1359 } 1360 } else if (mPendingInstalls.size() > 0) { 1361 HandlerParams params = mPendingInstalls.get(0); 1362 if (params != null) { 1363 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1364 System.identityHashCode(params)); 1365 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1366 if (params.startCopy()) { 1367 // We are done... look for more work or to 1368 // go idle. 1369 if (DEBUG_SD_INSTALL) Log.i(TAG, 1370 "Checking for more work or unbind..."); 1371 // Delete pending install 1372 if (mPendingInstalls.size() > 0) { 1373 mPendingInstalls.remove(0); 1374 } 1375 if (mPendingInstalls.size() == 0) { 1376 if (mBound) { 1377 if (DEBUG_SD_INSTALL) Log.i(TAG, 1378 "Posting delayed MCS_UNBIND"); 1379 removeMessages(MCS_UNBIND); 1380 Message ubmsg = obtainMessage(MCS_UNBIND); 1381 // Unbind after a little delay, to avoid 1382 // continual thrashing. 1383 sendMessageDelayed(ubmsg, 10000); 1384 } 1385 } else { 1386 // There are more pending requests in queue. 1387 // Just post MCS_BOUND message to trigger processing 1388 // of next pending install. 1389 if (DEBUG_SD_INSTALL) Log.i(TAG, 1390 "Posting MCS_BOUND for next work"); 1391 mHandler.sendEmptyMessage(MCS_BOUND); 1392 } 1393 } 1394 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1395 } 1396 } else { 1397 // Should never happen ideally. 1398 Slog.w(TAG, "Empty queue"); 1399 } 1400 break; 1401 } 1402 case MCS_RECONNECT: { 1403 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1404 if (mPendingInstalls.size() > 0) { 1405 if (mBound) { 1406 disconnectService(); 1407 } 1408 if (!connectToService()) { 1409 Slog.e(TAG, "Failed to bind to media container service"); 1410 for (HandlerParams params : mPendingInstalls) { 1411 // Indicate service bind error 1412 params.serviceError(); 1413 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1414 System.identityHashCode(params)); 1415 } 1416 mPendingInstalls.clear(); 1417 } 1418 } 1419 break; 1420 } 1421 case MCS_UNBIND: { 1422 // If there is no actual work left, then time to unbind. 1423 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1424 1425 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1426 if (mBound) { 1427 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1428 1429 disconnectService(); 1430 } 1431 } else if (mPendingInstalls.size() > 0) { 1432 // There are more pending requests in queue. 1433 // Just post MCS_BOUND message to trigger processing 1434 // of next pending install. 1435 mHandler.sendEmptyMessage(MCS_BOUND); 1436 } 1437 1438 break; 1439 } 1440 case MCS_GIVE_UP: { 1441 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1442 HandlerParams params = mPendingInstalls.remove(0); 1443 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1444 System.identityHashCode(params)); 1445 break; 1446 } 1447 case SEND_PENDING_BROADCAST: { 1448 String packages[]; 1449 ArrayList<String> components[]; 1450 int size = 0; 1451 int uids[]; 1452 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1453 synchronized (mPackages) { 1454 if (mPendingBroadcasts == null) { 1455 return; 1456 } 1457 size = mPendingBroadcasts.size(); 1458 if (size <= 0) { 1459 // Nothing to be done. Just return 1460 return; 1461 } 1462 packages = new String[size]; 1463 components = new ArrayList[size]; 1464 uids = new int[size]; 1465 int i = 0; // filling out the above arrays 1466 1467 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1468 int packageUserId = mPendingBroadcasts.userIdAt(n); 1469 Iterator<Map.Entry<String, ArrayList<String>>> it 1470 = mPendingBroadcasts.packagesForUserId(packageUserId) 1471 .entrySet().iterator(); 1472 while (it.hasNext() && i < size) { 1473 Map.Entry<String, ArrayList<String>> ent = it.next(); 1474 packages[i] = ent.getKey(); 1475 components[i] = ent.getValue(); 1476 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1477 uids[i] = (ps != null) 1478 ? UserHandle.getUid(packageUserId, ps.appId) 1479 : -1; 1480 i++; 1481 } 1482 } 1483 size = i; 1484 mPendingBroadcasts.clear(); 1485 } 1486 // Send broadcasts 1487 for (int i = 0; i < size; i++) { 1488 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1489 } 1490 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1491 break; 1492 } 1493 case START_CLEANING_PACKAGE: { 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1495 final String packageName = (String)msg.obj; 1496 final int userId = msg.arg1; 1497 final boolean andCode = msg.arg2 != 0; 1498 synchronized (mPackages) { 1499 if (userId == UserHandle.USER_ALL) { 1500 int[] users = sUserManager.getUserIds(); 1501 for (int user : users) { 1502 mSettings.addPackageToCleanLPw( 1503 new PackageCleanItem(user, packageName, andCode)); 1504 } 1505 } else { 1506 mSettings.addPackageToCleanLPw( 1507 new PackageCleanItem(userId, packageName, andCode)); 1508 } 1509 } 1510 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1511 startCleaningPackages(); 1512 } break; 1513 case POST_INSTALL: { 1514 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1515 1516 PostInstallData data = mRunningInstalls.get(msg.arg1); 1517 final boolean didRestore = (msg.arg2 != 0); 1518 mRunningInstalls.delete(msg.arg1); 1519 1520 if (data != null) { 1521 InstallArgs args = data.args; 1522 PackageInstalledInfo parentRes = data.res; 1523 1524 final boolean grantPermissions = (args.installFlags 1525 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1526 final boolean killApp = (args.installFlags 1527 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1528 final String[] grantedPermissions = args.installGrantPermissions; 1529 1530 // Handle the parent package 1531 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1532 grantedPermissions, didRestore, args.installerPackageName, 1533 args.observer); 1534 1535 // Handle the child packages 1536 final int childCount = (parentRes.addedChildPackages != null) 1537 ? parentRes.addedChildPackages.size() : 0; 1538 for (int i = 0; i < childCount; i++) { 1539 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1540 handlePackagePostInstall(childRes, grantPermissions, killApp, 1541 grantedPermissions, false, args.installerPackageName, 1542 args.observer); 1543 } 1544 1545 // Log tracing if needed 1546 if (args.traceMethod != null) { 1547 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1548 args.traceCookie); 1549 } 1550 } else { 1551 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1552 } 1553 1554 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1555 } break; 1556 case UPDATED_MEDIA_STATUS: { 1557 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1558 boolean reportStatus = msg.arg1 == 1; 1559 boolean doGc = msg.arg2 == 1; 1560 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1561 if (doGc) { 1562 // Force a gc to clear up stale containers. 1563 Runtime.getRuntime().gc(); 1564 } 1565 if (msg.obj != null) { 1566 @SuppressWarnings("unchecked") 1567 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1568 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1569 // Unload containers 1570 unloadAllContainers(args); 1571 } 1572 if (reportStatus) { 1573 try { 1574 if (DEBUG_SD_INSTALL) Log.i(TAG, 1575 "Invoking StorageManagerService call back"); 1576 PackageHelper.getStorageManager().finishMediaUpdate(); 1577 } catch (RemoteException e) { 1578 Log.e(TAG, "StorageManagerService not running?"); 1579 } 1580 } 1581 } break; 1582 case WRITE_SETTINGS: { 1583 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1584 synchronized (mPackages) { 1585 removeMessages(WRITE_SETTINGS); 1586 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1587 mSettings.writeLPr(); 1588 mDirtyUsers.clear(); 1589 } 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1591 } break; 1592 case WRITE_PACKAGE_RESTRICTIONS: { 1593 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1594 synchronized (mPackages) { 1595 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1596 for (int userId : mDirtyUsers) { 1597 mSettings.writePackageRestrictionsLPr(userId); 1598 } 1599 mDirtyUsers.clear(); 1600 } 1601 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1602 } break; 1603 case WRITE_PACKAGE_LIST: { 1604 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1605 synchronized (mPackages) { 1606 removeMessages(WRITE_PACKAGE_LIST); 1607 mSettings.writePackageListLPr(msg.arg1); 1608 } 1609 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1610 } break; 1611 case CHECK_PENDING_VERIFICATION: { 1612 final int verificationId = msg.arg1; 1613 final PackageVerificationState state = mPendingVerification.get(verificationId); 1614 1615 if ((state != null) && !state.timeoutExtended()) { 1616 final InstallArgs args = state.getInstallArgs(); 1617 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1618 1619 Slog.i(TAG, "Verification timed out for " + originUri); 1620 mPendingVerification.remove(verificationId); 1621 1622 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1623 1624 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1625 Slog.i(TAG, "Continuing with installation of " + originUri); 1626 state.setVerifierResponse(Binder.getCallingUid(), 1627 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1628 broadcastPackageVerified(verificationId, originUri, 1629 PackageManager.VERIFICATION_ALLOW, 1630 state.getInstallArgs().getUser()); 1631 try { 1632 ret = args.copyApk(mContainerService, true); 1633 } catch (RemoteException e) { 1634 Slog.e(TAG, "Could not contact the ContainerService"); 1635 } 1636 } else { 1637 broadcastPackageVerified(verificationId, originUri, 1638 PackageManager.VERIFICATION_REJECT, 1639 state.getInstallArgs().getUser()); 1640 } 1641 1642 Trace.asyncTraceEnd( 1643 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1644 1645 processPendingInstall(args, ret); 1646 mHandler.sendEmptyMessage(MCS_UNBIND); 1647 } 1648 break; 1649 } 1650 case PACKAGE_VERIFIED: { 1651 final int verificationId = msg.arg1; 1652 1653 final PackageVerificationState state = mPendingVerification.get(verificationId); 1654 if (state == null) { 1655 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1656 break; 1657 } 1658 1659 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1660 1661 state.setVerifierResponse(response.callerUid, response.code); 1662 1663 if (state.isVerificationComplete()) { 1664 mPendingVerification.remove(verificationId); 1665 1666 final InstallArgs args = state.getInstallArgs(); 1667 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1668 1669 int ret; 1670 if (state.isInstallAllowed()) { 1671 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1672 broadcastPackageVerified(verificationId, originUri, 1673 response.code, state.getInstallArgs().getUser()); 1674 try { 1675 ret = args.copyApk(mContainerService, true); 1676 } catch (RemoteException e) { 1677 Slog.e(TAG, "Could not contact the ContainerService"); 1678 } 1679 } else { 1680 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1681 } 1682 1683 Trace.asyncTraceEnd( 1684 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1685 1686 processPendingInstall(args, ret); 1687 mHandler.sendEmptyMessage(MCS_UNBIND); 1688 } 1689 1690 break; 1691 } 1692 case START_INTENT_FILTER_VERIFICATIONS: { 1693 IFVerificationParams params = (IFVerificationParams) msg.obj; 1694 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1695 params.replacing, params.pkg); 1696 break; 1697 } 1698 case INTENT_FILTER_VERIFIED: { 1699 final int verificationId = msg.arg1; 1700 1701 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1702 verificationId); 1703 if (state == null) { 1704 Slog.w(TAG, "Invalid IntentFilter verification token " 1705 + verificationId + " received"); 1706 break; 1707 } 1708 1709 final int userId = state.getUserId(); 1710 1711 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1712 "Processing IntentFilter verification with token:" 1713 + verificationId + " and userId:" + userId); 1714 1715 final IntentFilterVerificationResponse response = 1716 (IntentFilterVerificationResponse) msg.obj; 1717 1718 state.setVerifierResponse(response.callerUid, response.code); 1719 1720 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1721 "IntentFilter verification with token:" + verificationId 1722 + " and userId:" + userId 1723 + " is settings verifier response with response code:" 1724 + response.code); 1725 1726 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1727 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1728 + response.getFailedDomainsString()); 1729 } 1730 1731 if (state.isVerificationComplete()) { 1732 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1733 } else { 1734 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1735 "IntentFilter verification with token:" + verificationId 1736 + " was not said to be complete"); 1737 } 1738 1739 break; 1740 } 1741 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1742 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1743 mInstantAppResolverConnection, 1744 (EphemeralRequest) msg.obj, 1745 mInstantAppInstallerActivity, 1746 mHandler); 1747 } 1748 } 1749 } 1750 } 1751 1752 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1753 boolean killApp, String[] grantedPermissions, 1754 boolean launchedForRestore, String installerPackage, 1755 IPackageInstallObserver2 installObserver) { 1756 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1757 // Send the removed broadcasts 1758 if (res.removedInfo != null) { 1759 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1760 } 1761 1762 // Now that we successfully installed the package, grant runtime 1763 // permissions if requested before broadcasting the install. Also 1764 // for legacy apps in permission review mode we clear the permission 1765 // review flag which is used to emulate runtime permissions for 1766 // legacy apps. 1767 if (grantPermissions) { 1768 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1769 } 1770 1771 final boolean update = res.removedInfo != null 1772 && res.removedInfo.removedPackage != null; 1773 1774 // If this is the first time we have child packages for a disabled privileged 1775 // app that had no children, we grant requested runtime permissions to the new 1776 // children if the parent on the system image had them already granted. 1777 if (res.pkg.parentPackage != null) { 1778 synchronized (mPackages) { 1779 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1780 } 1781 } 1782 1783 synchronized (mPackages) { 1784 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1785 } 1786 1787 final String packageName = res.pkg.applicationInfo.packageName; 1788 1789 // Determine the set of users who are adding this package for 1790 // the first time vs. those who are seeing an update. 1791 int[] firstUsers = EMPTY_INT_ARRAY; 1792 int[] updateUsers = EMPTY_INT_ARRAY; 1793 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1794 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1795 for (int newUser : res.newUsers) { 1796 if (ps.getInstantApp(newUser)) { 1797 continue; 1798 } 1799 if (allNewUsers) { 1800 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1801 continue; 1802 } 1803 boolean isNew = true; 1804 for (int origUser : res.origUsers) { 1805 if (origUser == newUser) { 1806 isNew = false; 1807 break; 1808 } 1809 } 1810 if (isNew) { 1811 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1812 } else { 1813 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1814 } 1815 } 1816 1817 // Send installed broadcasts if the package is not a static shared lib. 1818 if (res.pkg.staticSharedLibName == null) { 1819 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1820 1821 // Send added for users that see the package for the first time 1822 // sendPackageAddedForNewUsers also deals with system apps 1823 int appId = UserHandle.getAppId(res.uid); 1824 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1825 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1826 1827 // Send added for users that don't see the package for the first time 1828 Bundle extras = new Bundle(1); 1829 extras.putInt(Intent.EXTRA_UID, res.uid); 1830 if (update) { 1831 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1832 } 1833 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1834 extras, 0 /*flags*/, null /*targetPackage*/, 1835 null /*finishedReceiver*/, updateUsers); 1836 1837 // Send replaced for users that don't see the package for the first time 1838 if (update) { 1839 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1840 packageName, extras, 0 /*flags*/, 1841 null /*targetPackage*/, null /*finishedReceiver*/, 1842 updateUsers); 1843 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1844 null /*package*/, null /*extras*/, 0 /*flags*/, 1845 packageName /*targetPackage*/, 1846 null /*finishedReceiver*/, updateUsers); 1847 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1848 // First-install and we did a restore, so we're responsible for the 1849 // first-launch broadcast. 1850 if (DEBUG_BACKUP) { 1851 Slog.i(TAG, "Post-restore of " + packageName 1852 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1853 } 1854 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1855 } 1856 1857 // Send broadcast package appeared if forward locked/external for all users 1858 // treat asec-hosted packages like removable media on upgrade 1859 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1860 if (DEBUG_INSTALL) { 1861 Slog.i(TAG, "upgrading pkg " + res.pkg 1862 + " is ASEC-hosted -> AVAILABLE"); 1863 } 1864 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1865 ArrayList<String> pkgList = new ArrayList<>(1); 1866 pkgList.add(packageName); 1867 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1868 } 1869 } 1870 1871 // Work that needs to happen on first install within each user 1872 if (firstUsers != null && firstUsers.length > 0) { 1873 synchronized (mPackages) { 1874 for (int userId : firstUsers) { 1875 // If this app is a browser and it's newly-installed for some 1876 // users, clear any default-browser state in those users. The 1877 // app's nature doesn't depend on the user, so we can just check 1878 // its browser nature in any user and generalize. 1879 if (packageIsBrowser(packageName, userId)) { 1880 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1881 } 1882 1883 // We may also need to apply pending (restored) runtime 1884 // permission grants within these users. 1885 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1886 } 1887 } 1888 } 1889 1890 // Log current value of "unknown sources" setting 1891 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1892 getUnknownSourcesSettings()); 1893 1894 // Force a gc to clear up things 1895 Runtime.getRuntime().gc(); 1896 1897 // Remove the replaced package's older resources safely now 1898 // We delete after a gc for applications on sdcard. 1899 if (res.removedInfo != null && res.removedInfo.args != null) { 1900 synchronized (mInstallLock) { 1901 res.removedInfo.args.doPostDeleteLI(true); 1902 } 1903 } 1904 1905 // Notify DexManager that the package was installed for new users. 1906 // The updated users should already be indexed and the package code paths 1907 // should not change. 1908 // Don't notify the manager for ephemeral apps as they are not expected to 1909 // survive long enough to benefit of background optimizations. 1910 for (int userId : firstUsers) { 1911 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1912 mDexManager.notifyPackageInstalled(info, userId); 1913 } 1914 } 1915 1916 // If someone is watching installs - notify them 1917 if (installObserver != null) { 1918 try { 1919 Bundle extras = extrasForInstallResult(res); 1920 installObserver.onPackageInstalled(res.name, res.returnCode, 1921 res.returnMsg, extras); 1922 } catch (RemoteException e) { 1923 Slog.i(TAG, "Observer no longer exists."); 1924 } 1925 } 1926 } 1927 1928 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1929 PackageParser.Package pkg) { 1930 if (pkg.parentPackage == null) { 1931 return; 1932 } 1933 if (pkg.requestedPermissions == null) { 1934 return; 1935 } 1936 final PackageSetting disabledSysParentPs = mSettings 1937 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1938 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1939 || !disabledSysParentPs.isPrivileged() 1940 || (disabledSysParentPs.childPackageNames != null 1941 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1942 return; 1943 } 1944 final int[] allUserIds = sUserManager.getUserIds(); 1945 final int permCount = pkg.requestedPermissions.size(); 1946 for (int i = 0; i < permCount; i++) { 1947 String permission = pkg.requestedPermissions.get(i); 1948 BasePermission bp = mSettings.mPermissions.get(permission); 1949 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1950 continue; 1951 } 1952 for (int userId : allUserIds) { 1953 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1954 permission, userId)) { 1955 grantRuntimePermission(pkg.packageName, permission, userId); 1956 } 1957 } 1958 } 1959 } 1960 1961 private StorageEventListener mStorageListener = new StorageEventListener() { 1962 @Override 1963 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1964 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1965 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1966 final String volumeUuid = vol.getFsUuid(); 1967 1968 // Clean up any users or apps that were removed or recreated 1969 // while this volume was missing 1970 sUserManager.reconcileUsers(volumeUuid); 1971 reconcileApps(volumeUuid); 1972 1973 // Clean up any install sessions that expired or were 1974 // cancelled while this volume was missing 1975 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1976 1977 loadPrivatePackages(vol); 1978 1979 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1980 unloadPrivatePackages(vol); 1981 } 1982 } 1983 1984 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1985 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1986 updateExternalMediaStatus(true, false); 1987 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1988 updateExternalMediaStatus(false, false); 1989 } 1990 } 1991 } 1992 1993 @Override 1994 public void onVolumeForgotten(String fsUuid) { 1995 if (TextUtils.isEmpty(fsUuid)) { 1996 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1997 return; 1998 } 1999 2000 // Remove any apps installed on the forgotten volume 2001 synchronized (mPackages) { 2002 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2003 for (PackageSetting ps : packages) { 2004 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2005 deletePackageVersioned(new VersionedPackage(ps.name, 2006 PackageManager.VERSION_CODE_HIGHEST), 2007 new LegacyPackageDeleteObserver(null).getBinder(), 2008 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2009 // Try very hard to release any references to this package 2010 // so we don't risk the system server being killed due to 2011 // open FDs 2012 AttributeCache.instance().removePackage(ps.name); 2013 } 2014 2015 mSettings.onVolumeForgotten(fsUuid); 2016 mSettings.writeLPr(); 2017 } 2018 } 2019 }; 2020 2021 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2022 String[] grantedPermissions) { 2023 for (int userId : userIds) { 2024 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2025 } 2026 } 2027 2028 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2029 String[] grantedPermissions) { 2030 SettingBase sb = (SettingBase) pkg.mExtras; 2031 if (sb == null) { 2032 return; 2033 } 2034 2035 PermissionsState permissionsState = sb.getPermissionsState(); 2036 2037 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2038 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2039 2040 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2041 >= Build.VERSION_CODES.M; 2042 2043 for (String permission : pkg.requestedPermissions) { 2044 final BasePermission bp; 2045 synchronized (mPackages) { 2046 bp = mSettings.mPermissions.get(permission); 2047 } 2048 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2049 && (grantedPermissions == null 2050 || ArrayUtils.contains(grantedPermissions, permission))) { 2051 final int flags = permissionsState.getPermissionFlags(permission, userId); 2052 if (supportsRuntimePermissions) { 2053 // Installer cannot change immutable permissions. 2054 if ((flags & immutableFlags) == 0) { 2055 grantRuntimePermission(pkg.packageName, permission, userId); 2056 } 2057 } else if (mPermissionReviewRequired) { 2058 // In permission review mode we clear the review flag when we 2059 // are asked to install the app with all permissions granted. 2060 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2061 updatePermissionFlags(permission, pkg.packageName, 2062 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2063 } 2064 } 2065 } 2066 } 2067 } 2068 2069 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2070 Bundle extras = null; 2071 switch (res.returnCode) { 2072 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2073 extras = new Bundle(); 2074 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2075 res.origPermission); 2076 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2077 res.origPackage); 2078 break; 2079 } 2080 case PackageManager.INSTALL_SUCCEEDED: { 2081 extras = new Bundle(); 2082 extras.putBoolean(Intent.EXTRA_REPLACING, 2083 res.removedInfo != null && res.removedInfo.removedPackage != null); 2084 break; 2085 } 2086 } 2087 return extras; 2088 } 2089 2090 void scheduleWriteSettingsLocked() { 2091 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2092 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2093 } 2094 } 2095 2096 void scheduleWritePackageListLocked(int userId) { 2097 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2098 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2099 msg.arg1 = userId; 2100 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2101 } 2102 } 2103 2104 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2105 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2106 scheduleWritePackageRestrictionsLocked(userId); 2107 } 2108 2109 void scheduleWritePackageRestrictionsLocked(int userId) { 2110 final int[] userIds = (userId == UserHandle.USER_ALL) 2111 ? sUserManager.getUserIds() : new int[]{userId}; 2112 for (int nextUserId : userIds) { 2113 if (!sUserManager.exists(nextUserId)) return; 2114 mDirtyUsers.add(nextUserId); 2115 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2116 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2117 } 2118 } 2119 } 2120 2121 public static PackageManagerService main(Context context, Installer installer, 2122 boolean factoryTest, boolean onlyCore) { 2123 // Self-check for initial settings. 2124 PackageManagerServiceCompilerMapping.checkProperties(); 2125 2126 PackageManagerService m = new PackageManagerService(context, installer, 2127 factoryTest, onlyCore); 2128 m.enableSystemUserPackages(); 2129 ServiceManager.addService("package", m); 2130 return m; 2131 } 2132 2133 private void enableSystemUserPackages() { 2134 if (!UserManager.isSplitSystemUser()) { 2135 return; 2136 } 2137 // For system user, enable apps based on the following conditions: 2138 // - app is whitelisted or belong to one of these groups: 2139 // -- system app which has no launcher icons 2140 // -- system app which has INTERACT_ACROSS_USERS permission 2141 // -- system IME app 2142 // - app is not in the blacklist 2143 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2144 Set<String> enableApps = new ArraySet<>(); 2145 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2146 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2147 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2148 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2149 enableApps.addAll(wlApps); 2150 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2151 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2152 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2153 enableApps.removeAll(blApps); 2154 Log.i(TAG, "Applications installed for system user: " + enableApps); 2155 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2156 UserHandle.SYSTEM); 2157 final int allAppsSize = allAps.size(); 2158 synchronized (mPackages) { 2159 for (int i = 0; i < allAppsSize; i++) { 2160 String pName = allAps.get(i); 2161 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2162 // Should not happen, but we shouldn't be failing if it does 2163 if (pkgSetting == null) { 2164 continue; 2165 } 2166 boolean install = enableApps.contains(pName); 2167 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2168 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2169 + " for system user"); 2170 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2171 } 2172 } 2173 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2174 } 2175 } 2176 2177 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2178 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2179 Context.DISPLAY_SERVICE); 2180 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2181 } 2182 2183 /** 2184 * Requests that files preopted on a secondary system partition be copied to the data partition 2185 * if possible. Note that the actual copying of the files is accomplished by init for security 2186 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2187 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2188 */ 2189 private static void requestCopyPreoptedFiles() { 2190 final int WAIT_TIME_MS = 100; 2191 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2192 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2193 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2194 // We will wait for up to 100 seconds. 2195 final long timeStart = SystemClock.uptimeMillis(); 2196 final long timeEnd = timeStart + 100 * 1000; 2197 long timeNow = timeStart; 2198 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2199 try { 2200 Thread.sleep(WAIT_TIME_MS); 2201 } catch (InterruptedException e) { 2202 // Do nothing 2203 } 2204 timeNow = SystemClock.uptimeMillis(); 2205 if (timeNow > timeEnd) { 2206 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2207 Slog.wtf(TAG, "cppreopt did not finish!"); 2208 break; 2209 } 2210 } 2211 2212 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2213 } 2214 } 2215 2216 public PackageManagerService(Context context, Installer installer, 2217 boolean factoryTest, boolean onlyCore) { 2218 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2219 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2220 SystemClock.uptimeMillis()); 2221 2222 if (mSdkVersion <= 0) { 2223 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2224 } 2225 2226 mContext = context; 2227 2228 mPermissionReviewRequired = context.getResources().getBoolean( 2229 R.bool.config_permissionReviewRequired); 2230 2231 mFactoryTest = factoryTest; 2232 mOnlyCore = onlyCore; 2233 mMetrics = new DisplayMetrics(); 2234 mSettings = new Settings(mPackages); 2235 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2236 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2237 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2240 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2241 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2242 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2243 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2244 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2245 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2246 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2247 2248 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2249 if (separateProcesses != null && separateProcesses.length() > 0) { 2250 if ("*".equals(separateProcesses)) { 2251 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2252 mSeparateProcesses = null; 2253 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2254 } else { 2255 mDefParseFlags = 0; 2256 mSeparateProcesses = separateProcesses.split(","); 2257 Slog.w(TAG, "Running with debug.separate_processes: " 2258 + separateProcesses); 2259 } 2260 } else { 2261 mDefParseFlags = 0; 2262 mSeparateProcesses = null; 2263 } 2264 2265 mInstaller = installer; 2266 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2267 "*dexopt*"); 2268 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2269 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2270 2271 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2272 FgThread.get().getLooper()); 2273 2274 getDefaultDisplayMetrics(context, mMetrics); 2275 2276 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2277 SystemConfig systemConfig = SystemConfig.getInstance(); 2278 mGlobalGids = systemConfig.getGlobalGids(); 2279 mSystemPermissions = systemConfig.getSystemPermissions(); 2280 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2281 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2282 2283 mProtectedPackages = new ProtectedPackages(mContext); 2284 2285 synchronized (mInstallLock) { 2286 // writer 2287 synchronized (mPackages) { 2288 mHandlerThread = new ServiceThread(TAG, 2289 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2290 mHandlerThread.start(); 2291 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2292 mProcessLoggingHandler = new ProcessLoggingHandler(); 2293 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2294 2295 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2296 mInstantAppRegistry = new InstantAppRegistry(this); 2297 2298 File dataDir = Environment.getDataDirectory(); 2299 mAppInstallDir = new File(dataDir, "app"); 2300 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2301 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2302 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2303 sUserManager = new UserManagerService(context, this, 2304 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2305 2306 // Propagate permission configuration in to package manager. 2307 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2308 = systemConfig.getPermissions(); 2309 for (int i=0; i<permConfig.size(); i++) { 2310 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2311 BasePermission bp = mSettings.mPermissions.get(perm.name); 2312 if (bp == null) { 2313 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2314 mSettings.mPermissions.put(perm.name, bp); 2315 } 2316 if (perm.gids != null) { 2317 bp.setGids(perm.gids, perm.perUser); 2318 } 2319 } 2320 2321 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2322 final int builtInLibCount = libConfig.size(); 2323 for (int i = 0; i < builtInLibCount; i++) { 2324 String name = libConfig.keyAt(i); 2325 String path = libConfig.valueAt(i); 2326 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2327 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2328 } 2329 2330 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2331 2332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2333 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2334 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2335 2336 // Clean up orphaned packages for which the code path doesn't exist 2337 // and they are an update to a system app - caused by bug/32321269 2338 final int packageSettingCount = mSettings.mPackages.size(); 2339 for (int i = packageSettingCount - 1; i >= 0; i--) { 2340 PackageSetting ps = mSettings.mPackages.valueAt(i); 2341 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2342 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2343 mSettings.mPackages.removeAt(i); 2344 mSettings.enableSystemPackageLPw(ps.name); 2345 } 2346 } 2347 2348 if (mFirstBoot) { 2349 requestCopyPreoptedFiles(); 2350 } 2351 2352 String customResolverActivity = Resources.getSystem().getString( 2353 R.string.config_customResolverActivity); 2354 if (TextUtils.isEmpty(customResolverActivity)) { 2355 customResolverActivity = null; 2356 } else { 2357 mCustomResolverComponentName = ComponentName.unflattenFromString( 2358 customResolverActivity); 2359 } 2360 2361 long startTime = SystemClock.uptimeMillis(); 2362 2363 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2364 startTime); 2365 2366 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2367 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2368 2369 if (bootClassPath == null) { 2370 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2371 } 2372 2373 if (systemServerClassPath == null) { 2374 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2375 } 2376 2377 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2378 final String[] dexCodeInstructionSets = 2379 getDexCodeInstructionSets( 2380 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2381 2382 /** 2383 * Ensure all external libraries have had dexopt run on them. 2384 */ 2385 if (mSharedLibraries.size() > 0) { 2386 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2387 // NOTE: For now, we're compiling these system "shared libraries" 2388 // (and framework jars) into all available architectures. It's possible 2389 // to compile them only when we come across an app that uses them (there's 2390 // already logic for that in scanPackageLI) but that adds some complexity. 2391 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2392 final int libCount = mSharedLibraries.size(); 2393 for (int i = 0; i < libCount; i++) { 2394 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2395 final int versionCount = versionedLib.size(); 2396 for (int j = 0; j < versionCount; j++) { 2397 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2398 final String libPath = libEntry.path != null 2399 ? libEntry.path : libEntry.apk; 2400 if (libPath == null) { 2401 continue; 2402 } 2403 try { 2404 // Shared libraries do not have profiles so we perform a full 2405 // AOT compilation (if needed). 2406 int dexoptNeeded = DexFile.getDexOptNeeded( 2407 libPath, dexCodeInstructionSet, 2408 getCompilerFilterForReason(REASON_SHARED_APK), 2409 false /* newProfile */); 2410 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2411 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2412 dexCodeInstructionSet, dexoptNeeded, null, 2413 DEXOPT_PUBLIC, 2414 getCompilerFilterForReason(REASON_SHARED_APK), 2415 StorageManager.UUID_PRIVATE_INTERNAL, 2416 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2417 } 2418 } catch (FileNotFoundException e) { 2419 Slog.w(TAG, "Library not found: " + libPath); 2420 } catch (IOException | InstallerException e) { 2421 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2422 + e.getMessage()); 2423 } 2424 } 2425 } 2426 } 2427 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2428 } 2429 2430 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2431 2432 final VersionInfo ver = mSettings.getInternalVersion(); 2433 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2434 2435 // when upgrading from pre-M, promote system app permissions from install to runtime 2436 mPromoteSystemApps = 2437 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2438 2439 // When upgrading from pre-N, we need to handle package extraction like first boot, 2440 // as there is no profiling data available. 2441 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2442 2443 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2444 2445 // save off the names of pre-existing system packages prior to scanning; we don't 2446 // want to automatically grant runtime permissions for new system apps 2447 if (mPromoteSystemApps) { 2448 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2449 while (pkgSettingIter.hasNext()) { 2450 PackageSetting ps = pkgSettingIter.next(); 2451 if (isSystemApp(ps)) { 2452 mExistingSystemPackages.add(ps.name); 2453 } 2454 } 2455 } 2456 2457 mCacheDir = preparePackageParserCache(mIsUpgrade); 2458 2459 // Set flag to monitor and not change apk file paths when 2460 // scanning install directories. 2461 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2462 2463 if (mIsUpgrade || mFirstBoot) { 2464 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2465 } 2466 2467 // Collect vendor overlay packages. (Do this before scanning any apps.) 2468 // For security and version matching reason, only consider 2469 // overlay packages if they reside in the right directory. 2470 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2471 if (overlayThemeDir.isEmpty()) { 2472 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2473 } 2474 if (!overlayThemeDir.isEmpty()) { 2475 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2476 | PackageParser.PARSE_IS_SYSTEM 2477 | PackageParser.PARSE_IS_SYSTEM_DIR 2478 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2479 } 2480 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2481 | PackageParser.PARSE_IS_SYSTEM 2482 | PackageParser.PARSE_IS_SYSTEM_DIR 2483 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2484 2485 // Find base frameworks (resource packages without code). 2486 scanDirTracedLI(frameworkDir, mDefParseFlags 2487 | PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR 2489 | PackageParser.PARSE_IS_PRIVILEGED, 2490 scanFlags | SCAN_NO_DEX, 0); 2491 2492 // Collected privileged system packages. 2493 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2494 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2495 | PackageParser.PARSE_IS_SYSTEM 2496 | PackageParser.PARSE_IS_SYSTEM_DIR 2497 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2498 2499 // Collect ordinary system packages. 2500 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2501 scanDirTracedLI(systemAppDir, mDefParseFlags 2502 | PackageParser.PARSE_IS_SYSTEM 2503 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2504 2505 // Collect all vendor packages. 2506 File vendorAppDir = new File("/vendor/app"); 2507 try { 2508 vendorAppDir = vendorAppDir.getCanonicalFile(); 2509 } catch (IOException e) { 2510 // failed to look up canonical path, continue with original one 2511 } 2512 scanDirTracedLI(vendorAppDir, mDefParseFlags 2513 | PackageParser.PARSE_IS_SYSTEM 2514 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2515 2516 // Collect all OEM packages. 2517 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2518 scanDirTracedLI(oemAppDir, mDefParseFlags 2519 | PackageParser.PARSE_IS_SYSTEM 2520 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2521 2522 // Prune any system packages that no longer exist. 2523 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2524 if (!mOnlyCore) { 2525 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2526 while (psit.hasNext()) { 2527 PackageSetting ps = psit.next(); 2528 2529 /* 2530 * If this is not a system app, it can't be a 2531 * disable system app. 2532 */ 2533 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2534 continue; 2535 } 2536 2537 /* 2538 * If the package is scanned, it's not erased. 2539 */ 2540 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2541 if (scannedPkg != null) { 2542 /* 2543 * If the system app is both scanned and in the 2544 * disabled packages list, then it must have been 2545 * added via OTA. Remove it from the currently 2546 * scanned package so the previously user-installed 2547 * application can be scanned. 2548 */ 2549 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2550 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2551 + ps.name + "; removing system app. Last known codePath=" 2552 + ps.codePathString + ", installStatus=" + ps.installStatus 2553 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2554 + scannedPkg.mVersionCode); 2555 removePackageLI(scannedPkg, true); 2556 mExpectingBetter.put(ps.name, ps.codePath); 2557 } 2558 2559 continue; 2560 } 2561 2562 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2563 psit.remove(); 2564 logCriticalInfo(Log.WARN, "System package " + ps.name 2565 + " no longer exists; it's data will be wiped"); 2566 // Actual deletion of code and data will be handled by later 2567 // reconciliation step 2568 } else { 2569 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2570 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2571 possiblyDeletedUpdatedSystemApps.add(ps.name); 2572 } 2573 } 2574 } 2575 } 2576 2577 //look for any incomplete package installations 2578 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2579 for (int i = 0; i < deletePkgsList.size(); i++) { 2580 // Actual deletion of code and data will be handled by later 2581 // reconciliation step 2582 final String packageName = deletePkgsList.get(i).name; 2583 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2584 synchronized (mPackages) { 2585 mSettings.removePackageLPw(packageName); 2586 } 2587 } 2588 2589 //delete tmp files 2590 deleteTempPackageFiles(); 2591 2592 // Remove any shared userIDs that have no associated packages 2593 mSettings.pruneSharedUsersLPw(); 2594 2595 if (!mOnlyCore) { 2596 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2597 SystemClock.uptimeMillis()); 2598 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2599 2600 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2601 | PackageParser.PARSE_FORWARD_LOCK, 2602 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2603 2604 /** 2605 * Remove disable package settings for any updated system 2606 * apps that were removed via an OTA. If they're not a 2607 * previously-updated app, remove them completely. 2608 * Otherwise, just revoke their system-level permissions. 2609 */ 2610 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2611 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2612 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2613 2614 String msg; 2615 if (deletedPkg == null) { 2616 msg = "Updated system package " + deletedAppName 2617 + " no longer exists; it's data will be wiped"; 2618 // Actual deletion of code and data will be handled by later 2619 // reconciliation step 2620 } else { 2621 msg = "Updated system app + " + deletedAppName 2622 + " no longer present; removing system privileges for " 2623 + deletedAppName; 2624 2625 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2626 2627 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2628 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2629 } 2630 logCriticalInfo(Log.WARN, msg); 2631 } 2632 2633 /** 2634 * Make sure all system apps that we expected to appear on 2635 * the userdata partition actually showed up. If they never 2636 * appeared, crawl back and revive the system version. 2637 */ 2638 for (int i = 0; i < mExpectingBetter.size(); i++) { 2639 final String packageName = mExpectingBetter.keyAt(i); 2640 if (!mPackages.containsKey(packageName)) { 2641 final File scanFile = mExpectingBetter.valueAt(i); 2642 2643 logCriticalInfo(Log.WARN, "Expected better " + packageName 2644 + " but never showed up; reverting to system"); 2645 2646 int reparseFlags = mDefParseFlags; 2647 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2648 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2649 | PackageParser.PARSE_IS_SYSTEM_DIR 2650 | PackageParser.PARSE_IS_PRIVILEGED; 2651 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2652 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2653 | PackageParser.PARSE_IS_SYSTEM_DIR; 2654 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2655 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2656 | PackageParser.PARSE_IS_SYSTEM_DIR; 2657 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2658 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2659 | PackageParser.PARSE_IS_SYSTEM_DIR; 2660 } else { 2661 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2662 continue; 2663 } 2664 2665 mSettings.enableSystemPackageLPw(packageName); 2666 2667 try { 2668 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2669 } catch (PackageManagerException e) { 2670 Slog.e(TAG, "Failed to parse original system package: " 2671 + e.getMessage()); 2672 } 2673 } 2674 } 2675 } 2676 mExpectingBetter.clear(); 2677 2678 // Resolve the storage manager. 2679 mStorageManagerPackage = getStorageManagerPackageName(); 2680 2681 // Resolve protected action filters. Only the setup wizard is allowed to 2682 // have a high priority filter for these actions. 2683 mSetupWizardPackage = getSetupWizardPackageName(); 2684 if (mProtectedFilters.size() > 0) { 2685 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2686 Slog.i(TAG, "No setup wizard;" 2687 + " All protected intents capped to priority 0"); 2688 } 2689 for (ActivityIntentInfo filter : mProtectedFilters) { 2690 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2691 if (DEBUG_FILTERS) { 2692 Slog.i(TAG, "Found setup wizard;" 2693 + " allow priority " + filter.getPriority() + ";" 2694 + " package: " + filter.activity.info.packageName 2695 + " activity: " + filter.activity.className 2696 + " priority: " + filter.getPriority()); 2697 } 2698 // skip setup wizard; allow it to keep the high priority filter 2699 continue; 2700 } 2701 Slog.w(TAG, "Protected action; cap priority to 0;" 2702 + " package: " + filter.activity.info.packageName 2703 + " activity: " + filter.activity.className 2704 + " origPrio: " + filter.getPriority()); 2705 filter.setPriority(0); 2706 } 2707 } 2708 mDeferProtectedFilters = false; 2709 mProtectedFilters.clear(); 2710 2711 // Now that we know all of the shared libraries, update all clients to have 2712 // the correct library paths. 2713 updateAllSharedLibrariesLPw(null); 2714 2715 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2716 // NOTE: We ignore potential failures here during a system scan (like 2717 // the rest of the commands above) because there's precious little we 2718 // can do about it. A settings error is reported, though. 2719 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2720 } 2721 2722 // Now that we know all the packages we are keeping, 2723 // read and update their last usage times. 2724 mPackageUsage.read(mPackages); 2725 mCompilerStats.read(); 2726 2727 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2728 SystemClock.uptimeMillis()); 2729 Slog.i(TAG, "Time to scan packages: " 2730 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2731 + " seconds"); 2732 2733 // If the platform SDK has changed since the last time we booted, 2734 // we need to re-grant app permission to catch any new ones that 2735 // appear. This is really a hack, and means that apps can in some 2736 // cases get permissions that the user didn't initially explicitly 2737 // allow... it would be nice to have some better way to handle 2738 // this situation. 2739 int updateFlags = UPDATE_PERMISSIONS_ALL; 2740 if (ver.sdkVersion != mSdkVersion) { 2741 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2742 + mSdkVersion + "; regranting permissions for internal storage"); 2743 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2744 } 2745 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2746 ver.sdkVersion = mSdkVersion; 2747 2748 // If this is the first boot or an update from pre-M, and it is a normal 2749 // boot, then we need to initialize the default preferred apps across 2750 // all defined users. 2751 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2752 for (UserInfo user : sUserManager.getUsers(true)) { 2753 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2754 applyFactoryDefaultBrowserLPw(user.id); 2755 primeDomainVerificationsLPw(user.id); 2756 } 2757 } 2758 2759 // Prepare storage for system user really early during boot, 2760 // since core system apps like SettingsProvider and SystemUI 2761 // can't wait for user to start 2762 final int storageFlags; 2763 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2764 storageFlags = StorageManager.FLAG_STORAGE_DE; 2765 } else { 2766 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2767 } 2768 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2769 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2770 true /* onlyCoreApps */); 2771 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2772 if (deferPackages == null || deferPackages.isEmpty()) { 2773 return; 2774 } 2775 int count = 0; 2776 for (String pkgName : deferPackages) { 2777 PackageParser.Package pkg = null; 2778 synchronized (mPackages) { 2779 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2780 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2781 pkg = ps.pkg; 2782 } 2783 } 2784 if (pkg != null) { 2785 synchronized (mInstallLock) { 2786 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2787 true /* maybeMigrateAppData */); 2788 } 2789 count++; 2790 } 2791 } 2792 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2793 }, "prepareAppData"); 2794 2795 // If this is first boot after an OTA, and a normal boot, then 2796 // we need to clear code cache directories. 2797 // Note that we do *not* clear the application profiles. These remain valid 2798 // across OTAs and are used to drive profile verification (post OTA) and 2799 // profile compilation (without waiting to collect a fresh set of profiles). 2800 if (mIsUpgrade && !onlyCore) { 2801 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2802 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2803 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2804 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2805 // No apps are running this early, so no need to freeze 2806 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2807 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2808 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2809 } 2810 } 2811 ver.fingerprint = Build.FINGERPRINT; 2812 } 2813 2814 checkDefaultBrowser(); 2815 2816 // clear only after permissions and other defaults have been updated 2817 mExistingSystemPackages.clear(); 2818 mPromoteSystemApps = false; 2819 2820 // All the changes are done during package scanning. 2821 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2822 2823 // can downgrade to reader 2824 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2825 mSettings.writeLPr(); 2826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2827 2828 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2829 // early on (before the package manager declares itself as early) because other 2830 // components in the system server might ask for package contexts for these apps. 2831 // 2832 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2833 // (i.e, that the data partition is unavailable). 2834 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2835 long start = System.nanoTime(); 2836 List<PackageParser.Package> coreApps = new ArrayList<>(); 2837 for (PackageParser.Package pkg : mPackages.values()) { 2838 if (pkg.coreApp) { 2839 coreApps.add(pkg); 2840 } 2841 } 2842 2843 int[] stats = performDexOptUpgrade(coreApps, false, 2844 getCompilerFilterForReason(REASON_CORE_APP)); 2845 2846 final int elapsedTimeSeconds = 2847 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2848 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2849 2850 if (DEBUG_DEXOPT) { 2851 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2852 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2853 } 2854 2855 2856 // TODO: Should we log these stats to tron too ? 2857 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2858 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2859 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2860 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2861 } 2862 2863 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2864 SystemClock.uptimeMillis()); 2865 2866 if (!mOnlyCore) { 2867 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2868 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2869 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2870 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2871 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2872 mIntentFilterVerifierComponent); 2873 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2874 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2875 SharedLibraryInfo.VERSION_UNDEFINED); 2876 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2877 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2878 SharedLibraryInfo.VERSION_UNDEFINED); 2879 } else { 2880 mRequiredVerifierPackage = null; 2881 mRequiredInstallerPackage = null; 2882 mRequiredUninstallerPackage = null; 2883 mIntentFilterVerifierComponent = null; 2884 mIntentFilterVerifier = null; 2885 mServicesSystemSharedLibraryPackageName = null; 2886 mSharedSystemSharedLibraryPackageName = null; 2887 } 2888 2889 mInstallerService = new PackageInstallerService(context, this); 2890 2891 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2892 if (ephemeralResolverComponent != null) { 2893 if (DEBUG_EPHEMERAL) { 2894 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2895 } 2896 mInstantAppResolverConnection = 2897 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2898 } else { 2899 mInstantAppResolverConnection = null; 2900 } 2901 mInstantAppInstallerComponent = getEphemeralInstallerLPr(); 2902 if (mInstantAppInstallerComponent != null) { 2903 if (DEBUG_EPHEMERAL) { 2904 Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent); 2905 } 2906 setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent); 2907 } 2908 2909 // Read and update the usage of dex files. 2910 // Do this at the end of PM init so that all the packages have their 2911 // data directory reconciled. 2912 // At this point we know the code paths of the packages, so we can validate 2913 // the disk file and build the internal cache. 2914 // The usage file is expected to be small so loading and verifying it 2915 // should take a fairly small time compare to the other activities (e.g. package 2916 // scanning). 2917 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2918 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2919 for (int userId : currentUserIds) { 2920 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2921 } 2922 mDexManager.load(userPackages); 2923 } // synchronized (mPackages) 2924 } // synchronized (mInstallLock) 2925 2926 // Now after opening every single application zip, make sure they 2927 // are all flushed. Not really needed, but keeps things nice and 2928 // tidy. 2929 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2930 Runtime.getRuntime().gc(); 2931 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2932 2933 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2934 FallbackCategoryProvider.loadFallbacks(); 2935 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2936 2937 // The initial scanning above does many calls into installd while 2938 // holding the mPackages lock, but we're mostly interested in yelling 2939 // once we have a booted system. 2940 mInstaller.setWarnIfHeld(mPackages); 2941 2942 // Expose private service for system components to use. 2943 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2944 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2945 } 2946 2947 private static File preparePackageParserCache(boolean isUpgrade) { 2948 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2949 return null; 2950 } 2951 2952 // Disable package parsing on eng builds to allow for faster incremental development. 2953 if ("eng".equals(Build.TYPE)) { 2954 return null; 2955 } 2956 2957 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2958 Slog.i(TAG, "Disabling package parser cache due to system property."); 2959 return null; 2960 } 2961 2962 // The base directory for the package parser cache lives under /data/system/. 2963 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2964 "package_cache"); 2965 if (cacheBaseDir == null) { 2966 return null; 2967 } 2968 2969 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2970 // This also serves to "GC" unused entries when the package cache version changes (which 2971 // can only happen during upgrades). 2972 if (isUpgrade) { 2973 FileUtils.deleteContents(cacheBaseDir); 2974 } 2975 2976 2977 // Return the versioned package cache directory. This is something like 2978 // "/data/system/package_cache/1" 2979 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2980 2981 // The following is a workaround to aid development on non-numbered userdebug 2982 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2983 // the system partition is newer. 2984 // 2985 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2986 // that starts with "eng." to signify that this is an engineering build and not 2987 // destined for release. 2988 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2989 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2990 2991 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2992 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2993 // in general and should not be used for production changes. In this specific case, 2994 // we know that they will work. 2995 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2996 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2997 FileUtils.deleteContents(cacheBaseDir); 2998 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2999 } 3000 } 3001 3002 return cacheDir; 3003 } 3004 3005 @Override 3006 public boolean isFirstBoot() { 3007 return mFirstBoot; 3008 } 3009 3010 @Override 3011 public boolean isOnlyCoreApps() { 3012 return mOnlyCore; 3013 } 3014 3015 @Override 3016 public boolean isUpgrade() { 3017 return mIsUpgrade; 3018 } 3019 3020 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3021 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3022 3023 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3024 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3025 UserHandle.USER_SYSTEM); 3026 if (matches.size() == 1) { 3027 return matches.get(0).getComponentInfo().packageName; 3028 } else if (matches.size() == 0) { 3029 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3030 return null; 3031 } 3032 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3033 } 3034 3035 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3036 synchronized (mPackages) { 3037 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3038 if (libraryEntry == null) { 3039 throw new IllegalStateException("Missing required shared library:" + name); 3040 } 3041 return libraryEntry.apk; 3042 } 3043 } 3044 3045 private @NonNull String getRequiredInstallerLPr() { 3046 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3047 intent.addCategory(Intent.CATEGORY_DEFAULT); 3048 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3049 3050 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3051 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3052 UserHandle.USER_SYSTEM); 3053 if (matches.size() == 1) { 3054 ResolveInfo resolveInfo = matches.get(0); 3055 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3056 throw new RuntimeException("The installer must be a privileged app"); 3057 } 3058 return matches.get(0).getComponentInfo().packageName; 3059 } else { 3060 throw new RuntimeException("There must be exactly one installer; found " + matches); 3061 } 3062 } 3063 3064 private @NonNull String getRequiredUninstallerLPr() { 3065 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3066 intent.addCategory(Intent.CATEGORY_DEFAULT); 3067 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3068 3069 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3070 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3071 UserHandle.USER_SYSTEM); 3072 if (resolveInfo == null || 3073 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3074 throw new RuntimeException("There must be exactly one uninstaller; found " 3075 + resolveInfo); 3076 } 3077 return resolveInfo.getComponentInfo().packageName; 3078 } 3079 3080 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3081 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3082 3083 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3084 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3085 UserHandle.USER_SYSTEM); 3086 ResolveInfo best = null; 3087 final int N = matches.size(); 3088 for (int i = 0; i < N; i++) { 3089 final ResolveInfo cur = matches.get(i); 3090 final String packageName = cur.getComponentInfo().packageName; 3091 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3092 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3093 continue; 3094 } 3095 3096 if (best == null || cur.priority > best.priority) { 3097 best = cur; 3098 } 3099 } 3100 3101 if (best != null) { 3102 return best.getComponentInfo().getComponentName(); 3103 } else { 3104 throw new RuntimeException("There must be at least one intent filter verifier"); 3105 } 3106 } 3107 3108 private @Nullable ComponentName getEphemeralResolverLPr() { 3109 final String[] packageArray = 3110 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3111 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3112 if (DEBUG_EPHEMERAL) { 3113 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3114 } 3115 return null; 3116 } 3117 3118 final int resolveFlags = 3119 MATCH_DIRECT_BOOT_AWARE 3120 | MATCH_DIRECT_BOOT_UNAWARE 3121 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3122 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3123 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3124 resolveFlags, UserHandle.USER_SYSTEM); 3125 3126 final int N = resolvers.size(); 3127 if (N == 0) { 3128 if (DEBUG_EPHEMERAL) { 3129 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3130 } 3131 return null; 3132 } 3133 3134 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3135 for (int i = 0; i < N; i++) { 3136 final ResolveInfo info = resolvers.get(i); 3137 3138 if (info.serviceInfo == null) { 3139 continue; 3140 } 3141 3142 final String packageName = info.serviceInfo.packageName; 3143 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3144 if (DEBUG_EPHEMERAL) { 3145 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3146 + " pkg: " + packageName + ", info:" + info); 3147 } 3148 continue; 3149 } 3150 3151 if (DEBUG_EPHEMERAL) { 3152 Slog.v(TAG, "Ephemeral resolver found;" 3153 + " pkg: " + packageName + ", info:" + info); 3154 } 3155 return new ComponentName(packageName, info.serviceInfo.name); 3156 } 3157 if (DEBUG_EPHEMERAL) { 3158 Slog.v(TAG, "Ephemeral resolver NOT found"); 3159 } 3160 return null; 3161 } 3162 3163 private @Nullable ComponentName getEphemeralInstallerLPr() { 3164 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3165 intent.addCategory(Intent.CATEGORY_DEFAULT); 3166 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3167 3168 final int resolveFlags = 3169 MATCH_DIRECT_BOOT_AWARE 3170 | MATCH_DIRECT_BOOT_UNAWARE 3171 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3172 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3173 resolveFlags, UserHandle.USER_SYSTEM); 3174 Iterator<ResolveInfo> iter = matches.iterator(); 3175 while (iter.hasNext()) { 3176 final ResolveInfo rInfo = iter.next(); 3177 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3178 if (ps != null) { 3179 final PermissionsState permissionsState = ps.getPermissionsState(); 3180 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3181 continue; 3182 } 3183 } 3184 iter.remove(); 3185 } 3186 if (matches.size() == 0) { 3187 return null; 3188 } else if (matches.size() == 1) { 3189 return matches.get(0).getComponentInfo().getComponentName(); 3190 } else { 3191 throw new RuntimeException( 3192 "There must be at most one ephemeral installer; found " + matches); 3193 } 3194 } 3195 3196 private void primeDomainVerificationsLPw(int userId) { 3197 if (DEBUG_DOMAIN_VERIFICATION) { 3198 Slog.d(TAG, "Priming domain verifications in user " + userId); 3199 } 3200 3201 SystemConfig systemConfig = SystemConfig.getInstance(); 3202 ArraySet<String> packages = systemConfig.getLinkedApps(); 3203 3204 for (String packageName : packages) { 3205 PackageParser.Package pkg = mPackages.get(packageName); 3206 if (pkg != null) { 3207 if (!pkg.isSystemApp()) { 3208 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3209 continue; 3210 } 3211 3212 ArraySet<String> domains = null; 3213 for (PackageParser.Activity a : pkg.activities) { 3214 for (ActivityIntentInfo filter : a.intents) { 3215 if (hasValidDomains(filter)) { 3216 if (domains == null) { 3217 domains = new ArraySet<String>(); 3218 } 3219 domains.addAll(filter.getHostsList()); 3220 } 3221 } 3222 } 3223 3224 if (domains != null && domains.size() > 0) { 3225 if (DEBUG_DOMAIN_VERIFICATION) { 3226 Slog.v(TAG, " + " + packageName); 3227 } 3228 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3229 // state w.r.t. the formal app-linkage "no verification attempted" state; 3230 // and then 'always' in the per-user state actually used for intent resolution. 3231 final IntentFilterVerificationInfo ivi; 3232 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3233 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3234 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3235 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3236 } else { 3237 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3238 + "' does not handle web links"); 3239 } 3240 } else { 3241 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3242 } 3243 } 3244 3245 scheduleWritePackageRestrictionsLocked(userId); 3246 scheduleWriteSettingsLocked(); 3247 } 3248 3249 private void applyFactoryDefaultBrowserLPw(int userId) { 3250 // The default browser app's package name is stored in a string resource, 3251 // with a product-specific overlay used for vendor customization. 3252 String browserPkg = mContext.getResources().getString( 3253 com.android.internal.R.string.default_browser); 3254 if (!TextUtils.isEmpty(browserPkg)) { 3255 // non-empty string => required to be a known package 3256 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3257 if (ps == null) { 3258 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3259 browserPkg = null; 3260 } else { 3261 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3262 } 3263 } 3264 3265 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3266 // default. If there's more than one, just leave everything alone. 3267 if (browserPkg == null) { 3268 calculateDefaultBrowserLPw(userId); 3269 } 3270 } 3271 3272 private void calculateDefaultBrowserLPw(int userId) { 3273 List<String> allBrowsers = resolveAllBrowserApps(userId); 3274 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3275 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3276 } 3277 3278 private List<String> resolveAllBrowserApps(int userId) { 3279 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3280 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3281 PackageManager.MATCH_ALL, userId); 3282 3283 final int count = list.size(); 3284 List<String> result = new ArrayList<String>(count); 3285 for (int i=0; i<count; i++) { 3286 ResolveInfo info = list.get(i); 3287 if (info.activityInfo == null 3288 || !info.handleAllWebDataURI 3289 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3290 || result.contains(info.activityInfo.packageName)) { 3291 continue; 3292 } 3293 result.add(info.activityInfo.packageName); 3294 } 3295 3296 return result; 3297 } 3298 3299 private boolean packageIsBrowser(String packageName, int userId) { 3300 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3301 PackageManager.MATCH_ALL, userId); 3302 final int N = list.size(); 3303 for (int i = 0; i < N; i++) { 3304 ResolveInfo info = list.get(i); 3305 if (packageName.equals(info.activityInfo.packageName)) { 3306 return true; 3307 } 3308 } 3309 return false; 3310 } 3311 3312 private void checkDefaultBrowser() { 3313 final int myUserId = UserHandle.myUserId(); 3314 final String packageName = getDefaultBrowserPackageName(myUserId); 3315 if (packageName != null) { 3316 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3317 if (info == null) { 3318 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3319 synchronized (mPackages) { 3320 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3321 } 3322 } 3323 } 3324 } 3325 3326 @Override 3327 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3328 throws RemoteException { 3329 try { 3330 return super.onTransact(code, data, reply, flags); 3331 } catch (RuntimeException e) { 3332 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3333 Slog.wtf(TAG, "Package Manager Crash", e); 3334 } 3335 throw e; 3336 } 3337 } 3338 3339 static int[] appendInts(int[] cur, int[] add) { 3340 if (add == null) return cur; 3341 if (cur == null) return add; 3342 final int N = add.length; 3343 for (int i=0; i<N; i++) { 3344 cur = appendInt(cur, add[i]); 3345 } 3346 return cur; 3347 } 3348 3349 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3350 if (!sUserManager.exists(userId)) return null; 3351 if (ps == null) { 3352 return null; 3353 } 3354 final PackageParser.Package p = ps.pkg; 3355 if (p == null) { 3356 return null; 3357 } 3358 // Filter out ephemeral app metadata: 3359 // * The system/shell/root can see metadata for any app 3360 // * An installed app can see metadata for 1) other installed apps 3361 // and 2) ephemeral apps that have explicitly interacted with it 3362 // * Ephemeral apps can only see their own metadata 3363 // * Holding a signature permission allows seeing instant apps 3364 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3365 if (callingAppId != Process.SYSTEM_UID 3366 && callingAppId != Process.SHELL_UID 3367 && callingAppId != Process.ROOT_UID 3368 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3369 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3370 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3371 if (instantAppPackageName != null) { 3372 // ephemeral apps can only get information on themselves 3373 if (!instantAppPackageName.equals(p.packageName)) { 3374 return null; 3375 } 3376 } else { 3377 if (ps.getInstantApp(userId)) { 3378 // only get access to the ephemeral app if we've been granted access 3379 if (!mInstantAppRegistry.isInstantAccessGranted( 3380 userId, callingAppId, ps.appId)) { 3381 return null; 3382 } 3383 } 3384 } 3385 } 3386 3387 final PermissionsState permissionsState = ps.getPermissionsState(); 3388 3389 // Compute GIDs only if requested 3390 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3391 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3392 // Compute granted permissions only if package has requested permissions 3393 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3394 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3395 final PackageUserState state = ps.readUserState(userId); 3396 3397 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3398 && ps.isSystem()) { 3399 flags |= MATCH_ANY_USER; 3400 } 3401 3402 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3403 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3404 3405 if (packageInfo == null) { 3406 return null; 3407 } 3408 3409 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3410 resolveExternalPackageNameLPr(p); 3411 3412 return packageInfo; 3413 } 3414 3415 @Override 3416 public void checkPackageStartable(String packageName, int userId) { 3417 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3418 3419 synchronized (mPackages) { 3420 final PackageSetting ps = mSettings.mPackages.get(packageName); 3421 if (ps == null) { 3422 throw new SecurityException("Package " + packageName + " was not found!"); 3423 } 3424 3425 if (!ps.getInstalled(userId)) { 3426 throw new SecurityException( 3427 "Package " + packageName + " was not installed for user " + userId + "!"); 3428 } 3429 3430 if (mSafeMode && !ps.isSystem()) { 3431 throw new SecurityException("Package " + packageName + " not a system app!"); 3432 } 3433 3434 if (mFrozenPackages.contains(packageName)) { 3435 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3436 } 3437 3438 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3439 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3440 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3441 } 3442 } 3443 } 3444 3445 @Override 3446 public boolean isPackageAvailable(String packageName, int userId) { 3447 if (!sUserManager.exists(userId)) return false; 3448 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3449 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3450 synchronized (mPackages) { 3451 PackageParser.Package p = mPackages.get(packageName); 3452 if (p != null) { 3453 final PackageSetting ps = (PackageSetting) p.mExtras; 3454 if (ps != null) { 3455 final PackageUserState state = ps.readUserState(userId); 3456 if (state != null) { 3457 return PackageParser.isAvailable(state); 3458 } 3459 } 3460 } 3461 } 3462 return false; 3463 } 3464 3465 @Override 3466 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3467 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3468 flags, userId); 3469 } 3470 3471 @Override 3472 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3473 int flags, int userId) { 3474 return getPackageInfoInternal(versionedPackage.getPackageName(), 3475 // TODO: We will change version code to long, so in the new API it is long 3476 (int) versionedPackage.getVersionCode(), flags, userId); 3477 } 3478 3479 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3480 int flags, int userId) { 3481 if (!sUserManager.exists(userId)) return null; 3482 flags = updateFlagsForPackage(flags, userId, packageName); 3483 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3484 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3485 3486 // reader 3487 synchronized (mPackages) { 3488 // Normalize package name to handle renamed packages and static libs 3489 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3490 3491 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3492 if (matchFactoryOnly) { 3493 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3494 if (ps != null) { 3495 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3496 return null; 3497 } 3498 return generatePackageInfo(ps, flags, userId); 3499 } 3500 } 3501 3502 PackageParser.Package p = mPackages.get(packageName); 3503 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3504 return null; 3505 } 3506 if (DEBUG_PACKAGE_INFO) 3507 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3508 if (p != null) { 3509 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3510 Binder.getCallingUid(), userId)) { 3511 return null; 3512 } 3513 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3514 } 3515 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3516 final PackageSetting ps = mSettings.mPackages.get(packageName); 3517 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3518 return null; 3519 } 3520 return generatePackageInfo(ps, flags, userId); 3521 } 3522 } 3523 return null; 3524 } 3525 3526 3527 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3528 // System/shell/root get to see all static libs 3529 final int appId = UserHandle.getAppId(uid); 3530 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3531 || appId == Process.ROOT_UID) { 3532 return false; 3533 } 3534 3535 // No package means no static lib as it is always on internal storage 3536 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3537 return false; 3538 } 3539 3540 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3541 ps.pkg.staticSharedLibVersion); 3542 if (libEntry == null) { 3543 return false; 3544 } 3545 3546 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3547 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3548 if (uidPackageNames == null) { 3549 return true; 3550 } 3551 3552 for (String uidPackageName : uidPackageNames) { 3553 if (ps.name.equals(uidPackageName)) { 3554 return false; 3555 } 3556 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3557 if (uidPs != null) { 3558 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3559 libEntry.info.getName()); 3560 if (index < 0) { 3561 continue; 3562 } 3563 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3564 return false; 3565 } 3566 } 3567 } 3568 return true; 3569 } 3570 3571 @Override 3572 public String[] currentToCanonicalPackageNames(String[] names) { 3573 String[] out = new String[names.length]; 3574 // reader 3575 synchronized (mPackages) { 3576 for (int i=names.length-1; i>=0; i--) { 3577 PackageSetting ps = mSettings.mPackages.get(names[i]); 3578 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3579 } 3580 } 3581 return out; 3582 } 3583 3584 @Override 3585 public String[] canonicalToCurrentPackageNames(String[] names) { 3586 String[] out = new String[names.length]; 3587 // reader 3588 synchronized (mPackages) { 3589 for (int i=names.length-1; i>=0; i--) { 3590 String cur = mSettings.getRenamedPackageLPr(names[i]); 3591 out[i] = cur != null ? cur : names[i]; 3592 } 3593 } 3594 return out; 3595 } 3596 3597 @Override 3598 public int getPackageUid(String packageName, int flags, int userId) { 3599 if (!sUserManager.exists(userId)) return -1; 3600 flags = updateFlagsForPackage(flags, userId, packageName); 3601 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3602 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3603 3604 // reader 3605 synchronized (mPackages) { 3606 final PackageParser.Package p = mPackages.get(packageName); 3607 if (p != null && p.isMatch(flags)) { 3608 return UserHandle.getUid(userId, p.applicationInfo.uid); 3609 } 3610 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3611 final PackageSetting ps = mSettings.mPackages.get(packageName); 3612 if (ps != null && ps.isMatch(flags)) { 3613 return UserHandle.getUid(userId, ps.appId); 3614 } 3615 } 3616 } 3617 3618 return -1; 3619 } 3620 3621 @Override 3622 public int[] getPackageGids(String packageName, int flags, int userId) { 3623 if (!sUserManager.exists(userId)) return null; 3624 flags = updateFlagsForPackage(flags, userId, packageName); 3625 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3626 false /* requireFullPermission */, false /* checkShell */, 3627 "getPackageGids"); 3628 3629 // reader 3630 synchronized (mPackages) { 3631 final PackageParser.Package p = mPackages.get(packageName); 3632 if (p != null && p.isMatch(flags)) { 3633 PackageSetting ps = (PackageSetting) p.mExtras; 3634 // TODO: Shouldn't this be checking for package installed state for userId and 3635 // return null? 3636 return ps.getPermissionsState().computeGids(userId); 3637 } 3638 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3639 final PackageSetting ps = mSettings.mPackages.get(packageName); 3640 if (ps != null && ps.isMatch(flags)) { 3641 return ps.getPermissionsState().computeGids(userId); 3642 } 3643 } 3644 } 3645 3646 return null; 3647 } 3648 3649 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3650 if (bp.perm != null) { 3651 return PackageParser.generatePermissionInfo(bp.perm, flags); 3652 } 3653 PermissionInfo pi = new PermissionInfo(); 3654 pi.name = bp.name; 3655 pi.packageName = bp.sourcePackage; 3656 pi.nonLocalizedLabel = bp.name; 3657 pi.protectionLevel = bp.protectionLevel; 3658 return pi; 3659 } 3660 3661 @Override 3662 public PermissionInfo getPermissionInfo(String name, int flags) { 3663 // reader 3664 synchronized (mPackages) { 3665 final BasePermission p = mSettings.mPermissions.get(name); 3666 if (p != null) { 3667 return generatePermissionInfo(p, flags); 3668 } 3669 return null; 3670 } 3671 } 3672 3673 @Override 3674 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3675 int flags) { 3676 // reader 3677 synchronized (mPackages) { 3678 if (group != null && !mPermissionGroups.containsKey(group)) { 3679 // This is thrown as NameNotFoundException 3680 return null; 3681 } 3682 3683 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3684 for (BasePermission p : mSettings.mPermissions.values()) { 3685 if (group == null) { 3686 if (p.perm == null || p.perm.info.group == null) { 3687 out.add(generatePermissionInfo(p, flags)); 3688 } 3689 } else { 3690 if (p.perm != null && group.equals(p.perm.info.group)) { 3691 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3692 } 3693 } 3694 } 3695 return new ParceledListSlice<>(out); 3696 } 3697 } 3698 3699 @Override 3700 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3701 // reader 3702 synchronized (mPackages) { 3703 return PackageParser.generatePermissionGroupInfo( 3704 mPermissionGroups.get(name), flags); 3705 } 3706 } 3707 3708 @Override 3709 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3710 // reader 3711 synchronized (mPackages) { 3712 final int N = mPermissionGroups.size(); 3713 ArrayList<PermissionGroupInfo> out 3714 = new ArrayList<PermissionGroupInfo>(N); 3715 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3716 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3717 } 3718 return new ParceledListSlice<>(out); 3719 } 3720 } 3721 3722 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3723 int uid, int userId) { 3724 if (!sUserManager.exists(userId)) return null; 3725 PackageSetting ps = mSettings.mPackages.get(packageName); 3726 if (ps != null) { 3727 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3728 return null; 3729 } 3730 if (ps.pkg == null) { 3731 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3732 if (pInfo != null) { 3733 return pInfo.applicationInfo; 3734 } 3735 return null; 3736 } 3737 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3738 ps.readUserState(userId), userId); 3739 if (ai != null) { 3740 rebaseEnabledOverlays(ai, userId); 3741 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3742 } 3743 return ai; 3744 } 3745 return null; 3746 } 3747 3748 @Override 3749 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3750 if (!sUserManager.exists(userId)) return null; 3751 flags = updateFlagsForApplication(flags, userId, packageName); 3752 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3753 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3754 3755 // writer 3756 synchronized (mPackages) { 3757 // Normalize package name to handle renamed packages and static libs 3758 packageName = resolveInternalPackageNameLPr(packageName, 3759 PackageManager.VERSION_CODE_HIGHEST); 3760 3761 PackageParser.Package p = mPackages.get(packageName); 3762 if (DEBUG_PACKAGE_INFO) Log.v( 3763 TAG, "getApplicationInfo " + packageName 3764 + ": " + p); 3765 if (p != null) { 3766 PackageSetting ps = mSettings.mPackages.get(packageName); 3767 if (ps == null) return null; 3768 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3769 return null; 3770 } 3771 // Note: isEnabledLP() does not apply here - always return info 3772 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3773 p, flags, ps.readUserState(userId), userId); 3774 if (ai != null) { 3775 rebaseEnabledOverlays(ai, userId); 3776 ai.packageName = resolveExternalPackageNameLPr(p); 3777 } 3778 return ai; 3779 } 3780 if ("android".equals(packageName)||"system".equals(packageName)) { 3781 return mAndroidApplication; 3782 } 3783 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3784 // Already generates the external package name 3785 return generateApplicationInfoFromSettingsLPw(packageName, 3786 Binder.getCallingUid(), flags, userId); 3787 } 3788 } 3789 return null; 3790 } 3791 3792 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3793 List<String> paths = new ArrayList<>(); 3794 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3795 mEnabledOverlayPaths.get(userId); 3796 if (userSpecificOverlays != null) { 3797 if (!"android".equals(ai.packageName)) { 3798 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3799 if (frameworkOverlays != null) { 3800 paths.addAll(frameworkOverlays); 3801 } 3802 } 3803 3804 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3805 if (appOverlays != null) { 3806 paths.addAll(appOverlays); 3807 } 3808 } 3809 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3810 } 3811 3812 private String normalizePackageNameLPr(String packageName) { 3813 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3814 return normalizedPackageName != null ? normalizedPackageName : packageName; 3815 } 3816 3817 @Override 3818 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3819 final IPackageDataObserver observer) { 3820 mContext.enforceCallingOrSelfPermission( 3821 android.Manifest.permission.CLEAR_APP_CACHE, null); 3822 mHandler.post(() -> { 3823 boolean success = false; 3824 try { 3825 freeStorage(volumeUuid, freeStorageSize, 0); 3826 success = true; 3827 } catch (IOException e) { 3828 Slog.w(TAG, e); 3829 } 3830 if (observer != null) { 3831 try { 3832 observer.onRemoveCompleted(null, success); 3833 } catch (RemoteException e) { 3834 Slog.w(TAG, e); 3835 } 3836 } 3837 }); 3838 } 3839 3840 @Override 3841 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3842 final IntentSender pi) { 3843 mContext.enforceCallingOrSelfPermission( 3844 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3845 mHandler.post(() -> { 3846 boolean success = false; 3847 try { 3848 freeStorage(volumeUuid, freeStorageSize, 0); 3849 success = true; 3850 } catch (IOException e) { 3851 Slog.w(TAG, e); 3852 } 3853 if (pi != null) { 3854 try { 3855 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3856 } catch (SendIntentException e) { 3857 Slog.w(TAG, e); 3858 } 3859 } 3860 }); 3861 } 3862 3863 /** 3864 * Blocking call to clear various types of cached data across the system 3865 * until the requested bytes are available. 3866 */ 3867 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3868 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3869 final File file = storage.findPathForUuid(volumeUuid); 3870 3871 if (ENABLE_FREE_CACHE_V2) { 3872 final boolean aggressive = (storageFlags 3873 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3874 3875 // 1. Pre-flight to determine if we have any chance to succeed 3876 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3877 3878 // 3. Consider parsed APK data (aggressive only) 3879 if (aggressive) { 3880 FileUtils.deleteContents(mCacheDir); 3881 } 3882 if (file.getUsableSpace() >= bytes) return; 3883 3884 // 4. Consider cached app data (above quotas) 3885 try { 3886 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3887 } catch (InstallerException ignored) { 3888 } 3889 if (file.getUsableSpace() >= bytes) return; 3890 3891 // 5. Consider shared libraries with refcount=0 and age>2h 3892 // 6. Consider dexopt output (aggressive only) 3893 // 7. Consider ephemeral apps not used in last week 3894 3895 // 8. Consider cached app data (below quotas) 3896 try { 3897 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3898 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3899 } catch (InstallerException ignored) { 3900 } 3901 if (file.getUsableSpace() >= bytes) return; 3902 3903 // 9. Consider DropBox entries 3904 // 10. Consider ephemeral cookies 3905 3906 } else { 3907 try { 3908 mInstaller.freeCache(volumeUuid, bytes, 0); 3909 } catch (InstallerException ignored) { 3910 } 3911 if (file.getUsableSpace() >= bytes) return; 3912 } 3913 3914 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3915 } 3916 3917 /** 3918 * Update given flags based on encryption status of current user. 3919 */ 3920 private int updateFlags(int flags, int userId) { 3921 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3922 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3923 // Caller expressed an explicit opinion about what encryption 3924 // aware/unaware components they want to see, so fall through and 3925 // give them what they want 3926 } else { 3927 // Caller expressed no opinion, so match based on user state 3928 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3929 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3930 } else { 3931 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3932 } 3933 } 3934 return flags; 3935 } 3936 3937 private UserManagerInternal getUserManagerInternal() { 3938 if (mUserManagerInternal == null) { 3939 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3940 } 3941 return mUserManagerInternal; 3942 } 3943 3944 private DeviceIdleController.LocalService getDeviceIdleController() { 3945 if (mDeviceIdleController == null) { 3946 mDeviceIdleController = 3947 LocalServices.getService(DeviceIdleController.LocalService.class); 3948 } 3949 return mDeviceIdleController; 3950 } 3951 3952 /** 3953 * Update given flags when being used to request {@link PackageInfo}. 3954 */ 3955 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3956 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3957 boolean triaged = true; 3958 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3959 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3960 // Caller is asking for component details, so they'd better be 3961 // asking for specific encryption matching behavior, or be triaged 3962 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3963 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3964 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3965 triaged = false; 3966 } 3967 } 3968 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3969 | PackageManager.MATCH_SYSTEM_ONLY 3970 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3971 triaged = false; 3972 } 3973 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3974 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3975 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3976 + Debug.getCallers(5)); 3977 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3978 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3979 // If the caller wants all packages and has a restricted profile associated with it, 3980 // then match all users. This is to make sure that launchers that need to access work 3981 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3982 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3983 flags |= PackageManager.MATCH_ANY_USER; 3984 } 3985 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3986 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3987 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3988 } 3989 return updateFlags(flags, userId); 3990 } 3991 3992 /** 3993 * Update given flags when being used to request {@link ApplicationInfo}. 3994 */ 3995 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3996 return updateFlagsForPackage(flags, userId, cookie); 3997 } 3998 3999 /** 4000 * Update given flags when being used to request {@link ComponentInfo}. 4001 */ 4002 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4003 if (cookie instanceof Intent) { 4004 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4005 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4006 } 4007 } 4008 4009 boolean triaged = true; 4010 // Caller is asking for component details, so they'd better be 4011 // asking for specific encryption matching behavior, or be triaged 4012 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4013 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4014 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4015 triaged = false; 4016 } 4017 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4018 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4019 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4020 } 4021 4022 return updateFlags(flags, userId); 4023 } 4024 4025 /** 4026 * Update given intent when being used to request {@link ResolveInfo}. 4027 */ 4028 private Intent updateIntentForResolve(Intent intent) { 4029 if (intent.getSelector() != null) { 4030 intent = intent.getSelector(); 4031 } 4032 if (DEBUG_PREFERRED) { 4033 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4034 } 4035 return intent; 4036 } 4037 4038 /** 4039 * Update given flags when being used to request {@link ResolveInfo}. 4040 */ 4041 int updateFlagsForResolve(int flags, int userId, Object cookie) { 4042 // Safe mode means we shouldn't match any third-party components 4043 if (mSafeMode) { 4044 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4045 } 4046 final int callingUid = Binder.getCallingUid(); 4047 if (getInstantAppPackageName(callingUid) != null) { 4048 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4049 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4050 flags |= PackageManager.MATCH_INSTANT; 4051 } else { 4052 // Otherwise, prevent leaking ephemeral components 4053 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4054 if (callingUid != Process.SYSTEM_UID 4055 && callingUid != Process.SHELL_UID 4056 && callingUid != 0) { 4057 // Unless called from the system process 4058 flags &= ~PackageManager.MATCH_INSTANT; 4059 } 4060 } 4061 return updateFlagsForComponent(flags, userId, cookie); 4062 } 4063 4064 @Override 4065 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4066 if (!sUserManager.exists(userId)) return null; 4067 flags = updateFlagsForComponent(flags, userId, component); 4068 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4069 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4070 synchronized (mPackages) { 4071 PackageParser.Activity a = mActivities.mActivities.get(component); 4072 4073 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4074 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4075 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4076 if (ps == null) return null; 4077 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4078 userId); 4079 } 4080 if (mResolveComponentName.equals(component)) { 4081 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4082 new PackageUserState(), userId); 4083 } 4084 } 4085 return null; 4086 } 4087 4088 @Override 4089 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4090 String resolvedType) { 4091 synchronized (mPackages) { 4092 if (component.equals(mResolveComponentName)) { 4093 // The resolver supports EVERYTHING! 4094 return true; 4095 } 4096 PackageParser.Activity a = mActivities.mActivities.get(component); 4097 if (a == null) { 4098 return false; 4099 } 4100 for (int i=0; i<a.intents.size(); i++) { 4101 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4102 intent.getData(), intent.getCategories(), TAG) >= 0) { 4103 return true; 4104 } 4105 } 4106 return false; 4107 } 4108 } 4109 4110 @Override 4111 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4112 if (!sUserManager.exists(userId)) return null; 4113 flags = updateFlagsForComponent(flags, userId, component); 4114 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4115 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4116 synchronized (mPackages) { 4117 PackageParser.Activity a = mReceivers.mActivities.get(component); 4118 if (DEBUG_PACKAGE_INFO) Log.v( 4119 TAG, "getReceiverInfo " + component + ": " + a); 4120 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4121 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4122 if (ps == null) return null; 4123 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4124 userId); 4125 } 4126 } 4127 return null; 4128 } 4129 4130 @Override 4131 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4132 if (!sUserManager.exists(userId)) return null; 4133 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4134 4135 flags = updateFlagsForPackage(flags, userId, null); 4136 4137 final boolean canSeeStaticLibraries = 4138 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4139 == PERMISSION_GRANTED 4140 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4141 == PERMISSION_GRANTED 4142 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4143 == PERMISSION_GRANTED 4144 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4145 == PERMISSION_GRANTED; 4146 4147 synchronized (mPackages) { 4148 List<SharedLibraryInfo> result = null; 4149 4150 final int libCount = mSharedLibraries.size(); 4151 for (int i = 0; i < libCount; i++) { 4152 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4153 if (versionedLib == null) { 4154 continue; 4155 } 4156 4157 final int versionCount = versionedLib.size(); 4158 for (int j = 0; j < versionCount; j++) { 4159 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4160 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4161 break; 4162 } 4163 final long identity = Binder.clearCallingIdentity(); 4164 try { 4165 // TODO: We will change version code to long, so in the new API it is long 4166 PackageInfo packageInfo = getPackageInfoVersioned( 4167 libInfo.getDeclaringPackage(), flags, userId); 4168 if (packageInfo == null) { 4169 continue; 4170 } 4171 } finally { 4172 Binder.restoreCallingIdentity(identity); 4173 } 4174 4175 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4176 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4177 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4178 4179 if (result == null) { 4180 result = new ArrayList<>(); 4181 } 4182 result.add(resLibInfo); 4183 } 4184 } 4185 4186 return result != null ? new ParceledListSlice<>(result) : null; 4187 } 4188 } 4189 4190 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4191 SharedLibraryInfo libInfo, int flags, int userId) { 4192 List<VersionedPackage> versionedPackages = null; 4193 final int packageCount = mSettings.mPackages.size(); 4194 for (int i = 0; i < packageCount; i++) { 4195 PackageSetting ps = mSettings.mPackages.valueAt(i); 4196 4197 if (ps == null) { 4198 continue; 4199 } 4200 4201 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4202 continue; 4203 } 4204 4205 final String libName = libInfo.getName(); 4206 if (libInfo.isStatic()) { 4207 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4208 if (libIdx < 0) { 4209 continue; 4210 } 4211 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4212 continue; 4213 } 4214 if (versionedPackages == null) { 4215 versionedPackages = new ArrayList<>(); 4216 } 4217 // If the dependent is a static shared lib, use the public package name 4218 String dependentPackageName = ps.name; 4219 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4220 dependentPackageName = ps.pkg.manifestPackageName; 4221 } 4222 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4223 } else if (ps.pkg != null) { 4224 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4225 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4226 if (versionedPackages == null) { 4227 versionedPackages = new ArrayList<>(); 4228 } 4229 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4230 } 4231 } 4232 } 4233 4234 return versionedPackages; 4235 } 4236 4237 @Override 4238 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4239 if (!sUserManager.exists(userId)) return null; 4240 flags = updateFlagsForComponent(flags, userId, component); 4241 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4242 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4243 synchronized (mPackages) { 4244 PackageParser.Service s = mServices.mServices.get(component); 4245 if (DEBUG_PACKAGE_INFO) Log.v( 4246 TAG, "getServiceInfo " + component + ": " + s); 4247 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4248 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4249 if (ps == null) return null; 4250 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4251 userId); 4252 } 4253 } 4254 return null; 4255 } 4256 4257 @Override 4258 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4259 if (!sUserManager.exists(userId)) return null; 4260 flags = updateFlagsForComponent(flags, userId, component); 4261 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4262 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4263 synchronized (mPackages) { 4264 PackageParser.Provider p = mProviders.mProviders.get(component); 4265 if (DEBUG_PACKAGE_INFO) Log.v( 4266 TAG, "getProviderInfo " + component + ": " + p); 4267 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4268 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4269 if (ps == null) return null; 4270 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4271 userId); 4272 } 4273 } 4274 return null; 4275 } 4276 4277 @Override 4278 public String[] getSystemSharedLibraryNames() { 4279 synchronized (mPackages) { 4280 Set<String> libs = null; 4281 final int libCount = mSharedLibraries.size(); 4282 for (int i = 0; i < libCount; i++) { 4283 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4284 if (versionedLib == null) { 4285 continue; 4286 } 4287 final int versionCount = versionedLib.size(); 4288 for (int j = 0; j < versionCount; j++) { 4289 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4290 if (!libEntry.info.isStatic()) { 4291 if (libs == null) { 4292 libs = new ArraySet<>(); 4293 } 4294 libs.add(libEntry.info.getName()); 4295 break; 4296 } 4297 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4298 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4299 UserHandle.getUserId(Binder.getCallingUid()))) { 4300 if (libs == null) { 4301 libs = new ArraySet<>(); 4302 } 4303 libs.add(libEntry.info.getName()); 4304 break; 4305 } 4306 } 4307 } 4308 4309 if (libs != null) { 4310 String[] libsArray = new String[libs.size()]; 4311 libs.toArray(libsArray); 4312 return libsArray; 4313 } 4314 4315 return null; 4316 } 4317 } 4318 4319 @Override 4320 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4321 synchronized (mPackages) { 4322 return mServicesSystemSharedLibraryPackageName; 4323 } 4324 } 4325 4326 @Override 4327 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4328 synchronized (mPackages) { 4329 return mSharedSystemSharedLibraryPackageName; 4330 } 4331 } 4332 4333 private void updateSequenceNumberLP(String packageName, int[] userList) { 4334 for (int i = userList.length - 1; i >= 0; --i) { 4335 final int userId = userList[i]; 4336 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4337 if (changedPackages == null) { 4338 changedPackages = new SparseArray<>(); 4339 mChangedPackages.put(userId, changedPackages); 4340 } 4341 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4342 if (sequenceNumbers == null) { 4343 sequenceNumbers = new HashMap<>(); 4344 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4345 } 4346 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4347 if (sequenceNumber != null) { 4348 changedPackages.remove(sequenceNumber); 4349 } 4350 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4351 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4352 } 4353 mChangedPackagesSequenceNumber++; 4354 } 4355 4356 @Override 4357 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4358 synchronized (mPackages) { 4359 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4360 return null; 4361 } 4362 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4363 if (changedPackages == null) { 4364 return null; 4365 } 4366 final List<String> packageNames = 4367 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4368 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4369 final String packageName = changedPackages.get(i); 4370 if (packageName != null) { 4371 packageNames.add(packageName); 4372 } 4373 } 4374 return packageNames.isEmpty() 4375 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4376 } 4377 } 4378 4379 @Override 4380 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4381 ArrayList<FeatureInfo> res; 4382 synchronized (mAvailableFeatures) { 4383 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4384 res.addAll(mAvailableFeatures.values()); 4385 } 4386 final FeatureInfo fi = new FeatureInfo(); 4387 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4388 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4389 res.add(fi); 4390 4391 return new ParceledListSlice<>(res); 4392 } 4393 4394 @Override 4395 public boolean hasSystemFeature(String name, int version) { 4396 synchronized (mAvailableFeatures) { 4397 final FeatureInfo feat = mAvailableFeatures.get(name); 4398 if (feat == null) { 4399 return false; 4400 } else { 4401 return feat.version >= version; 4402 } 4403 } 4404 } 4405 4406 @Override 4407 public int checkPermission(String permName, String pkgName, int userId) { 4408 if (!sUserManager.exists(userId)) { 4409 return PackageManager.PERMISSION_DENIED; 4410 } 4411 4412 synchronized (mPackages) { 4413 final PackageParser.Package p = mPackages.get(pkgName); 4414 if (p != null && p.mExtras != null) { 4415 final PackageSetting ps = (PackageSetting) p.mExtras; 4416 final PermissionsState permissionsState = ps.getPermissionsState(); 4417 if (permissionsState.hasPermission(permName, userId)) { 4418 return PackageManager.PERMISSION_GRANTED; 4419 } 4420 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4421 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4422 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4423 return PackageManager.PERMISSION_GRANTED; 4424 } 4425 } 4426 } 4427 4428 return PackageManager.PERMISSION_DENIED; 4429 } 4430 4431 @Override 4432 public int checkUidPermission(String permName, int uid) { 4433 final int userId = UserHandle.getUserId(uid); 4434 4435 if (!sUserManager.exists(userId)) { 4436 return PackageManager.PERMISSION_DENIED; 4437 } 4438 4439 synchronized (mPackages) { 4440 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4441 if (obj != null) { 4442 final SettingBase ps = (SettingBase) obj; 4443 final PermissionsState permissionsState = ps.getPermissionsState(); 4444 if (permissionsState.hasPermission(permName, userId)) { 4445 return PackageManager.PERMISSION_GRANTED; 4446 } 4447 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4448 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4449 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4450 return PackageManager.PERMISSION_GRANTED; 4451 } 4452 } else { 4453 ArraySet<String> perms = mSystemPermissions.get(uid); 4454 if (perms != null) { 4455 if (perms.contains(permName)) { 4456 return PackageManager.PERMISSION_GRANTED; 4457 } 4458 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4459 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4460 return PackageManager.PERMISSION_GRANTED; 4461 } 4462 } 4463 } 4464 } 4465 4466 return PackageManager.PERMISSION_DENIED; 4467 } 4468 4469 @Override 4470 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4471 if (UserHandle.getCallingUserId() != userId) { 4472 mContext.enforceCallingPermission( 4473 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4474 "isPermissionRevokedByPolicy for user " + userId); 4475 } 4476 4477 if (checkPermission(permission, packageName, userId) 4478 == PackageManager.PERMISSION_GRANTED) { 4479 return false; 4480 } 4481 4482 final long identity = Binder.clearCallingIdentity(); 4483 try { 4484 final int flags = getPermissionFlags(permission, packageName, userId); 4485 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4486 } finally { 4487 Binder.restoreCallingIdentity(identity); 4488 } 4489 } 4490 4491 @Override 4492 public String getPermissionControllerPackageName() { 4493 synchronized (mPackages) { 4494 return mRequiredInstallerPackage; 4495 } 4496 } 4497 4498 /** 4499 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4500 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4501 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4502 * @param message the message to log on security exception 4503 */ 4504 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4505 boolean checkShell, String message) { 4506 if (userId < 0) { 4507 throw new IllegalArgumentException("Invalid userId " + userId); 4508 } 4509 if (checkShell) { 4510 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4511 } 4512 if (userId == UserHandle.getUserId(callingUid)) return; 4513 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4514 if (requireFullPermission) { 4515 mContext.enforceCallingOrSelfPermission( 4516 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4517 } else { 4518 try { 4519 mContext.enforceCallingOrSelfPermission( 4520 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4521 } catch (SecurityException se) { 4522 mContext.enforceCallingOrSelfPermission( 4523 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4524 } 4525 } 4526 } 4527 } 4528 4529 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4530 if (callingUid == Process.SHELL_UID) { 4531 if (userHandle >= 0 4532 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4533 throw new SecurityException("Shell does not have permission to access user " 4534 + userHandle); 4535 } else if (userHandle < 0) { 4536 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4537 + Debug.getCallers(3)); 4538 } 4539 } 4540 } 4541 4542 private BasePermission findPermissionTreeLP(String permName) { 4543 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4544 if (permName.startsWith(bp.name) && 4545 permName.length() > bp.name.length() && 4546 permName.charAt(bp.name.length()) == '.') { 4547 return bp; 4548 } 4549 } 4550 return null; 4551 } 4552 4553 private BasePermission checkPermissionTreeLP(String permName) { 4554 if (permName != null) { 4555 BasePermission bp = findPermissionTreeLP(permName); 4556 if (bp != null) { 4557 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4558 return bp; 4559 } 4560 throw new SecurityException("Calling uid " 4561 + Binder.getCallingUid() 4562 + " is not allowed to add to permission tree " 4563 + bp.name + " owned by uid " + bp.uid); 4564 } 4565 } 4566 throw new SecurityException("No permission tree found for " + permName); 4567 } 4568 4569 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4570 if (s1 == null) { 4571 return s2 == null; 4572 } 4573 if (s2 == null) { 4574 return false; 4575 } 4576 if (s1.getClass() != s2.getClass()) { 4577 return false; 4578 } 4579 return s1.equals(s2); 4580 } 4581 4582 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4583 if (pi1.icon != pi2.icon) return false; 4584 if (pi1.logo != pi2.logo) return false; 4585 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4586 if (!compareStrings(pi1.name, pi2.name)) return false; 4587 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4588 // We'll take care of setting this one. 4589 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4590 // These are not currently stored in settings. 4591 //if (!compareStrings(pi1.group, pi2.group)) return false; 4592 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4593 //if (pi1.labelRes != pi2.labelRes) return false; 4594 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4595 return true; 4596 } 4597 4598 int permissionInfoFootprint(PermissionInfo info) { 4599 int size = info.name.length(); 4600 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4601 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4602 return size; 4603 } 4604 4605 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4606 int size = 0; 4607 for (BasePermission perm : mSettings.mPermissions.values()) { 4608 if (perm.uid == tree.uid) { 4609 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4610 } 4611 } 4612 return size; 4613 } 4614 4615 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4616 // We calculate the max size of permissions defined by this uid and throw 4617 // if that plus the size of 'info' would exceed our stated maximum. 4618 if (tree.uid != Process.SYSTEM_UID) { 4619 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4620 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4621 throw new SecurityException("Permission tree size cap exceeded"); 4622 } 4623 } 4624 } 4625 4626 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4627 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4628 throw new SecurityException("Label must be specified in permission"); 4629 } 4630 BasePermission tree = checkPermissionTreeLP(info.name); 4631 BasePermission bp = mSettings.mPermissions.get(info.name); 4632 boolean added = bp == null; 4633 boolean changed = true; 4634 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4635 if (added) { 4636 enforcePermissionCapLocked(info, tree); 4637 bp = new BasePermission(info.name, tree.sourcePackage, 4638 BasePermission.TYPE_DYNAMIC); 4639 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4640 throw new SecurityException( 4641 "Not allowed to modify non-dynamic permission " 4642 + info.name); 4643 } else { 4644 if (bp.protectionLevel == fixedLevel 4645 && bp.perm.owner.equals(tree.perm.owner) 4646 && bp.uid == tree.uid 4647 && comparePermissionInfos(bp.perm.info, info)) { 4648 changed = false; 4649 } 4650 } 4651 bp.protectionLevel = fixedLevel; 4652 info = new PermissionInfo(info); 4653 info.protectionLevel = fixedLevel; 4654 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4655 bp.perm.info.packageName = tree.perm.info.packageName; 4656 bp.uid = tree.uid; 4657 if (added) { 4658 mSettings.mPermissions.put(info.name, bp); 4659 } 4660 if (changed) { 4661 if (!async) { 4662 mSettings.writeLPr(); 4663 } else { 4664 scheduleWriteSettingsLocked(); 4665 } 4666 } 4667 return added; 4668 } 4669 4670 @Override 4671 public boolean addPermission(PermissionInfo info) { 4672 synchronized (mPackages) { 4673 return addPermissionLocked(info, false); 4674 } 4675 } 4676 4677 @Override 4678 public boolean addPermissionAsync(PermissionInfo info) { 4679 synchronized (mPackages) { 4680 return addPermissionLocked(info, true); 4681 } 4682 } 4683 4684 @Override 4685 public void removePermission(String name) { 4686 synchronized (mPackages) { 4687 checkPermissionTreeLP(name); 4688 BasePermission bp = mSettings.mPermissions.get(name); 4689 if (bp != null) { 4690 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4691 throw new SecurityException( 4692 "Not allowed to modify non-dynamic permission " 4693 + name); 4694 } 4695 mSettings.mPermissions.remove(name); 4696 mSettings.writeLPr(); 4697 } 4698 } 4699 } 4700 4701 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4702 BasePermission bp) { 4703 int index = pkg.requestedPermissions.indexOf(bp.name); 4704 if (index == -1) { 4705 throw new SecurityException("Package " + pkg.packageName 4706 + " has not requested permission " + bp.name); 4707 } 4708 if (!bp.isRuntime() && !bp.isDevelopment()) { 4709 throw new SecurityException("Permission " + bp.name 4710 + " is not a changeable permission type"); 4711 } 4712 } 4713 4714 @Override 4715 public void grantRuntimePermission(String packageName, String name, final int userId) { 4716 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4717 } 4718 4719 private void grantRuntimePermission(String packageName, String name, final int userId, 4720 boolean overridePolicy) { 4721 if (!sUserManager.exists(userId)) { 4722 Log.e(TAG, "No such user:" + userId); 4723 return; 4724 } 4725 4726 mContext.enforceCallingOrSelfPermission( 4727 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4728 "grantRuntimePermission"); 4729 4730 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4731 true /* requireFullPermission */, true /* checkShell */, 4732 "grantRuntimePermission"); 4733 4734 final int uid; 4735 final SettingBase sb; 4736 4737 synchronized (mPackages) { 4738 final PackageParser.Package pkg = mPackages.get(packageName); 4739 if (pkg == null) { 4740 throw new IllegalArgumentException("Unknown package: " + packageName); 4741 } 4742 4743 final BasePermission bp = mSettings.mPermissions.get(name); 4744 if (bp == null) { 4745 throw new IllegalArgumentException("Unknown permission: " + name); 4746 } 4747 4748 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4749 4750 // If a permission review is required for legacy apps we represent 4751 // their permissions as always granted runtime ones since we need 4752 // to keep the review required permission flag per user while an 4753 // install permission's state is shared across all users. 4754 if (mPermissionReviewRequired 4755 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4756 && bp.isRuntime()) { 4757 return; 4758 } 4759 4760 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4761 sb = (SettingBase) pkg.mExtras; 4762 if (sb == null) { 4763 throw new IllegalArgumentException("Unknown package: " + packageName); 4764 } 4765 4766 final PermissionsState permissionsState = sb.getPermissionsState(); 4767 4768 final int flags = permissionsState.getPermissionFlags(name, userId); 4769 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4770 throw new SecurityException("Cannot grant system fixed permission " 4771 + name + " for package " + packageName); 4772 } 4773 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4774 throw new SecurityException("Cannot grant policy fixed permission " 4775 + name + " for package " + packageName); 4776 } 4777 4778 if (bp.isDevelopment()) { 4779 // Development permissions must be handled specially, since they are not 4780 // normal runtime permissions. For now they apply to all users. 4781 if (permissionsState.grantInstallPermission(bp) != 4782 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4783 scheduleWriteSettingsLocked(); 4784 } 4785 return; 4786 } 4787 4788 final PackageSetting ps = mSettings.mPackages.get(packageName); 4789 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4790 throw new SecurityException("Cannot grant non-ephemeral permission" 4791 + name + " for package " + packageName); 4792 } 4793 4794 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4795 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4796 return; 4797 } 4798 4799 final int result = permissionsState.grantRuntimePermission(bp, userId); 4800 switch (result) { 4801 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4802 return; 4803 } 4804 4805 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4806 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4807 mHandler.post(new Runnable() { 4808 @Override 4809 public void run() { 4810 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4811 } 4812 }); 4813 } 4814 break; 4815 } 4816 4817 if (bp.isRuntime()) { 4818 logPermissionGranted(mContext, name, packageName); 4819 } 4820 4821 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4822 4823 // Not critical if that is lost - app has to request again. 4824 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4825 } 4826 4827 // Only need to do this if user is initialized. Otherwise it's a new user 4828 // and there are no processes running as the user yet and there's no need 4829 // to make an expensive call to remount processes for the changed permissions. 4830 if (READ_EXTERNAL_STORAGE.equals(name) 4831 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4832 final long token = Binder.clearCallingIdentity(); 4833 try { 4834 if (sUserManager.isInitialized(userId)) { 4835 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4836 StorageManagerInternal.class); 4837 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4838 } 4839 } finally { 4840 Binder.restoreCallingIdentity(token); 4841 } 4842 } 4843 } 4844 4845 @Override 4846 public void revokeRuntimePermission(String packageName, String name, int userId) { 4847 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4848 } 4849 4850 private void revokeRuntimePermission(String packageName, String name, int userId, 4851 boolean overridePolicy) { 4852 if (!sUserManager.exists(userId)) { 4853 Log.e(TAG, "No such user:" + userId); 4854 return; 4855 } 4856 4857 mContext.enforceCallingOrSelfPermission( 4858 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4859 "revokeRuntimePermission"); 4860 4861 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4862 true /* requireFullPermission */, true /* checkShell */, 4863 "revokeRuntimePermission"); 4864 4865 final int appId; 4866 4867 synchronized (mPackages) { 4868 final PackageParser.Package pkg = mPackages.get(packageName); 4869 if (pkg == null) { 4870 throw new IllegalArgumentException("Unknown package: " + packageName); 4871 } 4872 4873 final BasePermission bp = mSettings.mPermissions.get(name); 4874 if (bp == null) { 4875 throw new IllegalArgumentException("Unknown permission: " + name); 4876 } 4877 4878 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4879 4880 // If a permission review is required for legacy apps we represent 4881 // their permissions as always granted runtime ones since we need 4882 // to keep the review required permission flag per user while an 4883 // install permission's state is shared across all users. 4884 if (mPermissionReviewRequired 4885 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4886 && bp.isRuntime()) { 4887 return; 4888 } 4889 4890 SettingBase sb = (SettingBase) pkg.mExtras; 4891 if (sb == null) { 4892 throw new IllegalArgumentException("Unknown package: " + packageName); 4893 } 4894 4895 final PermissionsState permissionsState = sb.getPermissionsState(); 4896 4897 final int flags = permissionsState.getPermissionFlags(name, userId); 4898 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4899 throw new SecurityException("Cannot revoke system fixed permission " 4900 + name + " for package " + packageName); 4901 } 4902 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4903 throw new SecurityException("Cannot revoke policy fixed permission " 4904 + name + " for package " + packageName); 4905 } 4906 4907 if (bp.isDevelopment()) { 4908 // Development permissions must be handled specially, since they are not 4909 // normal runtime permissions. For now they apply to all users. 4910 if (permissionsState.revokeInstallPermission(bp) != 4911 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4912 scheduleWriteSettingsLocked(); 4913 } 4914 return; 4915 } 4916 4917 if (permissionsState.revokeRuntimePermission(bp, userId) == 4918 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4919 return; 4920 } 4921 4922 if (bp.isRuntime()) { 4923 logPermissionRevoked(mContext, name, packageName); 4924 } 4925 4926 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4927 4928 // Critical, after this call app should never have the permission. 4929 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4930 4931 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4932 } 4933 4934 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4935 } 4936 4937 /** 4938 * Get the first event id for the permission. 4939 * 4940 * <p>There are four events for each permission: <ul> 4941 * <li>Request permission: first id + 0</li> 4942 * <li>Grant permission: first id + 1</li> 4943 * <li>Request for permission denied: first id + 2</li> 4944 * <li>Revoke permission: first id + 3</li> 4945 * </ul></p> 4946 * 4947 * @param name name of the permission 4948 * 4949 * @return The first event id for the permission 4950 */ 4951 private static int getBaseEventId(@NonNull String name) { 4952 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4953 4954 if (eventIdIndex == -1) { 4955 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4956 || "user".equals(Build.TYPE)) { 4957 Log.i(TAG, "Unknown permission " + name); 4958 4959 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4960 } else { 4961 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4962 // 4963 // Also update 4964 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4965 // - metrics_constants.proto 4966 throw new IllegalStateException("Unknown permission " + name); 4967 } 4968 } 4969 4970 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4971 } 4972 4973 /** 4974 * Log that a permission was revoked. 4975 * 4976 * @param context Context of the caller 4977 * @param name name of the permission 4978 * @param packageName package permission if for 4979 */ 4980 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4981 @NonNull String packageName) { 4982 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4983 } 4984 4985 /** 4986 * Log that a permission request was granted. 4987 * 4988 * @param context Context of the caller 4989 * @param name name of the permission 4990 * @param packageName package permission if for 4991 */ 4992 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4993 @NonNull String packageName) { 4994 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4995 } 4996 4997 @Override 4998 public void resetRuntimePermissions() { 4999 mContext.enforceCallingOrSelfPermission( 5000 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5001 "revokeRuntimePermission"); 5002 5003 int callingUid = Binder.getCallingUid(); 5004 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5005 mContext.enforceCallingOrSelfPermission( 5006 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5007 "resetRuntimePermissions"); 5008 } 5009 5010 synchronized (mPackages) { 5011 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5012 for (int userId : UserManagerService.getInstance().getUserIds()) { 5013 final int packageCount = mPackages.size(); 5014 for (int i = 0; i < packageCount; i++) { 5015 PackageParser.Package pkg = mPackages.valueAt(i); 5016 if (!(pkg.mExtras instanceof PackageSetting)) { 5017 continue; 5018 } 5019 PackageSetting ps = (PackageSetting) pkg.mExtras; 5020 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5021 } 5022 } 5023 } 5024 } 5025 5026 @Override 5027 public int getPermissionFlags(String name, String packageName, int userId) { 5028 if (!sUserManager.exists(userId)) { 5029 return 0; 5030 } 5031 5032 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5033 5034 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5035 true /* requireFullPermission */, false /* checkShell */, 5036 "getPermissionFlags"); 5037 5038 synchronized (mPackages) { 5039 final PackageParser.Package pkg = mPackages.get(packageName); 5040 if (pkg == null) { 5041 return 0; 5042 } 5043 5044 final BasePermission bp = mSettings.mPermissions.get(name); 5045 if (bp == null) { 5046 return 0; 5047 } 5048 5049 SettingBase sb = (SettingBase) pkg.mExtras; 5050 if (sb == null) { 5051 return 0; 5052 } 5053 5054 PermissionsState permissionsState = sb.getPermissionsState(); 5055 return permissionsState.getPermissionFlags(name, userId); 5056 } 5057 } 5058 5059 @Override 5060 public void updatePermissionFlags(String name, String packageName, int flagMask, 5061 int flagValues, int userId) { 5062 if (!sUserManager.exists(userId)) { 5063 return; 5064 } 5065 5066 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5067 5068 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5069 true /* requireFullPermission */, true /* checkShell */, 5070 "updatePermissionFlags"); 5071 5072 // Only the system can change these flags and nothing else. 5073 if (getCallingUid() != Process.SYSTEM_UID) { 5074 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5075 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5076 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5077 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5078 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5079 } 5080 5081 synchronized (mPackages) { 5082 final PackageParser.Package pkg = mPackages.get(packageName); 5083 if (pkg == null) { 5084 throw new IllegalArgumentException("Unknown package: " + packageName); 5085 } 5086 5087 final BasePermission bp = mSettings.mPermissions.get(name); 5088 if (bp == null) { 5089 throw new IllegalArgumentException("Unknown permission: " + name); 5090 } 5091 5092 SettingBase sb = (SettingBase) pkg.mExtras; 5093 if (sb == null) { 5094 throw new IllegalArgumentException("Unknown package: " + packageName); 5095 } 5096 5097 PermissionsState permissionsState = sb.getPermissionsState(); 5098 5099 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5100 5101 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5102 // Install and runtime permissions are stored in different places, 5103 // so figure out what permission changed and persist the change. 5104 if (permissionsState.getInstallPermissionState(name) != null) { 5105 scheduleWriteSettingsLocked(); 5106 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5107 || hadState) { 5108 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5109 } 5110 } 5111 } 5112 } 5113 5114 /** 5115 * Update the permission flags for all packages and runtime permissions of a user in order 5116 * to allow device or profile owner to remove POLICY_FIXED. 5117 */ 5118 @Override 5119 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5120 if (!sUserManager.exists(userId)) { 5121 return; 5122 } 5123 5124 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5125 5126 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5127 true /* requireFullPermission */, true /* checkShell */, 5128 "updatePermissionFlagsForAllApps"); 5129 5130 // Only the system can change system fixed flags. 5131 if (getCallingUid() != Process.SYSTEM_UID) { 5132 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5133 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5134 } 5135 5136 synchronized (mPackages) { 5137 boolean changed = false; 5138 final int packageCount = mPackages.size(); 5139 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5140 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5141 SettingBase sb = (SettingBase) pkg.mExtras; 5142 if (sb == null) { 5143 continue; 5144 } 5145 PermissionsState permissionsState = sb.getPermissionsState(); 5146 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5147 userId, flagMask, flagValues); 5148 } 5149 if (changed) { 5150 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5151 } 5152 } 5153 } 5154 5155 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5156 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5157 != PackageManager.PERMISSION_GRANTED 5158 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5159 != PackageManager.PERMISSION_GRANTED) { 5160 throw new SecurityException(message + " requires " 5161 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5162 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5163 } 5164 } 5165 5166 @Override 5167 public boolean shouldShowRequestPermissionRationale(String permissionName, 5168 String packageName, int userId) { 5169 if (UserHandle.getCallingUserId() != userId) { 5170 mContext.enforceCallingPermission( 5171 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5172 "canShowRequestPermissionRationale for user " + userId); 5173 } 5174 5175 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5176 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5177 return false; 5178 } 5179 5180 if (checkPermission(permissionName, packageName, userId) 5181 == PackageManager.PERMISSION_GRANTED) { 5182 return false; 5183 } 5184 5185 final int flags; 5186 5187 final long identity = Binder.clearCallingIdentity(); 5188 try { 5189 flags = getPermissionFlags(permissionName, 5190 packageName, userId); 5191 } finally { 5192 Binder.restoreCallingIdentity(identity); 5193 } 5194 5195 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5196 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5197 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5198 5199 if ((flags & fixedFlags) != 0) { 5200 return false; 5201 } 5202 5203 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5204 } 5205 5206 @Override 5207 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5208 mContext.enforceCallingOrSelfPermission( 5209 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5210 "addOnPermissionsChangeListener"); 5211 5212 synchronized (mPackages) { 5213 mOnPermissionChangeListeners.addListenerLocked(listener); 5214 } 5215 } 5216 5217 @Override 5218 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5219 synchronized (mPackages) { 5220 mOnPermissionChangeListeners.removeListenerLocked(listener); 5221 } 5222 } 5223 5224 @Override 5225 public boolean isProtectedBroadcast(String actionName) { 5226 synchronized (mPackages) { 5227 if (mProtectedBroadcasts.contains(actionName)) { 5228 return true; 5229 } else if (actionName != null) { 5230 // TODO: remove these terrible hacks 5231 if (actionName.startsWith("android.net.netmon.lingerExpired") 5232 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5233 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5234 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5235 return true; 5236 } 5237 } 5238 } 5239 return false; 5240 } 5241 5242 @Override 5243 public int checkSignatures(String pkg1, String pkg2) { 5244 synchronized (mPackages) { 5245 final PackageParser.Package p1 = mPackages.get(pkg1); 5246 final PackageParser.Package p2 = mPackages.get(pkg2); 5247 if (p1 == null || p1.mExtras == null 5248 || p2 == null || p2.mExtras == null) { 5249 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5250 } 5251 return compareSignatures(p1.mSignatures, p2.mSignatures); 5252 } 5253 } 5254 5255 @Override 5256 public int checkUidSignatures(int uid1, int uid2) { 5257 // Map to base uids. 5258 uid1 = UserHandle.getAppId(uid1); 5259 uid2 = UserHandle.getAppId(uid2); 5260 // reader 5261 synchronized (mPackages) { 5262 Signature[] s1; 5263 Signature[] s2; 5264 Object obj = mSettings.getUserIdLPr(uid1); 5265 if (obj != null) { 5266 if (obj instanceof SharedUserSetting) { 5267 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5268 } else if (obj instanceof PackageSetting) { 5269 s1 = ((PackageSetting)obj).signatures.mSignatures; 5270 } else { 5271 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5272 } 5273 } else { 5274 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5275 } 5276 obj = mSettings.getUserIdLPr(uid2); 5277 if (obj != null) { 5278 if (obj instanceof SharedUserSetting) { 5279 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5280 } else if (obj instanceof PackageSetting) { 5281 s2 = ((PackageSetting)obj).signatures.mSignatures; 5282 } else { 5283 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5284 } 5285 } else { 5286 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5287 } 5288 return compareSignatures(s1, s2); 5289 } 5290 } 5291 5292 /** 5293 * This method should typically only be used when granting or revoking 5294 * permissions, since the app may immediately restart after this call. 5295 * <p> 5296 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5297 * guard your work against the app being relaunched. 5298 */ 5299 private void killUid(int appId, int userId, String reason) { 5300 final long identity = Binder.clearCallingIdentity(); 5301 try { 5302 IActivityManager am = ActivityManager.getService(); 5303 if (am != null) { 5304 try { 5305 am.killUid(appId, userId, reason); 5306 } catch (RemoteException e) { 5307 /* ignore - same process */ 5308 } 5309 } 5310 } finally { 5311 Binder.restoreCallingIdentity(identity); 5312 } 5313 } 5314 5315 /** 5316 * Compares two sets of signatures. Returns: 5317 * <br /> 5318 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5319 * <br /> 5320 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5321 * <br /> 5322 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5323 * <br /> 5324 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5325 * <br /> 5326 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5327 */ 5328 static int compareSignatures(Signature[] s1, Signature[] s2) { 5329 if (s1 == null) { 5330 return s2 == null 5331 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5332 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5333 } 5334 5335 if (s2 == null) { 5336 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5337 } 5338 5339 if (s1.length != s2.length) { 5340 return PackageManager.SIGNATURE_NO_MATCH; 5341 } 5342 5343 // Since both signature sets are of size 1, we can compare without HashSets. 5344 if (s1.length == 1) { 5345 return s1[0].equals(s2[0]) ? 5346 PackageManager.SIGNATURE_MATCH : 5347 PackageManager.SIGNATURE_NO_MATCH; 5348 } 5349 5350 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5351 for (Signature sig : s1) { 5352 set1.add(sig); 5353 } 5354 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5355 for (Signature sig : s2) { 5356 set2.add(sig); 5357 } 5358 // Make sure s2 contains all signatures in s1. 5359 if (set1.equals(set2)) { 5360 return PackageManager.SIGNATURE_MATCH; 5361 } 5362 return PackageManager.SIGNATURE_NO_MATCH; 5363 } 5364 5365 /** 5366 * If the database version for this type of package (internal storage or 5367 * external storage) is less than the version where package signatures 5368 * were updated, return true. 5369 */ 5370 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5371 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5372 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5373 } 5374 5375 /** 5376 * Used for backward compatibility to make sure any packages with 5377 * certificate chains get upgraded to the new style. {@code existingSigs} 5378 * will be in the old format (since they were stored on disk from before the 5379 * system upgrade) and {@code scannedSigs} will be in the newer format. 5380 */ 5381 private int compareSignaturesCompat(PackageSignatures existingSigs, 5382 PackageParser.Package scannedPkg) { 5383 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5384 return PackageManager.SIGNATURE_NO_MATCH; 5385 } 5386 5387 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5388 for (Signature sig : existingSigs.mSignatures) { 5389 existingSet.add(sig); 5390 } 5391 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5392 for (Signature sig : scannedPkg.mSignatures) { 5393 try { 5394 Signature[] chainSignatures = sig.getChainSignatures(); 5395 for (Signature chainSig : chainSignatures) { 5396 scannedCompatSet.add(chainSig); 5397 } 5398 } catch (CertificateEncodingException e) { 5399 scannedCompatSet.add(sig); 5400 } 5401 } 5402 /* 5403 * Make sure the expanded scanned set contains all signatures in the 5404 * existing one. 5405 */ 5406 if (scannedCompatSet.equals(existingSet)) { 5407 // Migrate the old signatures to the new scheme. 5408 existingSigs.assignSignatures(scannedPkg.mSignatures); 5409 // The new KeySets will be re-added later in the scanning process. 5410 synchronized (mPackages) { 5411 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5412 } 5413 return PackageManager.SIGNATURE_MATCH; 5414 } 5415 return PackageManager.SIGNATURE_NO_MATCH; 5416 } 5417 5418 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5419 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5420 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5421 } 5422 5423 private int compareSignaturesRecover(PackageSignatures existingSigs, 5424 PackageParser.Package scannedPkg) { 5425 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5426 return PackageManager.SIGNATURE_NO_MATCH; 5427 } 5428 5429 String msg = null; 5430 try { 5431 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5432 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5433 + scannedPkg.packageName); 5434 return PackageManager.SIGNATURE_MATCH; 5435 } 5436 } catch (CertificateException e) { 5437 msg = e.getMessage(); 5438 } 5439 5440 logCriticalInfo(Log.INFO, 5441 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5442 return PackageManager.SIGNATURE_NO_MATCH; 5443 } 5444 5445 @Override 5446 public List<String> getAllPackages() { 5447 synchronized (mPackages) { 5448 return new ArrayList<String>(mPackages.keySet()); 5449 } 5450 } 5451 5452 @Override 5453 public String[] getPackagesForUid(int uid) { 5454 final int userId = UserHandle.getUserId(uid); 5455 uid = UserHandle.getAppId(uid); 5456 // reader 5457 synchronized (mPackages) { 5458 Object obj = mSettings.getUserIdLPr(uid); 5459 if (obj instanceof SharedUserSetting) { 5460 final SharedUserSetting sus = (SharedUserSetting) obj; 5461 final int N = sus.packages.size(); 5462 String[] res = new String[N]; 5463 final Iterator<PackageSetting> it = sus.packages.iterator(); 5464 int i = 0; 5465 while (it.hasNext()) { 5466 PackageSetting ps = it.next(); 5467 if (ps.getInstalled(userId)) { 5468 res[i++] = ps.name; 5469 } else { 5470 res = ArrayUtils.removeElement(String.class, res, res[i]); 5471 } 5472 } 5473 return res; 5474 } else if (obj instanceof PackageSetting) { 5475 final PackageSetting ps = (PackageSetting) obj; 5476 if (ps.getInstalled(userId)) { 5477 return new String[]{ps.name}; 5478 } 5479 } 5480 } 5481 return null; 5482 } 5483 5484 @Override 5485 public String getNameForUid(int uid) { 5486 // reader 5487 synchronized (mPackages) { 5488 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5489 if (obj instanceof SharedUserSetting) { 5490 final SharedUserSetting sus = (SharedUserSetting) obj; 5491 return sus.name + ":" + sus.userId; 5492 } else if (obj instanceof PackageSetting) { 5493 final PackageSetting ps = (PackageSetting) obj; 5494 return ps.name; 5495 } 5496 } 5497 return null; 5498 } 5499 5500 @Override 5501 public int getUidForSharedUser(String sharedUserName) { 5502 if(sharedUserName == null) { 5503 return -1; 5504 } 5505 // reader 5506 synchronized (mPackages) { 5507 SharedUserSetting suid; 5508 try { 5509 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5510 if (suid != null) { 5511 return suid.userId; 5512 } 5513 } catch (PackageManagerException ignore) { 5514 // can't happen, but, still need to catch it 5515 } 5516 return -1; 5517 } 5518 } 5519 5520 @Override 5521 public int getFlagsForUid(int uid) { 5522 synchronized (mPackages) { 5523 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5524 if (obj instanceof SharedUserSetting) { 5525 final SharedUserSetting sus = (SharedUserSetting) obj; 5526 return sus.pkgFlags; 5527 } else if (obj instanceof PackageSetting) { 5528 final PackageSetting ps = (PackageSetting) obj; 5529 return ps.pkgFlags; 5530 } 5531 } 5532 return 0; 5533 } 5534 5535 @Override 5536 public int getPrivateFlagsForUid(int uid) { 5537 synchronized (mPackages) { 5538 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5539 if (obj instanceof SharedUserSetting) { 5540 final SharedUserSetting sus = (SharedUserSetting) obj; 5541 return sus.pkgPrivateFlags; 5542 } else if (obj instanceof PackageSetting) { 5543 final PackageSetting ps = (PackageSetting) obj; 5544 return ps.pkgPrivateFlags; 5545 } 5546 } 5547 return 0; 5548 } 5549 5550 @Override 5551 public boolean isUidPrivileged(int uid) { 5552 uid = UserHandle.getAppId(uid); 5553 // reader 5554 synchronized (mPackages) { 5555 Object obj = mSettings.getUserIdLPr(uid); 5556 if (obj instanceof SharedUserSetting) { 5557 final SharedUserSetting sus = (SharedUserSetting) obj; 5558 final Iterator<PackageSetting> it = sus.packages.iterator(); 5559 while (it.hasNext()) { 5560 if (it.next().isPrivileged()) { 5561 return true; 5562 } 5563 } 5564 } else if (obj instanceof PackageSetting) { 5565 final PackageSetting ps = (PackageSetting) obj; 5566 return ps.isPrivileged(); 5567 } 5568 } 5569 return false; 5570 } 5571 5572 @Override 5573 public String[] getAppOpPermissionPackages(String permissionName) { 5574 synchronized (mPackages) { 5575 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5576 if (pkgs == null) { 5577 return null; 5578 } 5579 return pkgs.toArray(new String[pkgs.size()]); 5580 } 5581 } 5582 5583 @Override 5584 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5585 int flags, int userId) { 5586 try { 5587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5588 5589 if (!sUserManager.exists(userId)) return null; 5590 flags = updateFlagsForResolve(flags, userId, intent); 5591 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5592 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5593 5594 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5595 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5596 flags, userId); 5597 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5598 5599 final ResolveInfo bestChoice = 5600 chooseBestActivity(intent, resolvedType, flags, query, userId); 5601 return bestChoice; 5602 } finally { 5603 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5604 } 5605 } 5606 5607 @Override 5608 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5609 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5610 throw new SecurityException( 5611 "findPersistentPreferredActivity can only be run by the system"); 5612 } 5613 if (!sUserManager.exists(userId)) { 5614 return null; 5615 } 5616 intent = updateIntentForResolve(intent); 5617 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5618 final int flags = updateFlagsForResolve(0, userId, intent); 5619 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5620 userId); 5621 synchronized (mPackages) { 5622 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5623 userId); 5624 } 5625 } 5626 5627 @Override 5628 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5629 IntentFilter filter, int match, ComponentName activity) { 5630 final int userId = UserHandle.getCallingUserId(); 5631 if (DEBUG_PREFERRED) { 5632 Log.v(TAG, "setLastChosenActivity intent=" + intent 5633 + " resolvedType=" + resolvedType 5634 + " flags=" + flags 5635 + " filter=" + filter 5636 + " match=" + match 5637 + " activity=" + activity); 5638 filter.dump(new PrintStreamPrinter(System.out), " "); 5639 } 5640 intent.setComponent(null); 5641 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5642 userId); 5643 // Find any earlier preferred or last chosen entries and nuke them 5644 findPreferredActivity(intent, resolvedType, 5645 flags, query, 0, false, true, false, userId); 5646 // Add the new activity as the last chosen for this filter 5647 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5648 "Setting last chosen"); 5649 } 5650 5651 @Override 5652 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5653 final int userId = UserHandle.getCallingUserId(); 5654 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5655 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5656 userId); 5657 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5658 false, false, false, userId); 5659 } 5660 5661 private boolean isEphemeralDisabled() { 5662 // ephemeral apps have been disabled across the board 5663 if (DISABLE_EPHEMERAL_APPS) { 5664 return true; 5665 } 5666 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5667 if (!mSystemReady) { 5668 return true; 5669 } 5670 // we can't get a content resolver until the system is ready; these checks must happen last 5671 final ContentResolver resolver = mContext.getContentResolver(); 5672 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5673 return true; 5674 } 5675 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5676 } 5677 5678 private boolean isEphemeralAllowed( 5679 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5680 boolean skipPackageCheck) { 5681 // Short circuit and return early if possible. 5682 if (isEphemeralDisabled()) { 5683 return false; 5684 } 5685 final int callingUser = UserHandle.getCallingUserId(); 5686 if (callingUser != UserHandle.USER_SYSTEM) { 5687 return false; 5688 } 5689 if (mInstantAppResolverConnection == null) { 5690 return false; 5691 } 5692 if (mInstantAppInstallerComponent == null) { 5693 return false; 5694 } 5695 if (intent.getComponent() != null) { 5696 return false; 5697 } 5698 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5699 return false; 5700 } 5701 if (!skipPackageCheck && intent.getPackage() != null) { 5702 return false; 5703 } 5704 final boolean isWebUri = hasWebURI(intent); 5705 if (!isWebUri || intent.getData().getHost() == null) { 5706 return false; 5707 } 5708 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5709 // Or if there's already an ephemeral app installed that handles the action 5710 synchronized (mPackages) { 5711 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5712 for (int n = 0; n < count; n++) { 5713 ResolveInfo info = resolvedActivities.get(n); 5714 String packageName = info.activityInfo.packageName; 5715 PackageSetting ps = mSettings.mPackages.get(packageName); 5716 if (ps != null) { 5717 // Try to get the status from User settings first 5718 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5719 int status = (int) (packedStatus >> 32); 5720 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5721 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5722 if (DEBUG_EPHEMERAL) { 5723 Slog.v(TAG, "DENY ephemeral apps;" 5724 + " pkg: " + packageName + ", status: " + status); 5725 } 5726 return false; 5727 } 5728 if (ps.getInstantApp(userId)) { 5729 return false; 5730 } 5731 } 5732 } 5733 } 5734 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5735 return true; 5736 } 5737 5738 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5739 Intent origIntent, String resolvedType, String callingPackage, 5740 int userId) { 5741 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5742 new EphemeralRequest(responseObj, origIntent, resolvedType, 5743 callingPackage, userId)); 5744 mHandler.sendMessage(msg); 5745 } 5746 5747 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5748 int flags, List<ResolveInfo> query, int userId) { 5749 if (query != null) { 5750 final int N = query.size(); 5751 if (N == 1) { 5752 return query.get(0); 5753 } else if (N > 1) { 5754 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5755 // If there is more than one activity with the same priority, 5756 // then let the user decide between them. 5757 ResolveInfo r0 = query.get(0); 5758 ResolveInfo r1 = query.get(1); 5759 if (DEBUG_INTENT_MATCHING || debug) { 5760 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5761 + r1.activityInfo.name + "=" + r1.priority); 5762 } 5763 // If the first activity has a higher priority, or a different 5764 // default, then it is always desirable to pick it. 5765 if (r0.priority != r1.priority 5766 || r0.preferredOrder != r1.preferredOrder 5767 || r0.isDefault != r1.isDefault) { 5768 return query.get(0); 5769 } 5770 // If we have saved a preference for a preferred activity for 5771 // this Intent, use that. 5772 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5773 flags, query, r0.priority, true, false, debug, userId); 5774 if (ri != null) { 5775 return ri; 5776 } 5777 ri = new ResolveInfo(mResolveInfo); 5778 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5779 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5780 // If all of the options come from the same package, show the application's 5781 // label and icon instead of the generic resolver's. 5782 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5783 // and then throw away the ResolveInfo itself, meaning that the caller loses 5784 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5785 // a fallback for this case; we only set the target package's resources on 5786 // the ResolveInfo, not the ActivityInfo. 5787 final String intentPackage = intent.getPackage(); 5788 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5789 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5790 ri.resolvePackageName = intentPackage; 5791 if (userNeedsBadging(userId)) { 5792 ri.noResourceId = true; 5793 } else { 5794 ri.icon = appi.icon; 5795 } 5796 ri.iconResourceId = appi.icon; 5797 ri.labelRes = appi.labelRes; 5798 } 5799 ri.activityInfo.applicationInfo = new ApplicationInfo( 5800 ri.activityInfo.applicationInfo); 5801 if (userId != 0) { 5802 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5803 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5804 } 5805 // Make sure that the resolver is displayable in car mode 5806 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5807 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5808 return ri; 5809 } 5810 } 5811 return null; 5812 } 5813 5814 /** 5815 * Return true if the given list is not empty and all of its contents have 5816 * an activityInfo with the given package name. 5817 */ 5818 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5819 if (ArrayUtils.isEmpty(list)) { 5820 return false; 5821 } 5822 for (int i = 0, N = list.size(); i < N; i++) { 5823 final ResolveInfo ri = list.get(i); 5824 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5825 if (ai == null || !packageName.equals(ai.packageName)) { 5826 return false; 5827 } 5828 } 5829 return true; 5830 } 5831 5832 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5833 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5834 final int N = query.size(); 5835 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5836 .get(userId); 5837 // Get the list of persistent preferred activities that handle the intent 5838 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5839 List<PersistentPreferredActivity> pprefs = ppir != null 5840 ? ppir.queryIntent(intent, resolvedType, 5841 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5842 userId) 5843 : null; 5844 if (pprefs != null && pprefs.size() > 0) { 5845 final int M = pprefs.size(); 5846 for (int i=0; i<M; i++) { 5847 final PersistentPreferredActivity ppa = pprefs.get(i); 5848 if (DEBUG_PREFERRED || debug) { 5849 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5850 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5851 + "\n component=" + ppa.mComponent); 5852 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5853 } 5854 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5855 flags | MATCH_DISABLED_COMPONENTS, userId); 5856 if (DEBUG_PREFERRED || debug) { 5857 Slog.v(TAG, "Found persistent preferred activity:"); 5858 if (ai != null) { 5859 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5860 } else { 5861 Slog.v(TAG, " null"); 5862 } 5863 } 5864 if (ai == null) { 5865 // This previously registered persistent preferred activity 5866 // component is no longer known. Ignore it and do NOT remove it. 5867 continue; 5868 } 5869 for (int j=0; j<N; j++) { 5870 final ResolveInfo ri = query.get(j); 5871 if (!ri.activityInfo.applicationInfo.packageName 5872 .equals(ai.applicationInfo.packageName)) { 5873 continue; 5874 } 5875 if (!ri.activityInfo.name.equals(ai.name)) { 5876 continue; 5877 } 5878 // Found a persistent preference that can handle the intent. 5879 if (DEBUG_PREFERRED || debug) { 5880 Slog.v(TAG, "Returning persistent preferred activity: " + 5881 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5882 } 5883 return ri; 5884 } 5885 } 5886 } 5887 return null; 5888 } 5889 5890 // TODO: handle preferred activities missing while user has amnesia 5891 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5892 List<ResolveInfo> query, int priority, boolean always, 5893 boolean removeMatches, boolean debug, int userId) { 5894 if (!sUserManager.exists(userId)) return null; 5895 flags = updateFlagsForResolve(flags, userId, intent); 5896 intent = updateIntentForResolve(intent); 5897 // writer 5898 synchronized (mPackages) { 5899 // Try to find a matching persistent preferred activity. 5900 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5901 debug, userId); 5902 5903 // If a persistent preferred activity matched, use it. 5904 if (pri != null) { 5905 return pri; 5906 } 5907 5908 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5909 // Get the list of preferred activities that handle the intent 5910 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5911 List<PreferredActivity> prefs = pir != null 5912 ? pir.queryIntent(intent, resolvedType, 5913 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5914 userId) 5915 : null; 5916 if (prefs != null && prefs.size() > 0) { 5917 boolean changed = false; 5918 try { 5919 // First figure out how good the original match set is. 5920 // We will only allow preferred activities that came 5921 // from the same match quality. 5922 int match = 0; 5923 5924 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5925 5926 final int N = query.size(); 5927 for (int j=0; j<N; j++) { 5928 final ResolveInfo ri = query.get(j); 5929 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5930 + ": 0x" + Integer.toHexString(match)); 5931 if (ri.match > match) { 5932 match = ri.match; 5933 } 5934 } 5935 5936 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5937 + Integer.toHexString(match)); 5938 5939 match &= IntentFilter.MATCH_CATEGORY_MASK; 5940 final int M = prefs.size(); 5941 for (int i=0; i<M; i++) { 5942 final PreferredActivity pa = prefs.get(i); 5943 if (DEBUG_PREFERRED || debug) { 5944 Slog.v(TAG, "Checking PreferredActivity ds=" 5945 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5946 + "\n component=" + pa.mPref.mComponent); 5947 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5948 } 5949 if (pa.mPref.mMatch != match) { 5950 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5951 + Integer.toHexString(pa.mPref.mMatch)); 5952 continue; 5953 } 5954 // If it's not an "always" type preferred activity and that's what we're 5955 // looking for, skip it. 5956 if (always && !pa.mPref.mAlways) { 5957 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5958 continue; 5959 } 5960 final ActivityInfo ai = getActivityInfo( 5961 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5962 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5963 userId); 5964 if (DEBUG_PREFERRED || debug) { 5965 Slog.v(TAG, "Found preferred activity:"); 5966 if (ai != null) { 5967 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5968 } else { 5969 Slog.v(TAG, " null"); 5970 } 5971 } 5972 if (ai == null) { 5973 // This previously registered preferred activity 5974 // component is no longer known. Most likely an update 5975 // to the app was installed and in the new version this 5976 // component no longer exists. Clean it up by removing 5977 // it from the preferred activities list, and skip it. 5978 Slog.w(TAG, "Removing dangling preferred activity: " 5979 + pa.mPref.mComponent); 5980 pir.removeFilter(pa); 5981 changed = true; 5982 continue; 5983 } 5984 for (int j=0; j<N; j++) { 5985 final ResolveInfo ri = query.get(j); 5986 if (!ri.activityInfo.applicationInfo.packageName 5987 .equals(ai.applicationInfo.packageName)) { 5988 continue; 5989 } 5990 if (!ri.activityInfo.name.equals(ai.name)) { 5991 continue; 5992 } 5993 5994 if (removeMatches) { 5995 pir.removeFilter(pa); 5996 changed = true; 5997 if (DEBUG_PREFERRED) { 5998 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5999 } 6000 break; 6001 } 6002 6003 // Okay we found a previously set preferred or last chosen app. 6004 // If the result set is different from when this 6005 // was created, we need to clear it and re-ask the 6006 // user their preference, if we're looking for an "always" type entry. 6007 if (always && !pa.mPref.sameSet(query)) { 6008 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6009 + intent + " type " + resolvedType); 6010 if (DEBUG_PREFERRED) { 6011 Slog.v(TAG, "Removing preferred activity since set changed " 6012 + pa.mPref.mComponent); 6013 } 6014 pir.removeFilter(pa); 6015 // Re-add the filter as a "last chosen" entry (!always) 6016 PreferredActivity lastChosen = new PreferredActivity( 6017 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6018 pir.addFilter(lastChosen); 6019 changed = true; 6020 return null; 6021 } 6022 6023 // Yay! Either the set matched or we're looking for the last chosen 6024 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6025 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6026 return ri; 6027 } 6028 } 6029 } finally { 6030 if (changed) { 6031 if (DEBUG_PREFERRED) { 6032 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6033 } 6034 scheduleWritePackageRestrictionsLocked(userId); 6035 } 6036 } 6037 } 6038 } 6039 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6040 return null; 6041 } 6042 6043 /* 6044 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6045 */ 6046 @Override 6047 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6048 int targetUserId) { 6049 mContext.enforceCallingOrSelfPermission( 6050 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6051 List<CrossProfileIntentFilter> matches = 6052 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6053 if (matches != null) { 6054 int size = matches.size(); 6055 for (int i = 0; i < size; i++) { 6056 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6057 } 6058 } 6059 if (hasWebURI(intent)) { 6060 // cross-profile app linking works only towards the parent. 6061 final UserInfo parent = getProfileParent(sourceUserId); 6062 synchronized(mPackages) { 6063 int flags = updateFlagsForResolve(0, parent.id, intent); 6064 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6065 intent, resolvedType, flags, sourceUserId, parent.id); 6066 return xpDomainInfo != null; 6067 } 6068 } 6069 return false; 6070 } 6071 6072 private UserInfo getProfileParent(int userId) { 6073 final long identity = Binder.clearCallingIdentity(); 6074 try { 6075 return sUserManager.getProfileParent(userId); 6076 } finally { 6077 Binder.restoreCallingIdentity(identity); 6078 } 6079 } 6080 6081 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6082 String resolvedType, int userId) { 6083 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6084 if (resolver != null) { 6085 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6086 } 6087 return null; 6088 } 6089 6090 @Override 6091 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6092 String resolvedType, int flags, int userId) { 6093 try { 6094 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6095 6096 return new ParceledListSlice<>( 6097 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6098 } finally { 6099 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6100 } 6101 } 6102 6103 /** 6104 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6105 * instant, returns {@code null}. 6106 */ 6107 private String getInstantAppPackageName(int callingUid) { 6108 final int appId = UserHandle.getAppId(callingUid); 6109 synchronized (mPackages) { 6110 final Object obj = mSettings.getUserIdLPr(appId); 6111 if (obj instanceof PackageSetting) { 6112 final PackageSetting ps = (PackageSetting) obj; 6113 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6114 return isInstantApp ? ps.pkg.packageName : null; 6115 } 6116 } 6117 return null; 6118 } 6119 6120 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6121 String resolvedType, int flags, int userId) { 6122 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6123 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6124 flags = updateFlagsForResolve(flags, userId, intent); 6125 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6126 false /* requireFullPermission */, false /* checkShell */, 6127 "query intent activities"); 6128 ComponentName comp = intent.getComponent(); 6129 if (comp == null) { 6130 if (intent.getSelector() != null) { 6131 intent = intent.getSelector(); 6132 comp = intent.getComponent(); 6133 } 6134 } 6135 6136 if (comp != null) { 6137 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6138 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6139 if (ai != null) { 6140 // When specifying an explicit component, we prevent the activity from being 6141 // used when either 1) the calling package is normal and the activity is within 6142 // an ephemeral application or 2) the calling package is ephemeral and the 6143 // activity is not visible to ephemeral applications. 6144 final boolean matchInstantApp = 6145 (flags & PackageManager.MATCH_INSTANT) != 0; 6146 final boolean matchVisibleToInstantAppOnly = 6147 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6148 final boolean isCallerInstantApp = 6149 instantAppPkgName != null; 6150 final boolean isTargetSameInstantApp = 6151 comp.getPackageName().equals(instantAppPkgName); 6152 final boolean isTargetInstantApp = 6153 (ai.applicationInfo.privateFlags 6154 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6155 final boolean isTargetHiddenFromInstantApp = 6156 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6157 final boolean blockResolution = 6158 !isTargetSameInstantApp 6159 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6160 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6161 && isTargetHiddenFromInstantApp)); 6162 if (!blockResolution) { 6163 final ResolveInfo ri = new ResolveInfo(); 6164 ri.activityInfo = ai; 6165 list.add(ri); 6166 } 6167 } 6168 return applyPostResolutionFilter(list, instantAppPkgName); 6169 } 6170 6171 // reader 6172 boolean sortResult = false; 6173 boolean addEphemeral = false; 6174 List<ResolveInfo> result; 6175 final String pkgName = intent.getPackage(); 6176 synchronized (mPackages) { 6177 if (pkgName == null) { 6178 List<CrossProfileIntentFilter> matchingFilters = 6179 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6180 // Check for results that need to skip the current profile. 6181 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6182 resolvedType, flags, userId); 6183 if (xpResolveInfo != null) { 6184 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6185 xpResult.add(xpResolveInfo); 6186 return applyPostResolutionFilter( 6187 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6188 } 6189 6190 // Check for results in the current profile. 6191 result = filterIfNotSystemUser(mActivities.queryIntent( 6192 intent, resolvedType, flags, userId), userId); 6193 addEphemeral = 6194 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6195 6196 // Check for cross profile results. 6197 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6198 xpResolveInfo = queryCrossProfileIntents( 6199 matchingFilters, intent, resolvedType, flags, userId, 6200 hasNonNegativePriorityResult); 6201 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6202 boolean isVisibleToUser = filterIfNotSystemUser( 6203 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6204 if (isVisibleToUser) { 6205 result.add(xpResolveInfo); 6206 sortResult = true; 6207 } 6208 } 6209 if (hasWebURI(intent)) { 6210 CrossProfileDomainInfo xpDomainInfo = null; 6211 final UserInfo parent = getProfileParent(userId); 6212 if (parent != null) { 6213 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6214 flags, userId, parent.id); 6215 } 6216 if (xpDomainInfo != null) { 6217 if (xpResolveInfo != null) { 6218 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6219 // in the result. 6220 result.remove(xpResolveInfo); 6221 } 6222 if (result.size() == 0 && !addEphemeral) { 6223 // No result in current profile, but found candidate in parent user. 6224 // And we are not going to add emphemeral app, so we can return the 6225 // result straight away. 6226 result.add(xpDomainInfo.resolveInfo); 6227 return applyPostResolutionFilter(result, instantAppPkgName); 6228 } 6229 } else if (result.size() <= 1 && !addEphemeral) { 6230 // No result in parent user and <= 1 result in current profile, and we 6231 // are not going to add emphemeral app, so we can return the result without 6232 // further processing. 6233 return applyPostResolutionFilter(result, instantAppPkgName); 6234 } 6235 // We have more than one candidate (combining results from current and parent 6236 // profile), so we need filtering and sorting. 6237 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6238 intent, flags, result, xpDomainInfo, userId); 6239 sortResult = true; 6240 } 6241 } else { 6242 final PackageParser.Package pkg = mPackages.get(pkgName); 6243 if (pkg != null) { 6244 result = applyPostResolutionFilter(filterIfNotSystemUser( 6245 mActivities.queryIntentForPackage( 6246 intent, resolvedType, flags, pkg.activities, userId), 6247 userId), instantAppPkgName); 6248 } else { 6249 // the caller wants to resolve for a particular package; however, there 6250 // were no installed results, so, try to find an ephemeral result 6251 addEphemeral = isEphemeralAllowed( 6252 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6253 result = new ArrayList<ResolveInfo>(); 6254 } 6255 } 6256 } 6257 if (addEphemeral) { 6258 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6259 final EphemeralRequest requestObject = new EphemeralRequest( 6260 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6261 null /*callingPackage*/, userId); 6262 final AuxiliaryResolveInfo auxiliaryResponse = 6263 EphemeralResolver.doEphemeralResolutionPhaseOne( 6264 mContext, mInstantAppResolverConnection, requestObject); 6265 if (auxiliaryResponse != null) { 6266 if (DEBUG_EPHEMERAL) { 6267 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6268 } 6269 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6270 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6271 // make sure this resolver is the default 6272 ephemeralInstaller.isDefault = true; 6273 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6274 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6275 // add a non-generic filter 6276 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6277 ephemeralInstaller.filter.addDataPath( 6278 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6279 result.add(ephemeralInstaller); 6280 } 6281 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6282 } 6283 if (sortResult) { 6284 Collections.sort(result, mResolvePrioritySorter); 6285 } 6286 return applyPostResolutionFilter(result, instantAppPkgName); 6287 } 6288 6289 private static class CrossProfileDomainInfo { 6290 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6291 ResolveInfo resolveInfo; 6292 /* Best domain verification status of the activities found in the other profile */ 6293 int bestDomainVerificationStatus; 6294 } 6295 6296 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6297 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6298 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6299 sourceUserId)) { 6300 return null; 6301 } 6302 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6303 resolvedType, flags, parentUserId); 6304 6305 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6306 return null; 6307 } 6308 CrossProfileDomainInfo result = null; 6309 int size = resultTargetUser.size(); 6310 for (int i = 0; i < size; i++) { 6311 ResolveInfo riTargetUser = resultTargetUser.get(i); 6312 // Intent filter verification is only for filters that specify a host. So don't return 6313 // those that handle all web uris. 6314 if (riTargetUser.handleAllWebDataURI) { 6315 continue; 6316 } 6317 String packageName = riTargetUser.activityInfo.packageName; 6318 PackageSetting ps = mSettings.mPackages.get(packageName); 6319 if (ps == null) { 6320 continue; 6321 } 6322 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6323 int status = (int)(verificationState >> 32); 6324 if (result == null) { 6325 result = new CrossProfileDomainInfo(); 6326 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6327 sourceUserId, parentUserId); 6328 result.bestDomainVerificationStatus = status; 6329 } else { 6330 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6331 result.bestDomainVerificationStatus); 6332 } 6333 } 6334 // Don't consider matches with status NEVER across profiles. 6335 if (result != null && result.bestDomainVerificationStatus 6336 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6337 return null; 6338 } 6339 return result; 6340 } 6341 6342 /** 6343 * Verification statuses are ordered from the worse to the best, except for 6344 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6345 */ 6346 private int bestDomainVerificationStatus(int status1, int status2) { 6347 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6348 return status2; 6349 } 6350 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6351 return status1; 6352 } 6353 return (int) MathUtils.max(status1, status2); 6354 } 6355 6356 private boolean isUserEnabled(int userId) { 6357 long callingId = Binder.clearCallingIdentity(); 6358 try { 6359 UserInfo userInfo = sUserManager.getUserInfo(userId); 6360 return userInfo != null && userInfo.isEnabled(); 6361 } finally { 6362 Binder.restoreCallingIdentity(callingId); 6363 } 6364 } 6365 6366 /** 6367 * Filter out activities with systemUserOnly flag set, when current user is not System. 6368 * 6369 * @return filtered list 6370 */ 6371 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6372 if (userId == UserHandle.USER_SYSTEM) { 6373 return resolveInfos; 6374 } 6375 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6376 ResolveInfo info = resolveInfos.get(i); 6377 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6378 resolveInfos.remove(i); 6379 } 6380 } 6381 return resolveInfos; 6382 } 6383 6384 /** 6385 * Filters out ephemeral activities. 6386 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6387 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6388 * 6389 * @param resolveInfos The pre-filtered list of resolved activities 6390 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6391 * is performed. 6392 * @return A filtered list of resolved activities. 6393 */ 6394 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6395 String ephemeralPkgName) { 6396 // TODO: When adding on-demand split support for non-instant apps, remove this check 6397 // and always apply post filtering 6398 if (ephemeralPkgName == null) { 6399 return resolveInfos; 6400 } 6401 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6402 final ResolveInfo info = resolveInfos.get(i); 6403 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6404 // allow activities that are defined in the provided package 6405 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6406 if (info.activityInfo.splitName != null 6407 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6408 info.activityInfo.splitName)) { 6409 // requested activity is defined in a split that hasn't been installed yet. 6410 // add the installer to the resolve list 6411 if (DEBUG_EPHEMERAL) { 6412 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6413 } 6414 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6415 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6416 info.activityInfo.packageName, info.activityInfo.splitName, 6417 info.activityInfo.applicationInfo.versionCode); 6418 // make sure this resolver is the default 6419 installerInfo.isDefault = true; 6420 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6421 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6422 // add a non-generic filter 6423 installerInfo.filter = new IntentFilter(); 6424 // load resources from the correct package 6425 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6426 resolveInfos.set(i, installerInfo); 6427 } 6428 continue; 6429 } 6430 // allow activities that have been explicitly exposed to ephemeral apps 6431 if (!isEphemeralApp 6432 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6433 continue; 6434 } 6435 resolveInfos.remove(i); 6436 } 6437 return resolveInfos; 6438 } 6439 6440 /** 6441 * @param resolveInfos list of resolve infos in descending priority order 6442 * @return if the list contains a resolve info with non-negative priority 6443 */ 6444 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6445 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6446 } 6447 6448 private static boolean hasWebURI(Intent intent) { 6449 if (intent.getData() == null) { 6450 return false; 6451 } 6452 final String scheme = intent.getScheme(); 6453 if (TextUtils.isEmpty(scheme)) { 6454 return false; 6455 } 6456 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6457 } 6458 6459 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6460 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6461 int userId) { 6462 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6463 6464 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6465 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6466 candidates.size()); 6467 } 6468 6469 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6470 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6471 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6472 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6473 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6474 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6475 6476 synchronized (mPackages) { 6477 final int count = candidates.size(); 6478 // First, try to use linked apps. Partition the candidates into four lists: 6479 // one for the final results, one for the "do not use ever", one for "undefined status" 6480 // and finally one for "browser app type". 6481 for (int n=0; n<count; n++) { 6482 ResolveInfo info = candidates.get(n); 6483 String packageName = info.activityInfo.packageName; 6484 PackageSetting ps = mSettings.mPackages.get(packageName); 6485 if (ps != null) { 6486 // Add to the special match all list (Browser use case) 6487 if (info.handleAllWebDataURI) { 6488 matchAllList.add(info); 6489 continue; 6490 } 6491 // Try to get the status from User settings first 6492 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6493 int status = (int)(packedStatus >> 32); 6494 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6495 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6496 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6497 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6498 + " : linkgen=" + linkGeneration); 6499 } 6500 // Use link-enabled generation as preferredOrder, i.e. 6501 // prefer newly-enabled over earlier-enabled. 6502 info.preferredOrder = linkGeneration; 6503 alwaysList.add(info); 6504 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6505 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6506 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6507 } 6508 neverList.add(info); 6509 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6510 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6511 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6512 } 6513 alwaysAskList.add(info); 6514 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6515 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6516 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6517 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6518 } 6519 undefinedList.add(info); 6520 } 6521 } 6522 } 6523 6524 // We'll want to include browser possibilities in a few cases 6525 boolean includeBrowser = false; 6526 6527 // First try to add the "always" resolution(s) for the current user, if any 6528 if (alwaysList.size() > 0) { 6529 result.addAll(alwaysList); 6530 } else { 6531 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6532 result.addAll(undefinedList); 6533 // Maybe add one for the other profile. 6534 if (xpDomainInfo != null && ( 6535 xpDomainInfo.bestDomainVerificationStatus 6536 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6537 result.add(xpDomainInfo.resolveInfo); 6538 } 6539 includeBrowser = true; 6540 } 6541 6542 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6543 // If there were 'always' entries their preferred order has been set, so we also 6544 // back that off to make the alternatives equivalent 6545 if (alwaysAskList.size() > 0) { 6546 for (ResolveInfo i : result) { 6547 i.preferredOrder = 0; 6548 } 6549 result.addAll(alwaysAskList); 6550 includeBrowser = true; 6551 } 6552 6553 if (includeBrowser) { 6554 // Also add browsers (all of them or only the default one) 6555 if (DEBUG_DOMAIN_VERIFICATION) { 6556 Slog.v(TAG, " ...including browsers in candidate set"); 6557 } 6558 if ((matchFlags & MATCH_ALL) != 0) { 6559 result.addAll(matchAllList); 6560 } else { 6561 // Browser/generic handling case. If there's a default browser, go straight 6562 // to that (but only if there is no other higher-priority match). 6563 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6564 int maxMatchPrio = 0; 6565 ResolveInfo defaultBrowserMatch = null; 6566 final int numCandidates = matchAllList.size(); 6567 for (int n = 0; n < numCandidates; n++) { 6568 ResolveInfo info = matchAllList.get(n); 6569 // track the highest overall match priority... 6570 if (info.priority > maxMatchPrio) { 6571 maxMatchPrio = info.priority; 6572 } 6573 // ...and the highest-priority default browser match 6574 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6575 if (defaultBrowserMatch == null 6576 || (defaultBrowserMatch.priority < info.priority)) { 6577 if (debug) { 6578 Slog.v(TAG, "Considering default browser match " + info); 6579 } 6580 defaultBrowserMatch = info; 6581 } 6582 } 6583 } 6584 if (defaultBrowserMatch != null 6585 && defaultBrowserMatch.priority >= maxMatchPrio 6586 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6587 { 6588 if (debug) { 6589 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6590 } 6591 result.add(defaultBrowserMatch); 6592 } else { 6593 result.addAll(matchAllList); 6594 } 6595 } 6596 6597 // If there is nothing selected, add all candidates and remove the ones that the user 6598 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6599 if (result.size() == 0) { 6600 result.addAll(candidates); 6601 result.removeAll(neverList); 6602 } 6603 } 6604 } 6605 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6606 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6607 result.size()); 6608 for (ResolveInfo info : result) { 6609 Slog.v(TAG, " + " + info.activityInfo); 6610 } 6611 } 6612 return result; 6613 } 6614 6615 // Returns a packed value as a long: 6616 // 6617 // high 'int'-sized word: link status: undefined/ask/never/always. 6618 // low 'int'-sized word: relative priority among 'always' results. 6619 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6620 long result = ps.getDomainVerificationStatusForUser(userId); 6621 // if none available, get the master status 6622 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6623 if (ps.getIntentFilterVerificationInfo() != null) { 6624 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6625 } 6626 } 6627 return result; 6628 } 6629 6630 private ResolveInfo querySkipCurrentProfileIntents( 6631 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6632 int flags, int sourceUserId) { 6633 if (matchingFilters != null) { 6634 int size = matchingFilters.size(); 6635 for (int i = 0; i < size; i ++) { 6636 CrossProfileIntentFilter filter = matchingFilters.get(i); 6637 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6638 // Checking if there are activities in the target user that can handle the 6639 // intent. 6640 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6641 resolvedType, flags, sourceUserId); 6642 if (resolveInfo != null) { 6643 return resolveInfo; 6644 } 6645 } 6646 } 6647 } 6648 return null; 6649 } 6650 6651 // Return matching ResolveInfo in target user if any. 6652 private ResolveInfo queryCrossProfileIntents( 6653 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6654 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6655 if (matchingFilters != null) { 6656 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6657 // match the same intent. For performance reasons, it is better not to 6658 // run queryIntent twice for the same userId 6659 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6660 int size = matchingFilters.size(); 6661 for (int i = 0; i < size; i++) { 6662 CrossProfileIntentFilter filter = matchingFilters.get(i); 6663 int targetUserId = filter.getTargetUserId(); 6664 boolean skipCurrentProfile = 6665 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6666 boolean skipCurrentProfileIfNoMatchFound = 6667 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6668 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6669 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6670 // Checking if there are activities in the target user that can handle the 6671 // intent. 6672 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6673 resolvedType, flags, sourceUserId); 6674 if (resolveInfo != null) return resolveInfo; 6675 alreadyTriedUserIds.put(targetUserId, true); 6676 } 6677 } 6678 } 6679 return null; 6680 } 6681 6682 /** 6683 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6684 * will forward the intent to the filter's target user. 6685 * Otherwise, returns null. 6686 */ 6687 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6688 String resolvedType, int flags, int sourceUserId) { 6689 int targetUserId = filter.getTargetUserId(); 6690 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6691 resolvedType, flags, targetUserId); 6692 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6693 // If all the matches in the target profile are suspended, return null. 6694 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6695 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6696 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6697 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6698 targetUserId); 6699 } 6700 } 6701 } 6702 return null; 6703 } 6704 6705 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6706 int sourceUserId, int targetUserId) { 6707 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6708 long ident = Binder.clearCallingIdentity(); 6709 boolean targetIsProfile; 6710 try { 6711 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6712 } finally { 6713 Binder.restoreCallingIdentity(ident); 6714 } 6715 String className; 6716 if (targetIsProfile) { 6717 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6718 } else { 6719 className = FORWARD_INTENT_TO_PARENT; 6720 } 6721 ComponentName forwardingActivityComponentName = new ComponentName( 6722 mAndroidApplication.packageName, className); 6723 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6724 sourceUserId); 6725 if (!targetIsProfile) { 6726 forwardingActivityInfo.showUserIcon = targetUserId; 6727 forwardingResolveInfo.noResourceId = true; 6728 } 6729 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6730 forwardingResolveInfo.priority = 0; 6731 forwardingResolveInfo.preferredOrder = 0; 6732 forwardingResolveInfo.match = 0; 6733 forwardingResolveInfo.isDefault = true; 6734 forwardingResolveInfo.filter = filter; 6735 forwardingResolveInfo.targetUserId = targetUserId; 6736 return forwardingResolveInfo; 6737 } 6738 6739 @Override 6740 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6741 Intent[] specifics, String[] specificTypes, Intent intent, 6742 String resolvedType, int flags, int userId) { 6743 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6744 specificTypes, intent, resolvedType, flags, userId)); 6745 } 6746 6747 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6748 Intent[] specifics, String[] specificTypes, Intent intent, 6749 String resolvedType, int flags, int userId) { 6750 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6751 flags = updateFlagsForResolve(flags, userId, intent); 6752 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6753 false /* requireFullPermission */, false /* checkShell */, 6754 "query intent activity options"); 6755 final String resultsAction = intent.getAction(); 6756 6757 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6758 | PackageManager.GET_RESOLVED_FILTER, userId); 6759 6760 if (DEBUG_INTENT_MATCHING) { 6761 Log.v(TAG, "Query " + intent + ": " + results); 6762 } 6763 6764 int specificsPos = 0; 6765 int N; 6766 6767 // todo: note that the algorithm used here is O(N^2). This 6768 // isn't a problem in our current environment, but if we start running 6769 // into situations where we have more than 5 or 10 matches then this 6770 // should probably be changed to something smarter... 6771 6772 // First we go through and resolve each of the specific items 6773 // that were supplied, taking care of removing any corresponding 6774 // duplicate items in the generic resolve list. 6775 if (specifics != null) { 6776 for (int i=0; i<specifics.length; i++) { 6777 final Intent sintent = specifics[i]; 6778 if (sintent == null) { 6779 continue; 6780 } 6781 6782 if (DEBUG_INTENT_MATCHING) { 6783 Log.v(TAG, "Specific #" + i + ": " + sintent); 6784 } 6785 6786 String action = sintent.getAction(); 6787 if (resultsAction != null && resultsAction.equals(action)) { 6788 // If this action was explicitly requested, then don't 6789 // remove things that have it. 6790 action = null; 6791 } 6792 6793 ResolveInfo ri = null; 6794 ActivityInfo ai = null; 6795 6796 ComponentName comp = sintent.getComponent(); 6797 if (comp == null) { 6798 ri = resolveIntent( 6799 sintent, 6800 specificTypes != null ? specificTypes[i] : null, 6801 flags, userId); 6802 if (ri == null) { 6803 continue; 6804 } 6805 if (ri == mResolveInfo) { 6806 // ACK! Must do something better with this. 6807 } 6808 ai = ri.activityInfo; 6809 comp = new ComponentName(ai.applicationInfo.packageName, 6810 ai.name); 6811 } else { 6812 ai = getActivityInfo(comp, flags, userId); 6813 if (ai == null) { 6814 continue; 6815 } 6816 } 6817 6818 // Look for any generic query activities that are duplicates 6819 // of this specific one, and remove them from the results. 6820 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6821 N = results.size(); 6822 int j; 6823 for (j=specificsPos; j<N; j++) { 6824 ResolveInfo sri = results.get(j); 6825 if ((sri.activityInfo.name.equals(comp.getClassName()) 6826 && sri.activityInfo.applicationInfo.packageName.equals( 6827 comp.getPackageName())) 6828 || (action != null && sri.filter.matchAction(action))) { 6829 results.remove(j); 6830 if (DEBUG_INTENT_MATCHING) Log.v( 6831 TAG, "Removing duplicate item from " + j 6832 + " due to specific " + specificsPos); 6833 if (ri == null) { 6834 ri = sri; 6835 } 6836 j--; 6837 N--; 6838 } 6839 } 6840 6841 // Add this specific item to its proper place. 6842 if (ri == null) { 6843 ri = new ResolveInfo(); 6844 ri.activityInfo = ai; 6845 } 6846 results.add(specificsPos, ri); 6847 ri.specificIndex = i; 6848 specificsPos++; 6849 } 6850 } 6851 6852 // Now we go through the remaining generic results and remove any 6853 // duplicate actions that are found here. 6854 N = results.size(); 6855 for (int i=specificsPos; i<N-1; i++) { 6856 final ResolveInfo rii = results.get(i); 6857 if (rii.filter == null) { 6858 continue; 6859 } 6860 6861 // Iterate over all of the actions of this result's intent 6862 // filter... typically this should be just one. 6863 final Iterator<String> it = rii.filter.actionsIterator(); 6864 if (it == null) { 6865 continue; 6866 } 6867 while (it.hasNext()) { 6868 final String action = it.next(); 6869 if (resultsAction != null && resultsAction.equals(action)) { 6870 // If this action was explicitly requested, then don't 6871 // remove things that have it. 6872 continue; 6873 } 6874 for (int j=i+1; j<N; j++) { 6875 final ResolveInfo rij = results.get(j); 6876 if (rij.filter != null && rij.filter.hasAction(action)) { 6877 results.remove(j); 6878 if (DEBUG_INTENT_MATCHING) Log.v( 6879 TAG, "Removing duplicate item from " + j 6880 + " due to action " + action + " at " + i); 6881 j--; 6882 N--; 6883 } 6884 } 6885 } 6886 6887 // If the caller didn't request filter information, drop it now 6888 // so we don't have to marshall/unmarshall it. 6889 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6890 rii.filter = null; 6891 } 6892 } 6893 6894 // Filter out the caller activity if so requested. 6895 if (caller != null) { 6896 N = results.size(); 6897 for (int i=0; i<N; i++) { 6898 ActivityInfo ainfo = results.get(i).activityInfo; 6899 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6900 && caller.getClassName().equals(ainfo.name)) { 6901 results.remove(i); 6902 break; 6903 } 6904 } 6905 } 6906 6907 // If the caller didn't request filter information, 6908 // drop them now so we don't have to 6909 // marshall/unmarshall it. 6910 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6911 N = results.size(); 6912 for (int i=0; i<N; i++) { 6913 results.get(i).filter = null; 6914 } 6915 } 6916 6917 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6918 return results; 6919 } 6920 6921 @Override 6922 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6923 String resolvedType, int flags, int userId) { 6924 return new ParceledListSlice<>( 6925 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6926 } 6927 6928 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6929 String resolvedType, int flags, int userId) { 6930 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6931 flags = updateFlagsForResolve(flags, userId, intent); 6932 ComponentName comp = intent.getComponent(); 6933 if (comp == null) { 6934 if (intent.getSelector() != null) { 6935 intent = intent.getSelector(); 6936 comp = intent.getComponent(); 6937 } 6938 } 6939 if (comp != null) { 6940 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6941 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6942 if (ai != null) { 6943 ResolveInfo ri = new ResolveInfo(); 6944 ri.activityInfo = ai; 6945 list.add(ri); 6946 } 6947 return list; 6948 } 6949 6950 // reader 6951 synchronized (mPackages) { 6952 String pkgName = intent.getPackage(); 6953 if (pkgName == null) { 6954 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6955 } 6956 final PackageParser.Package pkg = mPackages.get(pkgName); 6957 if (pkg != null) { 6958 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6959 userId); 6960 } 6961 return Collections.emptyList(); 6962 } 6963 } 6964 6965 @Override 6966 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6967 if (!sUserManager.exists(userId)) return null; 6968 flags = updateFlagsForResolve(flags, userId, intent); 6969 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6970 if (query != null) { 6971 if (query.size() >= 1) { 6972 // If there is more than one service with the same priority, 6973 // just arbitrarily pick the first one. 6974 return query.get(0); 6975 } 6976 } 6977 return null; 6978 } 6979 6980 @Override 6981 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6982 String resolvedType, int flags, int userId) { 6983 return new ParceledListSlice<>( 6984 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6985 } 6986 6987 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6988 String resolvedType, int flags, int userId) { 6989 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6990 flags = updateFlagsForResolve(flags, userId, intent); 6991 ComponentName comp = intent.getComponent(); 6992 if (comp == null) { 6993 if (intent.getSelector() != null) { 6994 intent = intent.getSelector(); 6995 comp = intent.getComponent(); 6996 } 6997 } 6998 if (comp != null) { 6999 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7000 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7001 if (si != null) { 7002 final ResolveInfo ri = new ResolveInfo(); 7003 ri.serviceInfo = si; 7004 list.add(ri); 7005 } 7006 return list; 7007 } 7008 7009 // reader 7010 synchronized (mPackages) { 7011 String pkgName = intent.getPackage(); 7012 if (pkgName == null) { 7013 return mServices.queryIntent(intent, resolvedType, flags, userId); 7014 } 7015 final PackageParser.Package pkg = mPackages.get(pkgName); 7016 if (pkg != null) { 7017 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7018 userId); 7019 } 7020 return Collections.emptyList(); 7021 } 7022 } 7023 7024 @Override 7025 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7026 String resolvedType, int flags, int userId) { 7027 return new ParceledListSlice<>( 7028 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7029 } 7030 7031 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7032 Intent intent, String resolvedType, int flags, int userId) { 7033 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7034 flags = updateFlagsForResolve(flags, userId, intent); 7035 ComponentName comp = intent.getComponent(); 7036 if (comp == null) { 7037 if (intent.getSelector() != null) { 7038 intent = intent.getSelector(); 7039 comp = intent.getComponent(); 7040 } 7041 } 7042 if (comp != null) { 7043 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7044 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7045 if (pi != null) { 7046 final ResolveInfo ri = new ResolveInfo(); 7047 ri.providerInfo = pi; 7048 list.add(ri); 7049 } 7050 return list; 7051 } 7052 7053 // reader 7054 synchronized (mPackages) { 7055 String pkgName = intent.getPackage(); 7056 if (pkgName == null) { 7057 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7058 } 7059 final PackageParser.Package pkg = mPackages.get(pkgName); 7060 if (pkg != null) { 7061 return mProviders.queryIntentForPackage( 7062 intent, resolvedType, flags, pkg.providers, userId); 7063 } 7064 return Collections.emptyList(); 7065 } 7066 } 7067 7068 @Override 7069 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7070 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7071 flags = updateFlagsForPackage(flags, userId, null); 7072 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7073 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7074 true /* requireFullPermission */, false /* checkShell */, 7075 "get installed packages"); 7076 7077 // writer 7078 synchronized (mPackages) { 7079 ArrayList<PackageInfo> list; 7080 if (listUninstalled) { 7081 list = new ArrayList<>(mSettings.mPackages.size()); 7082 for (PackageSetting ps : mSettings.mPackages.values()) { 7083 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7084 continue; 7085 } 7086 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7087 if (pi != null) { 7088 list.add(pi); 7089 } 7090 } 7091 } else { 7092 list = new ArrayList<>(mPackages.size()); 7093 for (PackageParser.Package p : mPackages.values()) { 7094 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7095 Binder.getCallingUid(), userId)) { 7096 continue; 7097 } 7098 final PackageInfo pi = generatePackageInfo((PackageSetting) 7099 p.mExtras, flags, userId); 7100 if (pi != null) { 7101 list.add(pi); 7102 } 7103 } 7104 } 7105 7106 return new ParceledListSlice<>(list); 7107 } 7108 } 7109 7110 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7111 String[] permissions, boolean[] tmp, int flags, int userId) { 7112 int numMatch = 0; 7113 final PermissionsState permissionsState = ps.getPermissionsState(); 7114 for (int i=0; i<permissions.length; i++) { 7115 final String permission = permissions[i]; 7116 if (permissionsState.hasPermission(permission, userId)) { 7117 tmp[i] = true; 7118 numMatch++; 7119 } else { 7120 tmp[i] = false; 7121 } 7122 } 7123 if (numMatch == 0) { 7124 return; 7125 } 7126 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7127 7128 // The above might return null in cases of uninstalled apps or install-state 7129 // skew across users/profiles. 7130 if (pi != null) { 7131 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7132 if (numMatch == permissions.length) { 7133 pi.requestedPermissions = permissions; 7134 } else { 7135 pi.requestedPermissions = new String[numMatch]; 7136 numMatch = 0; 7137 for (int i=0; i<permissions.length; i++) { 7138 if (tmp[i]) { 7139 pi.requestedPermissions[numMatch] = permissions[i]; 7140 numMatch++; 7141 } 7142 } 7143 } 7144 } 7145 list.add(pi); 7146 } 7147 } 7148 7149 @Override 7150 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7151 String[] permissions, int flags, int userId) { 7152 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7153 flags = updateFlagsForPackage(flags, userId, permissions); 7154 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7155 true /* requireFullPermission */, false /* checkShell */, 7156 "get packages holding permissions"); 7157 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7158 7159 // writer 7160 synchronized (mPackages) { 7161 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7162 boolean[] tmpBools = new boolean[permissions.length]; 7163 if (listUninstalled) { 7164 for (PackageSetting ps : mSettings.mPackages.values()) { 7165 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7166 userId); 7167 } 7168 } else { 7169 for (PackageParser.Package pkg : mPackages.values()) { 7170 PackageSetting ps = (PackageSetting)pkg.mExtras; 7171 if (ps != null) { 7172 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7173 userId); 7174 } 7175 } 7176 } 7177 7178 return new ParceledListSlice<PackageInfo>(list); 7179 } 7180 } 7181 7182 @Override 7183 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7184 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7185 flags = updateFlagsForApplication(flags, userId, null); 7186 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7187 7188 // writer 7189 synchronized (mPackages) { 7190 ArrayList<ApplicationInfo> list; 7191 if (listUninstalled) { 7192 list = new ArrayList<>(mSettings.mPackages.size()); 7193 for (PackageSetting ps : mSettings.mPackages.values()) { 7194 ApplicationInfo ai; 7195 int effectiveFlags = flags; 7196 if (ps.isSystem()) { 7197 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7198 } 7199 if (ps.pkg != null) { 7200 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7201 continue; 7202 } 7203 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7204 ps.readUserState(userId), userId); 7205 if (ai != null) { 7206 rebaseEnabledOverlays(ai, userId); 7207 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7208 } 7209 } else { 7210 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7211 // and already converts to externally visible package name 7212 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7213 Binder.getCallingUid(), effectiveFlags, userId); 7214 } 7215 if (ai != null) { 7216 list.add(ai); 7217 } 7218 } 7219 } else { 7220 list = new ArrayList<>(mPackages.size()); 7221 for (PackageParser.Package p : mPackages.values()) { 7222 if (p.mExtras != null) { 7223 PackageSetting ps = (PackageSetting) p.mExtras; 7224 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7225 continue; 7226 } 7227 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7228 ps.readUserState(userId), userId); 7229 if (ai != null) { 7230 rebaseEnabledOverlays(ai, userId); 7231 ai.packageName = resolveExternalPackageNameLPr(p); 7232 list.add(ai); 7233 } 7234 } 7235 } 7236 } 7237 7238 return new ParceledListSlice<>(list); 7239 } 7240 } 7241 7242 @Override 7243 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7244 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7245 return null; 7246 } 7247 7248 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7249 "getEphemeralApplications"); 7250 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7251 true /* requireFullPermission */, false /* checkShell */, 7252 "getEphemeralApplications"); 7253 synchronized (mPackages) { 7254 List<InstantAppInfo> instantApps = mInstantAppRegistry 7255 .getInstantAppsLPr(userId); 7256 if (instantApps != null) { 7257 return new ParceledListSlice<>(instantApps); 7258 } 7259 } 7260 return null; 7261 } 7262 7263 @Override 7264 public boolean isInstantApp(String packageName, int userId) { 7265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7266 true /* requireFullPermission */, false /* checkShell */, 7267 "isInstantApp"); 7268 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7269 return false; 7270 } 7271 7272 if (!isCallerSameApp(packageName)) { 7273 return false; 7274 } 7275 synchronized (mPackages) { 7276 final PackageSetting ps = mSettings.mPackages.get(packageName); 7277 if (ps != null) { 7278 return ps.getInstantApp(userId); 7279 } 7280 } 7281 return false; 7282 } 7283 7284 @Override 7285 public byte[] getInstantAppCookie(String packageName, int userId) { 7286 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7287 return null; 7288 } 7289 7290 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7291 true /* requireFullPermission */, false /* checkShell */, 7292 "getInstantAppCookie"); 7293 if (!isCallerSameApp(packageName)) { 7294 return null; 7295 } 7296 synchronized (mPackages) { 7297 return mInstantAppRegistry.getInstantAppCookieLPw( 7298 packageName, userId); 7299 } 7300 } 7301 7302 @Override 7303 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7304 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7305 return true; 7306 } 7307 7308 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7309 true /* requireFullPermission */, true /* checkShell */, 7310 "setInstantAppCookie"); 7311 if (!isCallerSameApp(packageName)) { 7312 return false; 7313 } 7314 synchronized (mPackages) { 7315 return mInstantAppRegistry.setInstantAppCookieLPw( 7316 packageName, cookie, userId); 7317 } 7318 } 7319 7320 @Override 7321 public Bitmap getInstantAppIcon(String packageName, int userId) { 7322 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7323 return null; 7324 } 7325 7326 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7327 "getInstantAppIcon"); 7328 7329 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7330 true /* requireFullPermission */, false /* checkShell */, 7331 "getInstantAppIcon"); 7332 7333 synchronized (mPackages) { 7334 return mInstantAppRegistry.getInstantAppIconLPw( 7335 packageName, userId); 7336 } 7337 } 7338 7339 private boolean isCallerSameApp(String packageName) { 7340 PackageParser.Package pkg = mPackages.get(packageName); 7341 return pkg != null 7342 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7343 } 7344 7345 @Override 7346 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7347 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7348 } 7349 7350 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7351 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7352 7353 // reader 7354 synchronized (mPackages) { 7355 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7356 final int userId = UserHandle.getCallingUserId(); 7357 while (i.hasNext()) { 7358 final PackageParser.Package p = i.next(); 7359 if (p.applicationInfo == null) continue; 7360 7361 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7362 && !p.applicationInfo.isDirectBootAware(); 7363 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7364 && p.applicationInfo.isDirectBootAware(); 7365 7366 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7367 && (!mSafeMode || isSystemApp(p)) 7368 && (matchesUnaware || matchesAware)) { 7369 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7370 if (ps != null) { 7371 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7372 ps.readUserState(userId), userId); 7373 if (ai != null) { 7374 rebaseEnabledOverlays(ai, userId); 7375 finalList.add(ai); 7376 } 7377 } 7378 } 7379 } 7380 } 7381 7382 return finalList; 7383 } 7384 7385 @Override 7386 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7387 if (!sUserManager.exists(userId)) return null; 7388 flags = updateFlagsForComponent(flags, userId, name); 7389 // reader 7390 synchronized (mPackages) { 7391 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7392 PackageSetting ps = provider != null 7393 ? mSettings.mPackages.get(provider.owner.packageName) 7394 : null; 7395 return ps != null 7396 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7397 ? PackageParser.generateProviderInfo(provider, flags, 7398 ps.readUserState(userId), userId) 7399 : null; 7400 } 7401 } 7402 7403 /** 7404 * @deprecated 7405 */ 7406 @Deprecated 7407 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7408 // reader 7409 synchronized (mPackages) { 7410 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7411 .entrySet().iterator(); 7412 final int userId = UserHandle.getCallingUserId(); 7413 while (i.hasNext()) { 7414 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7415 PackageParser.Provider p = entry.getValue(); 7416 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7417 7418 if (ps != null && p.syncable 7419 && (!mSafeMode || (p.info.applicationInfo.flags 7420 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7421 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7422 ps.readUserState(userId), userId); 7423 if (info != null) { 7424 outNames.add(entry.getKey()); 7425 outInfo.add(info); 7426 } 7427 } 7428 } 7429 } 7430 } 7431 7432 @Override 7433 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7434 int uid, int flags) { 7435 final int userId = processName != null ? UserHandle.getUserId(uid) 7436 : UserHandle.getCallingUserId(); 7437 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7438 flags = updateFlagsForComponent(flags, userId, processName); 7439 7440 ArrayList<ProviderInfo> finalList = null; 7441 // reader 7442 synchronized (mPackages) { 7443 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7444 while (i.hasNext()) { 7445 final PackageParser.Provider p = i.next(); 7446 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7447 if (ps != null && p.info.authority != null 7448 && (processName == null 7449 || (p.info.processName.equals(processName) 7450 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7451 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7452 if (finalList == null) { 7453 finalList = new ArrayList<ProviderInfo>(3); 7454 } 7455 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7456 ps.readUserState(userId), userId); 7457 if (info != null) { 7458 finalList.add(info); 7459 } 7460 } 7461 } 7462 } 7463 7464 if (finalList != null) { 7465 Collections.sort(finalList, mProviderInitOrderSorter); 7466 return new ParceledListSlice<ProviderInfo>(finalList); 7467 } 7468 7469 return ParceledListSlice.emptyList(); 7470 } 7471 7472 @Override 7473 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7474 // reader 7475 synchronized (mPackages) { 7476 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7477 return PackageParser.generateInstrumentationInfo(i, flags); 7478 } 7479 } 7480 7481 @Override 7482 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7483 String targetPackage, int flags) { 7484 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7485 } 7486 7487 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7488 int flags) { 7489 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7490 7491 // reader 7492 synchronized (mPackages) { 7493 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7494 while (i.hasNext()) { 7495 final PackageParser.Instrumentation p = i.next(); 7496 if (targetPackage == null 7497 || targetPackage.equals(p.info.targetPackage)) { 7498 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7499 flags); 7500 if (ii != null) { 7501 finalList.add(ii); 7502 } 7503 } 7504 } 7505 } 7506 7507 return finalList; 7508 } 7509 7510 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7511 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7512 try { 7513 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7514 } finally { 7515 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7516 } 7517 } 7518 7519 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7520 final File[] files = dir.listFiles(); 7521 if (ArrayUtils.isEmpty(files)) { 7522 Log.d(TAG, "No files in app dir " + dir); 7523 return; 7524 } 7525 7526 if (DEBUG_PACKAGE_SCANNING) { 7527 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7528 + " flags=0x" + Integer.toHexString(parseFlags)); 7529 } 7530 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7531 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7532 7533 // Submit files for parsing in parallel 7534 int fileCount = 0; 7535 for (File file : files) { 7536 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7537 && !PackageInstallerService.isStageName(file.getName()); 7538 if (!isPackage) { 7539 // Ignore entries which are not packages 7540 continue; 7541 } 7542 parallelPackageParser.submit(file, parseFlags); 7543 fileCount++; 7544 } 7545 7546 // Process results one by one 7547 for (; fileCount > 0; fileCount--) { 7548 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7549 Throwable throwable = parseResult.throwable; 7550 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7551 7552 if (throwable == null) { 7553 // Static shared libraries have synthetic package names 7554 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7555 renameStaticSharedLibraryPackage(parseResult.pkg); 7556 } 7557 try { 7558 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7559 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7560 currentTime, null); 7561 } 7562 } catch (PackageManagerException e) { 7563 errorCode = e.error; 7564 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7565 } 7566 } else if (throwable instanceof PackageParser.PackageParserException) { 7567 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7568 throwable; 7569 errorCode = e.error; 7570 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7571 } else { 7572 throw new IllegalStateException("Unexpected exception occurred while parsing " 7573 + parseResult.scanFile, throwable); 7574 } 7575 7576 // Delete invalid userdata apps 7577 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7578 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7579 logCriticalInfo(Log.WARN, 7580 "Deleting invalid package at " + parseResult.scanFile); 7581 removeCodePathLI(parseResult.scanFile); 7582 } 7583 } 7584 parallelPackageParser.close(); 7585 } 7586 7587 private static File getSettingsProblemFile() { 7588 File dataDir = Environment.getDataDirectory(); 7589 File systemDir = new File(dataDir, "system"); 7590 File fname = new File(systemDir, "uiderrors.txt"); 7591 return fname; 7592 } 7593 7594 static void reportSettingsProblem(int priority, String msg) { 7595 logCriticalInfo(priority, msg); 7596 } 7597 7598 static void logCriticalInfo(int priority, String msg) { 7599 Slog.println(priority, TAG, msg); 7600 EventLogTags.writePmCriticalInfo(msg); 7601 try { 7602 File fname = getSettingsProblemFile(); 7603 FileOutputStream out = new FileOutputStream(fname, true); 7604 PrintWriter pw = new FastPrintWriter(out); 7605 SimpleDateFormat formatter = new SimpleDateFormat(); 7606 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7607 pw.println(dateString + ": " + msg); 7608 pw.close(); 7609 FileUtils.setPermissions( 7610 fname.toString(), 7611 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7612 -1, -1); 7613 } catch (java.io.IOException e) { 7614 } 7615 } 7616 7617 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7618 if (srcFile.isDirectory()) { 7619 final File baseFile = new File(pkg.baseCodePath); 7620 long maxModifiedTime = baseFile.lastModified(); 7621 if (pkg.splitCodePaths != null) { 7622 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7623 final File splitFile = new File(pkg.splitCodePaths[i]); 7624 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7625 } 7626 } 7627 return maxModifiedTime; 7628 } 7629 return srcFile.lastModified(); 7630 } 7631 7632 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7633 final int policyFlags) throws PackageManagerException { 7634 // When upgrading from pre-N MR1, verify the package time stamp using the package 7635 // directory and not the APK file. 7636 final long lastModifiedTime = mIsPreNMR1Upgrade 7637 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7638 if (ps != null 7639 && ps.codePath.equals(srcFile) 7640 && ps.timeStamp == lastModifiedTime 7641 && !isCompatSignatureUpdateNeeded(pkg) 7642 && !isRecoverSignatureUpdateNeeded(pkg)) { 7643 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7644 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7645 ArraySet<PublicKey> signingKs; 7646 synchronized (mPackages) { 7647 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7648 } 7649 if (ps.signatures.mSignatures != null 7650 && ps.signatures.mSignatures.length != 0 7651 && signingKs != null) { 7652 // Optimization: reuse the existing cached certificates 7653 // if the package appears to be unchanged. 7654 pkg.mSignatures = ps.signatures.mSignatures; 7655 pkg.mSigningKeys = signingKs; 7656 return; 7657 } 7658 7659 Slog.w(TAG, "PackageSetting for " + ps.name 7660 + " is missing signatures. Collecting certs again to recover them."); 7661 } else { 7662 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7663 } 7664 7665 try { 7666 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7667 PackageParser.collectCertificates(pkg, policyFlags); 7668 } catch (PackageParserException e) { 7669 throw PackageManagerException.from(e); 7670 } finally { 7671 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7672 } 7673 } 7674 7675 /** 7676 * Traces a package scan. 7677 * @see #scanPackageLI(File, int, int, long, UserHandle) 7678 */ 7679 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7680 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7681 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7682 try { 7683 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7684 } finally { 7685 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7686 } 7687 } 7688 7689 /** 7690 * Scans a package and returns the newly parsed package. 7691 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7692 */ 7693 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7694 long currentTime, UserHandle user) throws PackageManagerException { 7695 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7696 PackageParser pp = new PackageParser(); 7697 pp.setSeparateProcesses(mSeparateProcesses); 7698 pp.setOnlyCoreApps(mOnlyCore); 7699 pp.setDisplayMetrics(mMetrics); 7700 7701 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7702 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7703 } 7704 7705 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7706 final PackageParser.Package pkg; 7707 try { 7708 pkg = pp.parsePackage(scanFile, parseFlags); 7709 } catch (PackageParserException e) { 7710 throw PackageManagerException.from(e); 7711 } finally { 7712 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7713 } 7714 7715 // Static shared libraries have synthetic package names 7716 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7717 renameStaticSharedLibraryPackage(pkg); 7718 } 7719 7720 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7721 } 7722 7723 /** 7724 * Scans a package and returns the newly parsed package. 7725 * @throws PackageManagerException on a parse error. 7726 */ 7727 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7728 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7729 throws PackageManagerException { 7730 // If the package has children and this is the first dive in the function 7731 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7732 // packages (parent and children) would be successfully scanned before the 7733 // actual scan since scanning mutates internal state and we want to atomically 7734 // install the package and its children. 7735 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7736 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7737 scanFlags |= SCAN_CHECK_ONLY; 7738 } 7739 } else { 7740 scanFlags &= ~SCAN_CHECK_ONLY; 7741 } 7742 7743 // Scan the parent 7744 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7745 scanFlags, currentTime, user); 7746 7747 // Scan the children 7748 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7749 for (int i = 0; i < childCount; i++) { 7750 PackageParser.Package childPackage = pkg.childPackages.get(i); 7751 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7752 currentTime, user); 7753 } 7754 7755 7756 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7757 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7758 } 7759 7760 return scannedPkg; 7761 } 7762 7763 /** 7764 * Scans a package and returns the newly parsed package. 7765 * @throws PackageManagerException on a parse error. 7766 */ 7767 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7768 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7769 throws PackageManagerException { 7770 PackageSetting ps = null; 7771 PackageSetting updatedPkg; 7772 // reader 7773 synchronized (mPackages) { 7774 // Look to see if we already know about this package. 7775 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7776 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7777 // This package has been renamed to its original name. Let's 7778 // use that. 7779 ps = mSettings.getPackageLPr(oldName); 7780 } 7781 // If there was no original package, see one for the real package name. 7782 if (ps == null) { 7783 ps = mSettings.getPackageLPr(pkg.packageName); 7784 } 7785 // Check to see if this package could be hiding/updating a system 7786 // package. Must look for it either under the original or real 7787 // package name depending on our state. 7788 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7789 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7790 7791 // If this is a package we don't know about on the system partition, we 7792 // may need to remove disabled child packages on the system partition 7793 // or may need to not add child packages if the parent apk is updated 7794 // on the data partition and no longer defines this child package. 7795 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7796 // If this is a parent package for an updated system app and this system 7797 // app got an OTA update which no longer defines some of the child packages 7798 // we have to prune them from the disabled system packages. 7799 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7800 if (disabledPs != null) { 7801 final int scannedChildCount = (pkg.childPackages != null) 7802 ? pkg.childPackages.size() : 0; 7803 final int disabledChildCount = disabledPs.childPackageNames != null 7804 ? disabledPs.childPackageNames.size() : 0; 7805 for (int i = 0; i < disabledChildCount; i++) { 7806 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7807 boolean disabledPackageAvailable = false; 7808 for (int j = 0; j < scannedChildCount; j++) { 7809 PackageParser.Package childPkg = pkg.childPackages.get(j); 7810 if (childPkg.packageName.equals(disabledChildPackageName)) { 7811 disabledPackageAvailable = true; 7812 break; 7813 } 7814 } 7815 if (!disabledPackageAvailable) { 7816 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7817 } 7818 } 7819 } 7820 } 7821 } 7822 7823 boolean updatedPkgBetter = false; 7824 // First check if this is a system package that may involve an update 7825 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7826 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7827 // it needs to drop FLAG_PRIVILEGED. 7828 if (locationIsPrivileged(scanFile)) { 7829 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7830 } else { 7831 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7832 } 7833 7834 if (ps != null && !ps.codePath.equals(scanFile)) { 7835 // The path has changed from what was last scanned... check the 7836 // version of the new path against what we have stored to determine 7837 // what to do. 7838 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7839 if (pkg.mVersionCode <= ps.versionCode) { 7840 // The system package has been updated and the code path does not match 7841 // Ignore entry. Skip it. 7842 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7843 + " ignored: updated version " + ps.versionCode 7844 + " better than this " + pkg.mVersionCode); 7845 if (!updatedPkg.codePath.equals(scanFile)) { 7846 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7847 + ps.name + " changing from " + updatedPkg.codePathString 7848 + " to " + scanFile); 7849 updatedPkg.codePath = scanFile; 7850 updatedPkg.codePathString = scanFile.toString(); 7851 updatedPkg.resourcePath = scanFile; 7852 updatedPkg.resourcePathString = scanFile.toString(); 7853 } 7854 updatedPkg.pkg = pkg; 7855 updatedPkg.versionCode = pkg.mVersionCode; 7856 7857 // Update the disabled system child packages to point to the package too. 7858 final int childCount = updatedPkg.childPackageNames != null 7859 ? updatedPkg.childPackageNames.size() : 0; 7860 for (int i = 0; i < childCount; i++) { 7861 String childPackageName = updatedPkg.childPackageNames.get(i); 7862 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7863 childPackageName); 7864 if (updatedChildPkg != null) { 7865 updatedChildPkg.pkg = pkg; 7866 updatedChildPkg.versionCode = pkg.mVersionCode; 7867 } 7868 } 7869 7870 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7871 + scanFile + " ignored: updated version " + ps.versionCode 7872 + " better than this " + pkg.mVersionCode); 7873 } else { 7874 // The current app on the system partition is better than 7875 // what we have updated to on the data partition; switch 7876 // back to the system partition version. 7877 // At this point, its safely assumed that package installation for 7878 // apps in system partition will go through. If not there won't be a working 7879 // version of the app 7880 // writer 7881 synchronized (mPackages) { 7882 // Just remove the loaded entries from package lists. 7883 mPackages.remove(ps.name); 7884 } 7885 7886 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7887 + " reverting from " + ps.codePathString 7888 + ": new version " + pkg.mVersionCode 7889 + " better than installed " + ps.versionCode); 7890 7891 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7892 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7893 synchronized (mInstallLock) { 7894 args.cleanUpResourcesLI(); 7895 } 7896 synchronized (mPackages) { 7897 mSettings.enableSystemPackageLPw(ps.name); 7898 } 7899 updatedPkgBetter = true; 7900 } 7901 } 7902 } 7903 7904 if (updatedPkg != null) { 7905 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7906 // initially 7907 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7908 7909 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7910 // flag set initially 7911 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7912 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7913 } 7914 } 7915 7916 // Verify certificates against what was last scanned 7917 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7918 7919 /* 7920 * A new system app appeared, but we already had a non-system one of the 7921 * same name installed earlier. 7922 */ 7923 boolean shouldHideSystemApp = false; 7924 if (updatedPkg == null && ps != null 7925 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7926 /* 7927 * Check to make sure the signatures match first. If they don't, 7928 * wipe the installed application and its data. 7929 */ 7930 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7931 != PackageManager.SIGNATURE_MATCH) { 7932 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7933 + " signatures don't match existing userdata copy; removing"); 7934 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7935 "scanPackageInternalLI")) { 7936 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7937 } 7938 ps = null; 7939 } else { 7940 /* 7941 * If the newly-added system app is an older version than the 7942 * already installed version, hide it. It will be scanned later 7943 * and re-added like an update. 7944 */ 7945 if (pkg.mVersionCode <= ps.versionCode) { 7946 shouldHideSystemApp = true; 7947 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7948 + " but new version " + pkg.mVersionCode + " better than installed " 7949 + ps.versionCode + "; hiding system"); 7950 } else { 7951 /* 7952 * The newly found system app is a newer version that the 7953 * one previously installed. Simply remove the 7954 * already-installed application and replace it with our own 7955 * while keeping the application data. 7956 */ 7957 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7958 + " reverting from " + ps.codePathString + ": new version " 7959 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7960 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7961 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7962 synchronized (mInstallLock) { 7963 args.cleanUpResourcesLI(); 7964 } 7965 } 7966 } 7967 } 7968 7969 // The apk is forward locked (not public) if its code and resources 7970 // are kept in different files. (except for app in either system or 7971 // vendor path). 7972 // TODO grab this value from PackageSettings 7973 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7974 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7975 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7976 } 7977 } 7978 7979 // TODO: extend to support forward-locked splits 7980 String resourcePath = null; 7981 String baseResourcePath = null; 7982 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7983 if (ps != null && ps.resourcePathString != null) { 7984 resourcePath = ps.resourcePathString; 7985 baseResourcePath = ps.resourcePathString; 7986 } else { 7987 // Should not happen at all. Just log an error. 7988 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7989 } 7990 } else { 7991 resourcePath = pkg.codePath; 7992 baseResourcePath = pkg.baseCodePath; 7993 } 7994 7995 // Set application objects path explicitly. 7996 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7997 pkg.setApplicationInfoCodePath(pkg.codePath); 7998 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7999 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8000 pkg.setApplicationInfoResourcePath(resourcePath); 8001 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8002 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8003 8004 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8005 if (ps != null && ps.getInstantApp(userId)) { 8006 scanFlags |= SCAN_AS_INSTANT_APP; 8007 } 8008 8009 // Note that we invoke the following method only if we are about to unpack an application 8010 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8011 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8012 8013 /* 8014 * If the system app should be overridden by a previously installed 8015 * data, hide the system app now and let the /data/app scan pick it up 8016 * again. 8017 */ 8018 if (shouldHideSystemApp) { 8019 synchronized (mPackages) { 8020 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8021 } 8022 } 8023 8024 return scannedPkg; 8025 } 8026 8027 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8028 // Derive the new package synthetic package name 8029 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8030 + pkg.staticSharedLibVersion); 8031 } 8032 8033 private static String fixProcessName(String defProcessName, 8034 String processName) { 8035 if (processName == null) { 8036 return defProcessName; 8037 } 8038 return processName; 8039 } 8040 8041 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8042 throws PackageManagerException { 8043 if (pkgSetting.signatures.mSignatures != null) { 8044 // Already existing package. Make sure signatures match 8045 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8046 == PackageManager.SIGNATURE_MATCH; 8047 if (!match) { 8048 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8049 == PackageManager.SIGNATURE_MATCH; 8050 } 8051 if (!match) { 8052 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8053 == PackageManager.SIGNATURE_MATCH; 8054 } 8055 if (!match) { 8056 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8057 + pkg.packageName + " signatures do not match the " 8058 + "previously installed version; ignoring!"); 8059 } 8060 } 8061 8062 // Check for shared user signatures 8063 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8064 // Already existing package. Make sure signatures match 8065 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8066 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8067 if (!match) { 8068 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8069 == PackageManager.SIGNATURE_MATCH; 8070 } 8071 if (!match) { 8072 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8073 == PackageManager.SIGNATURE_MATCH; 8074 } 8075 if (!match) { 8076 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8077 "Package " + pkg.packageName 8078 + " has no signatures that match those in shared user " 8079 + pkgSetting.sharedUser.name + "; ignoring!"); 8080 } 8081 } 8082 } 8083 8084 /** 8085 * Enforces that only the system UID or root's UID can call a method exposed 8086 * via Binder. 8087 * 8088 * @param message used as message if SecurityException is thrown 8089 * @throws SecurityException if the caller is not system or root 8090 */ 8091 private static final void enforceSystemOrRoot(String message) { 8092 final int uid = Binder.getCallingUid(); 8093 if (uid != Process.SYSTEM_UID && uid != 0) { 8094 throw new SecurityException(message); 8095 } 8096 } 8097 8098 @Override 8099 public void performFstrimIfNeeded() { 8100 enforceSystemOrRoot("Only the system can request fstrim"); 8101 8102 // Before everything else, see whether we need to fstrim. 8103 try { 8104 IStorageManager sm = PackageHelper.getStorageManager(); 8105 if (sm != null) { 8106 boolean doTrim = false; 8107 final long interval = android.provider.Settings.Global.getLong( 8108 mContext.getContentResolver(), 8109 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8110 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8111 if (interval > 0) { 8112 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8113 if (timeSinceLast > interval) { 8114 doTrim = true; 8115 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8116 + "; running immediately"); 8117 } 8118 } 8119 if (doTrim) { 8120 final boolean dexOptDialogShown; 8121 synchronized (mPackages) { 8122 dexOptDialogShown = mDexOptDialogShown; 8123 } 8124 if (!isFirstBoot() && dexOptDialogShown) { 8125 try { 8126 ActivityManager.getService().showBootMessage( 8127 mContext.getResources().getString( 8128 R.string.android_upgrading_fstrim), true); 8129 } catch (RemoteException e) { 8130 } 8131 } 8132 sm.runMaintenance(); 8133 } 8134 } else { 8135 Slog.e(TAG, "storageManager service unavailable!"); 8136 } 8137 } catch (RemoteException e) { 8138 // Can't happen; StorageManagerService is local 8139 } 8140 } 8141 8142 @Override 8143 public void updatePackagesIfNeeded() { 8144 enforceSystemOrRoot("Only the system can request package update"); 8145 8146 // We need to re-extract after an OTA. 8147 boolean causeUpgrade = isUpgrade(); 8148 8149 // First boot or factory reset. 8150 // Note: we also handle devices that are upgrading to N right now as if it is their 8151 // first boot, as they do not have profile data. 8152 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8153 8154 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8155 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8156 8157 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8158 return; 8159 } 8160 8161 List<PackageParser.Package> pkgs; 8162 synchronized (mPackages) { 8163 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8164 } 8165 8166 final long startTime = System.nanoTime(); 8167 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8168 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8169 8170 final int elapsedTimeSeconds = 8171 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8172 8173 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8174 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8175 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8176 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8177 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8178 } 8179 8180 /** 8181 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8182 * containing statistics about the invocation. The array consists of three elements, 8183 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8184 * and {@code numberOfPackagesFailed}. 8185 */ 8186 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8187 String compilerFilter) { 8188 8189 int numberOfPackagesVisited = 0; 8190 int numberOfPackagesOptimized = 0; 8191 int numberOfPackagesSkipped = 0; 8192 int numberOfPackagesFailed = 0; 8193 final int numberOfPackagesToDexopt = pkgs.size(); 8194 8195 for (PackageParser.Package pkg : pkgs) { 8196 numberOfPackagesVisited++; 8197 8198 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8199 if (DEBUG_DEXOPT) { 8200 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8201 } 8202 numberOfPackagesSkipped++; 8203 continue; 8204 } 8205 8206 if (DEBUG_DEXOPT) { 8207 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8208 numberOfPackagesToDexopt + ": " + pkg.packageName); 8209 } 8210 8211 if (showDialog) { 8212 try { 8213 ActivityManager.getService().showBootMessage( 8214 mContext.getResources().getString(R.string.android_upgrading_apk, 8215 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8216 } catch (RemoteException e) { 8217 } 8218 synchronized (mPackages) { 8219 mDexOptDialogShown = true; 8220 } 8221 } 8222 8223 // If the OTA updates a system app which was previously preopted to a non-preopted state 8224 // the app might end up being verified at runtime. That's because by default the apps 8225 // are verify-profile but for preopted apps there's no profile. 8226 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8227 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8228 // filter (by default interpret-only). 8229 // Note that at this stage unused apps are already filtered. 8230 if (isSystemApp(pkg) && 8231 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8232 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8233 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8234 } 8235 8236 // checkProfiles is false to avoid merging profiles during boot which 8237 // might interfere with background compilation (b/28612421). 8238 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8239 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8240 // trade-off worth doing to save boot time work. 8241 int dexOptStatus = performDexOptTraced(pkg.packageName, 8242 false /* checkProfiles */, 8243 compilerFilter, 8244 false /* force */); 8245 switch (dexOptStatus) { 8246 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8247 numberOfPackagesOptimized++; 8248 break; 8249 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8250 numberOfPackagesSkipped++; 8251 break; 8252 case PackageDexOptimizer.DEX_OPT_FAILED: 8253 numberOfPackagesFailed++; 8254 break; 8255 default: 8256 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8257 break; 8258 } 8259 } 8260 8261 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8262 numberOfPackagesFailed }; 8263 } 8264 8265 @Override 8266 public void notifyPackageUse(String packageName, int reason) { 8267 synchronized (mPackages) { 8268 PackageParser.Package p = mPackages.get(packageName); 8269 if (p == null) { 8270 return; 8271 } 8272 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8273 } 8274 } 8275 8276 @Override 8277 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8278 int userId = UserHandle.getCallingUserId(); 8279 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8280 if (ai == null) { 8281 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8282 + loadingPackageName + ", user=" + userId); 8283 return; 8284 } 8285 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8286 } 8287 8288 // TODO: this is not used nor needed. Delete it. 8289 @Override 8290 public boolean performDexOptIfNeeded(String packageName) { 8291 int dexOptStatus = performDexOptTraced(packageName, 8292 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8293 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8294 } 8295 8296 @Override 8297 public boolean performDexOpt(String packageName, 8298 boolean checkProfiles, int compileReason, boolean force) { 8299 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8300 getCompilerFilterForReason(compileReason), force); 8301 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8302 } 8303 8304 @Override 8305 public boolean performDexOptMode(String packageName, 8306 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8307 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8308 targetCompilerFilter, force); 8309 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8310 } 8311 8312 private int performDexOptTraced(String packageName, 8313 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8314 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8315 try { 8316 return performDexOptInternal(packageName, checkProfiles, 8317 targetCompilerFilter, force); 8318 } finally { 8319 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8320 } 8321 } 8322 8323 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8324 // if the package can now be considered up to date for the given filter. 8325 private int performDexOptInternal(String packageName, 8326 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8327 PackageParser.Package p; 8328 synchronized (mPackages) { 8329 p = mPackages.get(packageName); 8330 if (p == null) { 8331 // Package could not be found. Report failure. 8332 return PackageDexOptimizer.DEX_OPT_FAILED; 8333 } 8334 mPackageUsage.maybeWriteAsync(mPackages); 8335 mCompilerStats.maybeWriteAsync(); 8336 } 8337 long callingId = Binder.clearCallingIdentity(); 8338 try { 8339 synchronized (mInstallLock) { 8340 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8341 targetCompilerFilter, force); 8342 } 8343 } finally { 8344 Binder.restoreCallingIdentity(callingId); 8345 } 8346 } 8347 8348 public ArraySet<String> getOptimizablePackages() { 8349 ArraySet<String> pkgs = new ArraySet<String>(); 8350 synchronized (mPackages) { 8351 for (PackageParser.Package p : mPackages.values()) { 8352 if (PackageDexOptimizer.canOptimizePackage(p)) { 8353 pkgs.add(p.packageName); 8354 } 8355 } 8356 } 8357 return pkgs; 8358 } 8359 8360 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8361 boolean checkProfiles, String targetCompilerFilter, 8362 boolean force) { 8363 // Select the dex optimizer based on the force parameter. 8364 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8365 // allocate an object here. 8366 PackageDexOptimizer pdo = force 8367 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8368 : mPackageDexOptimizer; 8369 8370 // Optimize all dependencies first. Note: we ignore the return value and march on 8371 // on errors. 8372 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8373 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8374 if (!deps.isEmpty()) { 8375 for (PackageParser.Package depPackage : deps) { 8376 // TODO: Analyze and investigate if we (should) profile libraries. 8377 // Currently this will do a full compilation of the library by default. 8378 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8379 false /* checkProfiles */, 8380 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8381 getOrCreateCompilerPackageStats(depPackage)); 8382 } 8383 } 8384 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8385 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8386 } 8387 8388 // Performs dexopt on the used secondary dex files belonging to the given package. 8389 // Returns true if all dex files were process successfully (which could mean either dexopt or 8390 // skip). Returns false if any of the files caused errors. 8391 @Override 8392 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8393 boolean force) { 8394 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8395 } 8396 8397 /** 8398 * Reconcile the information we have about the secondary dex files belonging to 8399 * {@code packagName} and the actual dex files. For all dex files that were 8400 * deleted, update the internal records and delete the generated oat files. 8401 */ 8402 @Override 8403 public void reconcileSecondaryDexFiles(String packageName) { 8404 mDexManager.reconcileSecondaryDexFiles(packageName); 8405 } 8406 8407 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8408 // a reference there. 8409 /*package*/ DexManager getDexManager() { 8410 return mDexManager; 8411 } 8412 8413 /** 8414 * Execute the background dexopt job immediately. 8415 */ 8416 @Override 8417 public boolean runBackgroundDexoptJob() { 8418 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8419 } 8420 8421 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8422 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8423 || p.usesStaticLibraries != null) { 8424 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8425 Set<String> collectedNames = new HashSet<>(); 8426 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8427 8428 retValue.remove(p); 8429 8430 return retValue; 8431 } else { 8432 return Collections.emptyList(); 8433 } 8434 } 8435 8436 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8437 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8438 if (!collectedNames.contains(p.packageName)) { 8439 collectedNames.add(p.packageName); 8440 collected.add(p); 8441 8442 if (p.usesLibraries != null) { 8443 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8444 null, collected, collectedNames); 8445 } 8446 if (p.usesOptionalLibraries != null) { 8447 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8448 null, collected, collectedNames); 8449 } 8450 if (p.usesStaticLibraries != null) { 8451 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8452 p.usesStaticLibrariesVersions, collected, collectedNames); 8453 } 8454 } 8455 } 8456 8457 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8458 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8459 final int libNameCount = libs.size(); 8460 for (int i = 0; i < libNameCount; i++) { 8461 String libName = libs.get(i); 8462 int version = (versions != null && versions.length == libNameCount) 8463 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8464 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8465 if (libPkg != null) { 8466 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8467 } 8468 } 8469 } 8470 8471 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8472 synchronized (mPackages) { 8473 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8474 if (libEntry != null) { 8475 return mPackages.get(libEntry.apk); 8476 } 8477 return null; 8478 } 8479 } 8480 8481 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8482 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8483 if (versionedLib == null) { 8484 return null; 8485 } 8486 return versionedLib.get(version); 8487 } 8488 8489 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8490 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8491 pkg.staticSharedLibName); 8492 if (versionedLib == null) { 8493 return null; 8494 } 8495 int previousLibVersion = -1; 8496 final int versionCount = versionedLib.size(); 8497 for (int i = 0; i < versionCount; i++) { 8498 final int libVersion = versionedLib.keyAt(i); 8499 if (libVersion < pkg.staticSharedLibVersion) { 8500 previousLibVersion = Math.max(previousLibVersion, libVersion); 8501 } 8502 } 8503 if (previousLibVersion >= 0) { 8504 return versionedLib.get(previousLibVersion); 8505 } 8506 return null; 8507 } 8508 8509 public void shutdown() { 8510 mPackageUsage.writeNow(mPackages); 8511 mCompilerStats.writeNow(); 8512 } 8513 8514 @Override 8515 public void dumpProfiles(String packageName) { 8516 PackageParser.Package pkg; 8517 synchronized (mPackages) { 8518 pkg = mPackages.get(packageName); 8519 if (pkg == null) { 8520 throw new IllegalArgumentException("Unknown package: " + packageName); 8521 } 8522 } 8523 /* Only the shell, root, or the app user should be able to dump profiles. */ 8524 int callingUid = Binder.getCallingUid(); 8525 if (callingUid != Process.SHELL_UID && 8526 callingUid != Process.ROOT_UID && 8527 callingUid != pkg.applicationInfo.uid) { 8528 throw new SecurityException("dumpProfiles"); 8529 } 8530 8531 synchronized (mInstallLock) { 8532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8533 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8534 try { 8535 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8536 String codePaths = TextUtils.join(";", allCodePaths); 8537 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8538 } catch (InstallerException e) { 8539 Slog.w(TAG, "Failed to dump profiles", e); 8540 } 8541 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8542 } 8543 } 8544 8545 @Override 8546 public void forceDexOpt(String packageName) { 8547 enforceSystemOrRoot("forceDexOpt"); 8548 8549 PackageParser.Package pkg; 8550 synchronized (mPackages) { 8551 pkg = mPackages.get(packageName); 8552 if (pkg == null) { 8553 throw new IllegalArgumentException("Unknown package: " + packageName); 8554 } 8555 } 8556 8557 synchronized (mInstallLock) { 8558 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8559 8560 // Whoever is calling forceDexOpt wants a fully compiled package. 8561 // Don't use profiles since that may cause compilation to be skipped. 8562 final int res = performDexOptInternalWithDependenciesLI(pkg, 8563 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8564 true /* force */); 8565 8566 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8567 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8568 throw new IllegalStateException("Failed to dexopt: " + res); 8569 } 8570 } 8571 } 8572 8573 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8574 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8575 Slog.w(TAG, "Unable to update from " + oldPkg.name 8576 + " to " + newPkg.packageName 8577 + ": old package not in system partition"); 8578 return false; 8579 } else if (mPackages.get(oldPkg.name) != null) { 8580 Slog.w(TAG, "Unable to update from " + oldPkg.name 8581 + " to " + newPkg.packageName 8582 + ": old package still exists"); 8583 return false; 8584 } 8585 return true; 8586 } 8587 8588 void removeCodePathLI(File codePath) { 8589 if (codePath.isDirectory()) { 8590 try { 8591 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8592 } catch (InstallerException e) { 8593 Slog.w(TAG, "Failed to remove code path", e); 8594 } 8595 } else { 8596 codePath.delete(); 8597 } 8598 } 8599 8600 private int[] resolveUserIds(int userId) { 8601 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8602 } 8603 8604 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8605 if (pkg == null) { 8606 Slog.wtf(TAG, "Package was null!", new Throwable()); 8607 return; 8608 } 8609 clearAppDataLeafLIF(pkg, userId, flags); 8610 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8611 for (int i = 0; i < childCount; i++) { 8612 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8613 } 8614 } 8615 8616 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8617 final PackageSetting ps; 8618 synchronized (mPackages) { 8619 ps = mSettings.mPackages.get(pkg.packageName); 8620 } 8621 for (int realUserId : resolveUserIds(userId)) { 8622 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8623 try { 8624 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8625 ceDataInode); 8626 } catch (InstallerException e) { 8627 Slog.w(TAG, String.valueOf(e)); 8628 } 8629 } 8630 } 8631 8632 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8633 if (pkg == null) { 8634 Slog.wtf(TAG, "Package was null!", new Throwable()); 8635 return; 8636 } 8637 destroyAppDataLeafLIF(pkg, userId, flags); 8638 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8639 for (int i = 0; i < childCount; i++) { 8640 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8641 } 8642 } 8643 8644 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8645 final PackageSetting ps; 8646 synchronized (mPackages) { 8647 ps = mSettings.mPackages.get(pkg.packageName); 8648 } 8649 for (int realUserId : resolveUserIds(userId)) { 8650 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8651 try { 8652 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8653 ceDataInode); 8654 } catch (InstallerException e) { 8655 Slog.w(TAG, String.valueOf(e)); 8656 } 8657 } 8658 } 8659 8660 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8661 if (pkg == null) { 8662 Slog.wtf(TAG, "Package was null!", new Throwable()); 8663 return; 8664 } 8665 destroyAppProfilesLeafLIF(pkg); 8666 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8667 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8668 for (int i = 0; i < childCount; i++) { 8669 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8670 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8671 true /* removeBaseMarker */); 8672 } 8673 } 8674 8675 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8676 boolean removeBaseMarker) { 8677 if (pkg.isForwardLocked()) { 8678 return; 8679 } 8680 8681 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8682 try { 8683 path = PackageManagerServiceUtils.realpath(new File(path)); 8684 } catch (IOException e) { 8685 // TODO: Should we return early here ? 8686 Slog.w(TAG, "Failed to get canonical path", e); 8687 continue; 8688 } 8689 8690 final String useMarker = path.replace('/', '@'); 8691 for (int realUserId : resolveUserIds(userId)) { 8692 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8693 if (removeBaseMarker) { 8694 File foreignUseMark = new File(profileDir, useMarker); 8695 if (foreignUseMark.exists()) { 8696 if (!foreignUseMark.delete()) { 8697 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8698 + pkg.packageName); 8699 } 8700 } 8701 } 8702 8703 File[] markers = profileDir.listFiles(); 8704 if (markers != null) { 8705 final String searchString = "@" + pkg.packageName + "@"; 8706 // We also delete all markers that contain the package name we're 8707 // uninstalling. These are associated with secondary dex-files belonging 8708 // to the package. Reconstructing the path of these dex files is messy 8709 // in general. 8710 for (File marker : markers) { 8711 if (marker.getName().indexOf(searchString) > 0) { 8712 if (!marker.delete()) { 8713 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8714 + pkg.packageName); 8715 } 8716 } 8717 } 8718 } 8719 } 8720 } 8721 } 8722 8723 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8724 try { 8725 mInstaller.destroyAppProfiles(pkg.packageName); 8726 } catch (InstallerException e) { 8727 Slog.w(TAG, String.valueOf(e)); 8728 } 8729 } 8730 8731 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8732 if (pkg == null) { 8733 Slog.wtf(TAG, "Package was null!", new Throwable()); 8734 return; 8735 } 8736 clearAppProfilesLeafLIF(pkg); 8737 // We don't remove the base foreign use marker when clearing profiles because 8738 // we will rename it when the app is updated. Unlike the actual profile contents, 8739 // the foreign use marker is good across installs. 8740 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8741 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8742 for (int i = 0; i < childCount; i++) { 8743 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8744 } 8745 } 8746 8747 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8748 try { 8749 mInstaller.clearAppProfiles(pkg.packageName); 8750 } catch (InstallerException e) { 8751 Slog.w(TAG, String.valueOf(e)); 8752 } 8753 } 8754 8755 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8756 long lastUpdateTime) { 8757 // Set parent install/update time 8758 PackageSetting ps = (PackageSetting) pkg.mExtras; 8759 if (ps != null) { 8760 ps.firstInstallTime = firstInstallTime; 8761 ps.lastUpdateTime = lastUpdateTime; 8762 } 8763 // Set children install/update time 8764 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8765 for (int i = 0; i < childCount; i++) { 8766 PackageParser.Package childPkg = pkg.childPackages.get(i); 8767 ps = (PackageSetting) childPkg.mExtras; 8768 if (ps != null) { 8769 ps.firstInstallTime = firstInstallTime; 8770 ps.lastUpdateTime = lastUpdateTime; 8771 } 8772 } 8773 } 8774 8775 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8776 PackageParser.Package changingLib) { 8777 if (file.path != null) { 8778 usesLibraryFiles.add(file.path); 8779 return; 8780 } 8781 PackageParser.Package p = mPackages.get(file.apk); 8782 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8783 // If we are doing this while in the middle of updating a library apk, 8784 // then we need to make sure to use that new apk for determining the 8785 // dependencies here. (We haven't yet finished committing the new apk 8786 // to the package manager state.) 8787 if (p == null || p.packageName.equals(changingLib.packageName)) { 8788 p = changingLib; 8789 } 8790 } 8791 if (p != null) { 8792 usesLibraryFiles.addAll(p.getAllCodePaths()); 8793 } 8794 } 8795 8796 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8797 PackageParser.Package changingLib) throws PackageManagerException { 8798 if (pkg == null) { 8799 return; 8800 } 8801 ArraySet<String> usesLibraryFiles = null; 8802 if (pkg.usesLibraries != null) { 8803 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8804 null, null, pkg.packageName, changingLib, true, null); 8805 } 8806 if (pkg.usesStaticLibraries != null) { 8807 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8808 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8809 pkg.packageName, changingLib, true, usesLibraryFiles); 8810 } 8811 if (pkg.usesOptionalLibraries != null) { 8812 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8813 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8814 } 8815 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8816 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8817 } else { 8818 pkg.usesLibraryFiles = null; 8819 } 8820 } 8821 8822 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8823 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8824 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8825 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8826 throws PackageManagerException { 8827 final int libCount = requestedLibraries.size(); 8828 for (int i = 0; i < libCount; i++) { 8829 final String libName = requestedLibraries.get(i); 8830 final int libVersion = requiredVersions != null ? requiredVersions[i] 8831 : SharedLibraryInfo.VERSION_UNDEFINED; 8832 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8833 if (libEntry == null) { 8834 if (required) { 8835 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8836 "Package " + packageName + " requires unavailable shared library " 8837 + libName + "; failing!"); 8838 } else { 8839 Slog.w(TAG, "Package " + packageName 8840 + " desires unavailable shared library " 8841 + libName + "; ignoring!"); 8842 } 8843 } else { 8844 if (requiredVersions != null && requiredCertDigests != null) { 8845 if (libEntry.info.getVersion() != requiredVersions[i]) { 8846 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8847 "Package " + packageName + " requires unavailable static shared" 8848 + " library " + libName + " version " 8849 + libEntry.info.getVersion() + "; failing!"); 8850 } 8851 8852 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8853 if (libPkg == null) { 8854 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8855 "Package " + packageName + " requires unavailable static shared" 8856 + " library; failing!"); 8857 } 8858 8859 String expectedCertDigest = requiredCertDigests[i]; 8860 String libCertDigest = PackageUtils.computeCertSha256Digest( 8861 libPkg.mSignatures[0]); 8862 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8863 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8864 "Package " + packageName + " requires differently signed" + 8865 " static shared library; failing!"); 8866 } 8867 } 8868 8869 if (outUsedLibraries == null) { 8870 outUsedLibraries = new ArraySet<>(); 8871 } 8872 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8873 } 8874 } 8875 return outUsedLibraries; 8876 } 8877 8878 private static boolean hasString(List<String> list, List<String> which) { 8879 if (list == null) { 8880 return false; 8881 } 8882 for (int i=list.size()-1; i>=0; i--) { 8883 for (int j=which.size()-1; j>=0; j--) { 8884 if (which.get(j).equals(list.get(i))) { 8885 return true; 8886 } 8887 } 8888 } 8889 return false; 8890 } 8891 8892 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8893 PackageParser.Package changingPkg) { 8894 ArrayList<PackageParser.Package> res = null; 8895 for (PackageParser.Package pkg : mPackages.values()) { 8896 if (changingPkg != null 8897 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8898 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8899 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8900 changingPkg.staticSharedLibName)) { 8901 return null; 8902 } 8903 if (res == null) { 8904 res = new ArrayList<>(); 8905 } 8906 res.add(pkg); 8907 try { 8908 updateSharedLibrariesLPr(pkg, changingPkg); 8909 } catch (PackageManagerException e) { 8910 // If a system app update or an app and a required lib missing we 8911 // delete the package and for updated system apps keep the data as 8912 // it is better for the user to reinstall than to be in an limbo 8913 // state. Also libs disappearing under an app should never happen 8914 // - just in case. 8915 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8916 final int flags = pkg.isUpdatedSystemApp() 8917 ? PackageManager.DELETE_KEEP_DATA : 0; 8918 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8919 flags , null, true, null); 8920 } 8921 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8922 } 8923 } 8924 return res; 8925 } 8926 8927 /** 8928 * Derive the value of the {@code cpuAbiOverride} based on the provided 8929 * value and an optional stored value from the package settings. 8930 */ 8931 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8932 String cpuAbiOverride = null; 8933 8934 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8935 cpuAbiOverride = null; 8936 } else if (abiOverride != null) { 8937 cpuAbiOverride = abiOverride; 8938 } else if (settings != null) { 8939 cpuAbiOverride = settings.cpuAbiOverrideString; 8940 } 8941 8942 return cpuAbiOverride; 8943 } 8944 8945 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8946 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8947 throws PackageManagerException { 8948 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8949 // If the package has children and this is the first dive in the function 8950 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8951 // whether all packages (parent and children) would be successfully scanned 8952 // before the actual scan since scanning mutates internal state and we want 8953 // to atomically install the package and its children. 8954 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8955 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8956 scanFlags |= SCAN_CHECK_ONLY; 8957 } 8958 } else { 8959 scanFlags &= ~SCAN_CHECK_ONLY; 8960 } 8961 8962 final PackageParser.Package scannedPkg; 8963 try { 8964 // Scan the parent 8965 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8966 // Scan the children 8967 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8968 for (int i = 0; i < childCount; i++) { 8969 PackageParser.Package childPkg = pkg.childPackages.get(i); 8970 scanPackageLI(childPkg, policyFlags, 8971 scanFlags, currentTime, user); 8972 } 8973 } finally { 8974 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8975 } 8976 8977 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8978 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8979 } 8980 8981 return scannedPkg; 8982 } 8983 8984 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8985 int scanFlags, long currentTime, @Nullable UserHandle user) 8986 throws PackageManagerException { 8987 boolean success = false; 8988 try { 8989 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8990 currentTime, user); 8991 success = true; 8992 return res; 8993 } finally { 8994 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8995 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8996 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8997 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8998 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8999 } 9000 } 9001 } 9002 9003 /** 9004 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9005 */ 9006 private static boolean apkHasCode(String fileName) { 9007 StrictJarFile jarFile = null; 9008 try { 9009 jarFile = new StrictJarFile(fileName, 9010 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9011 return jarFile.findEntry("classes.dex") != null; 9012 } catch (IOException ignore) { 9013 } finally { 9014 try { 9015 if (jarFile != null) { 9016 jarFile.close(); 9017 } 9018 } catch (IOException ignore) {} 9019 } 9020 return false; 9021 } 9022 9023 /** 9024 * Enforces code policy for the package. This ensures that if an APK has 9025 * declared hasCode="true" in its manifest that the APK actually contains 9026 * code. 9027 * 9028 * @throws PackageManagerException If bytecode could not be found when it should exist 9029 */ 9030 private static void assertCodePolicy(PackageParser.Package pkg) 9031 throws PackageManagerException { 9032 final boolean shouldHaveCode = 9033 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9034 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9035 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9036 "Package " + pkg.baseCodePath + " code is missing"); 9037 } 9038 9039 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9040 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9041 final boolean splitShouldHaveCode = 9042 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9043 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9044 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9045 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9046 } 9047 } 9048 } 9049 } 9050 9051 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9052 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9053 throws PackageManagerException { 9054 if (DEBUG_PACKAGE_SCANNING) { 9055 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9056 Log.d(TAG, "Scanning package " + pkg.packageName); 9057 } 9058 9059 applyPolicy(pkg, policyFlags); 9060 9061 assertPackageIsValid(pkg, policyFlags, scanFlags); 9062 9063 // Initialize package source and resource directories 9064 final File scanFile = new File(pkg.codePath); 9065 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9066 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9067 9068 SharedUserSetting suid = null; 9069 PackageSetting pkgSetting = null; 9070 9071 // Getting the package setting may have a side-effect, so if we 9072 // are only checking if scan would succeed, stash a copy of the 9073 // old setting to restore at the end. 9074 PackageSetting nonMutatedPs = null; 9075 9076 // We keep references to the derived CPU Abis from settings in oder to reuse 9077 // them in the case where we're not upgrading or booting for the first time. 9078 String primaryCpuAbiFromSettings = null; 9079 String secondaryCpuAbiFromSettings = null; 9080 9081 // writer 9082 synchronized (mPackages) { 9083 if (pkg.mSharedUserId != null) { 9084 // SIDE EFFECTS; may potentially allocate a new shared user 9085 suid = mSettings.getSharedUserLPw( 9086 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9087 if (DEBUG_PACKAGE_SCANNING) { 9088 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9089 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9090 + "): packages=" + suid.packages); 9091 } 9092 } 9093 9094 // Check if we are renaming from an original package name. 9095 PackageSetting origPackage = null; 9096 String realName = null; 9097 if (pkg.mOriginalPackages != null) { 9098 // This package may need to be renamed to a previously 9099 // installed name. Let's check on that... 9100 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9101 if (pkg.mOriginalPackages.contains(renamed)) { 9102 // This package had originally been installed as the 9103 // original name, and we have already taken care of 9104 // transitioning to the new one. Just update the new 9105 // one to continue using the old name. 9106 realName = pkg.mRealPackage; 9107 if (!pkg.packageName.equals(renamed)) { 9108 // Callers into this function may have already taken 9109 // care of renaming the package; only do it here if 9110 // it is not already done. 9111 pkg.setPackageName(renamed); 9112 } 9113 } else { 9114 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9115 if ((origPackage = mSettings.getPackageLPr( 9116 pkg.mOriginalPackages.get(i))) != null) { 9117 // We do have the package already installed under its 9118 // original name... should we use it? 9119 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9120 // New package is not compatible with original. 9121 origPackage = null; 9122 continue; 9123 } else if (origPackage.sharedUser != null) { 9124 // Make sure uid is compatible between packages. 9125 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9126 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9127 + " to " + pkg.packageName + ": old uid " 9128 + origPackage.sharedUser.name 9129 + " differs from " + pkg.mSharedUserId); 9130 origPackage = null; 9131 continue; 9132 } 9133 // TODO: Add case when shared user id is added [b/28144775] 9134 } else { 9135 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9136 + pkg.packageName + " to old name " + origPackage.name); 9137 } 9138 break; 9139 } 9140 } 9141 } 9142 } 9143 9144 if (mTransferedPackages.contains(pkg.packageName)) { 9145 Slog.w(TAG, "Package " + pkg.packageName 9146 + " was transferred to another, but its .apk remains"); 9147 } 9148 9149 // See comments in nonMutatedPs declaration 9150 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9151 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9152 if (foundPs != null) { 9153 nonMutatedPs = new PackageSetting(foundPs); 9154 } 9155 } 9156 9157 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9158 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9159 if (foundPs != null) { 9160 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9161 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9162 } 9163 } 9164 9165 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9166 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9167 PackageManagerService.reportSettingsProblem(Log.WARN, 9168 "Package " + pkg.packageName + " shared user changed from " 9169 + (pkgSetting.sharedUser != null 9170 ? pkgSetting.sharedUser.name : "<nothing>") 9171 + " to " 9172 + (suid != null ? suid.name : "<nothing>") 9173 + "; replacing with new"); 9174 pkgSetting = null; 9175 } 9176 final PackageSetting oldPkgSetting = 9177 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9178 final PackageSetting disabledPkgSetting = 9179 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9180 9181 String[] usesStaticLibraries = null; 9182 if (pkg.usesStaticLibraries != null) { 9183 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9184 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9185 } 9186 9187 if (pkgSetting == null) { 9188 final String parentPackageName = (pkg.parentPackage != null) 9189 ? pkg.parentPackage.packageName : null; 9190 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9191 // REMOVE SharedUserSetting from method; update in a separate call 9192 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9193 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9194 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9195 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9196 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9197 true /*allowInstall*/, instantApp, parentPackageName, 9198 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9199 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9200 // SIDE EFFECTS; updates system state; move elsewhere 9201 if (origPackage != null) { 9202 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9203 } 9204 mSettings.addUserToSettingLPw(pkgSetting); 9205 } else { 9206 // REMOVE SharedUserSetting from method; update in a separate call. 9207 // 9208 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9209 // secondaryCpuAbi are not known at this point so we always update them 9210 // to null here, only to reset them at a later point. 9211 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9212 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9213 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9214 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9215 UserManagerService.getInstance(), usesStaticLibraries, 9216 pkg.usesStaticLibrariesVersions); 9217 } 9218 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9219 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9220 9221 // SIDE EFFECTS; modifies system state; move elsewhere 9222 if (pkgSetting.origPackage != null) { 9223 // If we are first transitioning from an original package, 9224 // fix up the new package's name now. We need to do this after 9225 // looking up the package under its new name, so getPackageLP 9226 // can take care of fiddling things correctly. 9227 pkg.setPackageName(origPackage.name); 9228 9229 // File a report about this. 9230 String msg = "New package " + pkgSetting.realName 9231 + " renamed to replace old package " + pkgSetting.name; 9232 reportSettingsProblem(Log.WARN, msg); 9233 9234 // Make a note of it. 9235 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9236 mTransferedPackages.add(origPackage.name); 9237 } 9238 9239 // No longer need to retain this. 9240 pkgSetting.origPackage = null; 9241 } 9242 9243 // SIDE EFFECTS; modifies system state; move elsewhere 9244 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9245 // Make a note of it. 9246 mTransferedPackages.add(pkg.packageName); 9247 } 9248 9249 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9250 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9251 } 9252 9253 if ((scanFlags & SCAN_BOOTING) == 0 9254 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9255 // Check all shared libraries and map to their actual file path. 9256 // We only do this here for apps not on a system dir, because those 9257 // are the only ones that can fail an install due to this. We 9258 // will take care of the system apps by updating all of their 9259 // library paths after the scan is done. Also during the initial 9260 // scan don't update any libs as we do this wholesale after all 9261 // apps are scanned to avoid dependency based scanning. 9262 updateSharedLibrariesLPr(pkg, null); 9263 } 9264 9265 if (mFoundPolicyFile) { 9266 SELinuxMMAC.assignSeInfoValue(pkg); 9267 } 9268 pkg.applicationInfo.uid = pkgSetting.appId; 9269 pkg.mExtras = pkgSetting; 9270 9271 9272 // Static shared libs have same package with different versions where 9273 // we internally use a synthetic package name to allow multiple versions 9274 // of the same package, therefore we need to compare signatures against 9275 // the package setting for the latest library version. 9276 PackageSetting signatureCheckPs = pkgSetting; 9277 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9278 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9279 if (libraryEntry != null) { 9280 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9281 } 9282 } 9283 9284 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9285 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9286 // We just determined the app is signed correctly, so bring 9287 // over the latest parsed certs. 9288 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9289 } else { 9290 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9291 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9292 "Package " + pkg.packageName + " upgrade keys do not match the " 9293 + "previously installed version"); 9294 } else { 9295 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9296 String msg = "System package " + pkg.packageName 9297 + " signature changed; retaining data."; 9298 reportSettingsProblem(Log.WARN, msg); 9299 } 9300 } 9301 } else { 9302 try { 9303 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9304 verifySignaturesLP(signatureCheckPs, pkg); 9305 // We just determined the app is signed correctly, so bring 9306 // over the latest parsed certs. 9307 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9308 } catch (PackageManagerException e) { 9309 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9310 throw e; 9311 } 9312 // The signature has changed, but this package is in the system 9313 // image... let's recover! 9314 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9315 // However... if this package is part of a shared user, but it 9316 // doesn't match the signature of the shared user, let's fail. 9317 // What this means is that you can't change the signatures 9318 // associated with an overall shared user, which doesn't seem all 9319 // that unreasonable. 9320 if (signatureCheckPs.sharedUser != null) { 9321 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9322 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9323 throw new PackageManagerException( 9324 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9325 "Signature mismatch for shared user: " 9326 + pkgSetting.sharedUser); 9327 } 9328 } 9329 // File a report about this. 9330 String msg = "System package " + pkg.packageName 9331 + " signature changed; retaining data."; 9332 reportSettingsProblem(Log.WARN, msg); 9333 } 9334 } 9335 9336 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9337 // This package wants to adopt ownership of permissions from 9338 // another package. 9339 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9340 final String origName = pkg.mAdoptPermissions.get(i); 9341 final PackageSetting orig = mSettings.getPackageLPr(origName); 9342 if (orig != null) { 9343 if (verifyPackageUpdateLPr(orig, pkg)) { 9344 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9345 + pkg.packageName); 9346 // SIDE EFFECTS; updates permissions system state; move elsewhere 9347 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9348 } 9349 } 9350 } 9351 } 9352 } 9353 9354 pkg.applicationInfo.processName = fixProcessName( 9355 pkg.applicationInfo.packageName, 9356 pkg.applicationInfo.processName); 9357 9358 if (pkg != mPlatformPackage) { 9359 // Get all of our default paths setup 9360 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9361 } 9362 9363 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9364 9365 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9366 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9367 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9368 derivePackageAbi( 9369 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9370 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9371 9372 // Some system apps still use directory structure for native libraries 9373 // in which case we might end up not detecting abi solely based on apk 9374 // structure. Try to detect abi based on directory structure. 9375 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9376 pkg.applicationInfo.primaryCpuAbi == null) { 9377 setBundledAppAbisAndRoots(pkg, pkgSetting); 9378 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9379 } 9380 } else { 9381 // This is not a first boot or an upgrade, don't bother deriving the 9382 // ABI during the scan. Instead, trust the value that was stored in the 9383 // package setting. 9384 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9385 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9386 9387 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9388 9389 if (DEBUG_ABI_SELECTION) { 9390 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9391 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9392 pkg.applicationInfo.secondaryCpuAbi); 9393 } 9394 } 9395 } else { 9396 if ((scanFlags & SCAN_MOVE) != 0) { 9397 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9398 // but we already have this packages package info in the PackageSetting. We just 9399 // use that and derive the native library path based on the new codepath. 9400 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9401 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9402 } 9403 9404 // Set native library paths again. For moves, the path will be updated based on the 9405 // ABIs we've determined above. For non-moves, the path will be updated based on the 9406 // ABIs we determined during compilation, but the path will depend on the final 9407 // package path (after the rename away from the stage path). 9408 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9409 } 9410 9411 // This is a special case for the "system" package, where the ABI is 9412 // dictated by the zygote configuration (and init.rc). We should keep track 9413 // of this ABI so that we can deal with "normal" applications that run under 9414 // the same UID correctly. 9415 if (mPlatformPackage == pkg) { 9416 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9417 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9418 } 9419 9420 // If there's a mismatch between the abi-override in the package setting 9421 // and the abiOverride specified for the install. Warn about this because we 9422 // would've already compiled the app without taking the package setting into 9423 // account. 9424 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9425 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9426 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9427 " for package " + pkg.packageName); 9428 } 9429 } 9430 9431 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9432 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9433 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9434 9435 // Copy the derived override back to the parsed package, so that we can 9436 // update the package settings accordingly. 9437 pkg.cpuAbiOverride = cpuAbiOverride; 9438 9439 if (DEBUG_ABI_SELECTION) { 9440 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9441 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9442 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9443 } 9444 9445 // Push the derived path down into PackageSettings so we know what to 9446 // clean up at uninstall time. 9447 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9448 9449 if (DEBUG_ABI_SELECTION) { 9450 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9451 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9452 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9453 } 9454 9455 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9456 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9457 // We don't do this here during boot because we can do it all 9458 // at once after scanning all existing packages. 9459 // 9460 // We also do this *before* we perform dexopt on this package, so that 9461 // we can avoid redundant dexopts, and also to make sure we've got the 9462 // code and package path correct. 9463 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9464 } 9465 9466 if (mFactoryTest && pkg.requestedPermissions.contains( 9467 android.Manifest.permission.FACTORY_TEST)) { 9468 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9469 } 9470 9471 if (isSystemApp(pkg)) { 9472 pkgSetting.isOrphaned = true; 9473 } 9474 9475 // Take care of first install / last update times. 9476 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9477 if (currentTime != 0) { 9478 if (pkgSetting.firstInstallTime == 0) { 9479 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9480 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9481 pkgSetting.lastUpdateTime = currentTime; 9482 } 9483 } else if (pkgSetting.firstInstallTime == 0) { 9484 // We need *something*. Take time time stamp of the file. 9485 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9486 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9487 if (scanFileTime != pkgSetting.timeStamp) { 9488 // A package on the system image has changed; consider this 9489 // to be an update. 9490 pkgSetting.lastUpdateTime = scanFileTime; 9491 } 9492 } 9493 pkgSetting.setTimeStamp(scanFileTime); 9494 9495 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9496 if (nonMutatedPs != null) { 9497 synchronized (mPackages) { 9498 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9499 } 9500 } 9501 } else { 9502 final int userId = user == null ? 0 : user.getIdentifier(); 9503 // Modify state for the given package setting 9504 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9505 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9506 if (pkgSetting.getInstantApp(userId)) { 9507 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9508 } 9509 } 9510 return pkg; 9511 } 9512 9513 /** 9514 * Applies policy to the parsed package based upon the given policy flags. 9515 * Ensures the package is in a good state. 9516 * <p> 9517 * Implementation detail: This method must NOT have any side effect. It would 9518 * ideally be static, but, it requires locks to read system state. 9519 */ 9520 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9521 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9522 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9523 if (pkg.applicationInfo.isDirectBootAware()) { 9524 // we're direct boot aware; set for all components 9525 for (PackageParser.Service s : pkg.services) { 9526 s.info.encryptionAware = s.info.directBootAware = true; 9527 } 9528 for (PackageParser.Provider p : pkg.providers) { 9529 p.info.encryptionAware = p.info.directBootAware = true; 9530 } 9531 for (PackageParser.Activity a : pkg.activities) { 9532 a.info.encryptionAware = a.info.directBootAware = true; 9533 } 9534 for (PackageParser.Activity r : pkg.receivers) { 9535 r.info.encryptionAware = r.info.directBootAware = true; 9536 } 9537 } 9538 } else { 9539 // Only allow system apps to be flagged as core apps. 9540 pkg.coreApp = false; 9541 // clear flags not applicable to regular apps 9542 pkg.applicationInfo.privateFlags &= 9543 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9544 pkg.applicationInfo.privateFlags &= 9545 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9546 } 9547 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9548 9549 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9550 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9551 } 9552 9553 if (!isSystemApp(pkg)) { 9554 // Only system apps can use these features. 9555 pkg.mOriginalPackages = null; 9556 pkg.mRealPackage = null; 9557 pkg.mAdoptPermissions = null; 9558 } 9559 } 9560 9561 /** 9562 * Asserts the parsed package is valid according to the given policy. If the 9563 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9564 * <p> 9565 * Implementation detail: This method must NOT have any side effects. It would 9566 * ideally be static, but, it requires locks to read system state. 9567 * 9568 * @throws PackageManagerException If the package fails any of the validation checks 9569 */ 9570 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9571 throws PackageManagerException { 9572 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9573 assertCodePolicy(pkg); 9574 } 9575 9576 if (pkg.applicationInfo.getCodePath() == null || 9577 pkg.applicationInfo.getResourcePath() == null) { 9578 // Bail out. The resource and code paths haven't been set. 9579 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9580 "Code and resource paths haven't been set correctly"); 9581 } 9582 9583 // Make sure we're not adding any bogus keyset info 9584 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9585 ksms.assertScannedPackageValid(pkg); 9586 9587 synchronized (mPackages) { 9588 // The special "android" package can only be defined once 9589 if (pkg.packageName.equals("android")) { 9590 if (mAndroidApplication != null) { 9591 Slog.w(TAG, "*************************************************"); 9592 Slog.w(TAG, "Core android package being redefined. Skipping."); 9593 Slog.w(TAG, " codePath=" + pkg.codePath); 9594 Slog.w(TAG, "*************************************************"); 9595 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9596 "Core android package being redefined. Skipping."); 9597 } 9598 } 9599 9600 // A package name must be unique; don't allow duplicates 9601 if (mPackages.containsKey(pkg.packageName)) { 9602 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9603 "Application package " + pkg.packageName 9604 + " already installed. Skipping duplicate."); 9605 } 9606 9607 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9608 // Static libs have a synthetic package name containing the version 9609 // but we still want the base name to be unique. 9610 if (mPackages.containsKey(pkg.manifestPackageName)) { 9611 throw new PackageManagerException( 9612 "Duplicate static shared lib provider package"); 9613 } 9614 9615 // Static shared libraries should have at least O target SDK 9616 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9617 throw new PackageManagerException( 9618 "Packages declaring static-shared libs must target O SDK or higher"); 9619 } 9620 9621 // Package declaring static a shared lib cannot be instant apps 9622 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9623 throw new PackageManagerException( 9624 "Packages declaring static-shared libs cannot be instant apps"); 9625 } 9626 9627 // Package declaring static a shared lib cannot be renamed since the package 9628 // name is synthetic and apps can't code around package manager internals. 9629 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9630 throw new PackageManagerException( 9631 "Packages declaring static-shared libs cannot be renamed"); 9632 } 9633 9634 // Package declaring static a shared lib cannot declare child packages 9635 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9636 throw new PackageManagerException( 9637 "Packages declaring static-shared libs cannot have child packages"); 9638 } 9639 9640 // Package declaring static a shared lib cannot declare dynamic libs 9641 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9642 throw new PackageManagerException( 9643 "Packages declaring static-shared libs cannot declare dynamic libs"); 9644 } 9645 9646 // Package declaring static a shared lib cannot declare shared users 9647 if (pkg.mSharedUserId != null) { 9648 throw new PackageManagerException( 9649 "Packages declaring static-shared libs cannot declare shared users"); 9650 } 9651 9652 // Static shared libs cannot declare activities 9653 if (!pkg.activities.isEmpty()) { 9654 throw new PackageManagerException( 9655 "Static shared libs cannot declare activities"); 9656 } 9657 9658 // Static shared libs cannot declare services 9659 if (!pkg.services.isEmpty()) { 9660 throw new PackageManagerException( 9661 "Static shared libs cannot declare services"); 9662 } 9663 9664 // Static shared libs cannot declare providers 9665 if (!pkg.providers.isEmpty()) { 9666 throw new PackageManagerException( 9667 "Static shared libs cannot declare content providers"); 9668 } 9669 9670 // Static shared libs cannot declare receivers 9671 if (!pkg.receivers.isEmpty()) { 9672 throw new PackageManagerException( 9673 "Static shared libs cannot declare broadcast receivers"); 9674 } 9675 9676 // Static shared libs cannot declare permission groups 9677 if (!pkg.permissionGroups.isEmpty()) { 9678 throw new PackageManagerException( 9679 "Static shared libs cannot declare permission groups"); 9680 } 9681 9682 // Static shared libs cannot declare permissions 9683 if (!pkg.permissions.isEmpty()) { 9684 throw new PackageManagerException( 9685 "Static shared libs cannot declare permissions"); 9686 } 9687 9688 // Static shared libs cannot declare protected broadcasts 9689 if (pkg.protectedBroadcasts != null) { 9690 throw new PackageManagerException( 9691 "Static shared libs cannot declare protected broadcasts"); 9692 } 9693 9694 // Static shared libs cannot be overlay targets 9695 if (pkg.mOverlayTarget != null) { 9696 throw new PackageManagerException( 9697 "Static shared libs cannot be overlay targets"); 9698 } 9699 9700 // The version codes must be ordered as lib versions 9701 int minVersionCode = Integer.MIN_VALUE; 9702 int maxVersionCode = Integer.MAX_VALUE; 9703 9704 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9705 pkg.staticSharedLibName); 9706 if (versionedLib != null) { 9707 final int versionCount = versionedLib.size(); 9708 for (int i = 0; i < versionCount; i++) { 9709 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9710 // TODO: We will change version code to long, so in the new API it is long 9711 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9712 .getVersionCode(); 9713 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9714 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9715 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9716 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9717 } else { 9718 minVersionCode = maxVersionCode = libVersionCode; 9719 break; 9720 } 9721 } 9722 } 9723 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9724 throw new PackageManagerException("Static shared" 9725 + " lib version codes must be ordered as lib versions"); 9726 } 9727 } 9728 9729 // Only privileged apps and updated privileged apps can add child packages. 9730 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9731 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9732 throw new PackageManagerException("Only privileged apps can add child " 9733 + "packages. Ignoring package " + pkg.packageName); 9734 } 9735 final int childCount = pkg.childPackages.size(); 9736 for (int i = 0; i < childCount; i++) { 9737 PackageParser.Package childPkg = pkg.childPackages.get(i); 9738 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9739 childPkg.packageName)) { 9740 throw new PackageManagerException("Can't override child of " 9741 + "another disabled app. Ignoring package " + pkg.packageName); 9742 } 9743 } 9744 } 9745 9746 // If we're only installing presumed-existing packages, require that the 9747 // scanned APK is both already known and at the path previously established 9748 // for it. Previously unknown packages we pick up normally, but if we have an 9749 // a priori expectation about this package's install presence, enforce it. 9750 // With a singular exception for new system packages. When an OTA contains 9751 // a new system package, we allow the codepath to change from a system location 9752 // to the user-installed location. If we don't allow this change, any newer, 9753 // user-installed version of the application will be ignored. 9754 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9755 if (mExpectingBetter.containsKey(pkg.packageName)) { 9756 logCriticalInfo(Log.WARN, 9757 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9758 } else { 9759 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9760 if (known != null) { 9761 if (DEBUG_PACKAGE_SCANNING) { 9762 Log.d(TAG, "Examining " + pkg.codePath 9763 + " and requiring known paths " + known.codePathString 9764 + " & " + known.resourcePathString); 9765 } 9766 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9767 || !pkg.applicationInfo.getResourcePath().equals( 9768 known.resourcePathString)) { 9769 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9770 "Application package " + pkg.packageName 9771 + " found at " + pkg.applicationInfo.getCodePath() 9772 + " but expected at " + known.codePathString 9773 + "; ignoring."); 9774 } 9775 } 9776 } 9777 } 9778 9779 // Verify that this new package doesn't have any content providers 9780 // that conflict with existing packages. Only do this if the 9781 // package isn't already installed, since we don't want to break 9782 // things that are installed. 9783 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9784 final int N = pkg.providers.size(); 9785 int i; 9786 for (i=0; i<N; i++) { 9787 PackageParser.Provider p = pkg.providers.get(i); 9788 if (p.info.authority != null) { 9789 String names[] = p.info.authority.split(";"); 9790 for (int j = 0; j < names.length; j++) { 9791 if (mProvidersByAuthority.containsKey(names[j])) { 9792 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9793 final String otherPackageName = 9794 ((other != null && other.getComponentName() != null) ? 9795 other.getComponentName().getPackageName() : "?"); 9796 throw new PackageManagerException( 9797 INSTALL_FAILED_CONFLICTING_PROVIDER, 9798 "Can't install because provider name " + names[j] 9799 + " (in package " + pkg.applicationInfo.packageName 9800 + ") is already used by " + otherPackageName); 9801 } 9802 } 9803 } 9804 } 9805 } 9806 } 9807 } 9808 9809 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9810 int type, String declaringPackageName, int declaringVersionCode) { 9811 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9812 if (versionedLib == null) { 9813 versionedLib = new SparseArray<>(); 9814 mSharedLibraries.put(name, versionedLib); 9815 if (type == SharedLibraryInfo.TYPE_STATIC) { 9816 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9817 } 9818 } else if (versionedLib.indexOfKey(version) >= 0) { 9819 return false; 9820 } 9821 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9822 version, type, declaringPackageName, declaringVersionCode); 9823 versionedLib.put(version, libEntry); 9824 return true; 9825 } 9826 9827 private boolean removeSharedLibraryLPw(String name, int version) { 9828 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9829 if (versionedLib == null) { 9830 return false; 9831 } 9832 final int libIdx = versionedLib.indexOfKey(version); 9833 if (libIdx < 0) { 9834 return false; 9835 } 9836 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9837 versionedLib.remove(version); 9838 if (versionedLib.size() <= 0) { 9839 mSharedLibraries.remove(name); 9840 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9841 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9842 .getPackageName()); 9843 } 9844 } 9845 return true; 9846 } 9847 9848 /** 9849 * Adds a scanned package to the system. When this method is finished, the package will 9850 * be available for query, resolution, etc... 9851 */ 9852 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9853 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9854 final String pkgName = pkg.packageName; 9855 if (mCustomResolverComponentName != null && 9856 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9857 setUpCustomResolverActivity(pkg); 9858 } 9859 9860 if (pkg.packageName.equals("android")) { 9861 synchronized (mPackages) { 9862 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9863 // Set up information for our fall-back user intent resolution activity. 9864 mPlatformPackage = pkg; 9865 pkg.mVersionCode = mSdkVersion; 9866 mAndroidApplication = pkg.applicationInfo; 9867 if (!mResolverReplaced) { 9868 mResolveActivity.applicationInfo = mAndroidApplication; 9869 mResolveActivity.name = ResolverActivity.class.getName(); 9870 mResolveActivity.packageName = mAndroidApplication.packageName; 9871 mResolveActivity.processName = "system:ui"; 9872 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9873 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9874 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9875 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9876 mResolveActivity.exported = true; 9877 mResolveActivity.enabled = true; 9878 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9879 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9880 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9881 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9882 | ActivityInfo.CONFIG_ORIENTATION 9883 | ActivityInfo.CONFIG_KEYBOARD 9884 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9885 mResolveInfo.activityInfo = mResolveActivity; 9886 mResolveInfo.priority = 0; 9887 mResolveInfo.preferredOrder = 0; 9888 mResolveInfo.match = 0; 9889 mResolveComponentName = new ComponentName( 9890 mAndroidApplication.packageName, mResolveActivity.name); 9891 } 9892 } 9893 } 9894 } 9895 9896 ArrayList<PackageParser.Package> clientLibPkgs = null; 9897 // writer 9898 synchronized (mPackages) { 9899 boolean hasStaticSharedLibs = false; 9900 9901 // Any app can add new static shared libraries 9902 if (pkg.staticSharedLibName != null) { 9903 // Static shared libs don't allow renaming as they have synthetic package 9904 // names to allow install of multiple versions, so use name from manifest. 9905 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9906 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9907 pkg.manifestPackageName, pkg.mVersionCode)) { 9908 hasStaticSharedLibs = true; 9909 } else { 9910 Slog.w(TAG, "Package " + pkg.packageName + " library " 9911 + pkg.staticSharedLibName + " already exists; skipping"); 9912 } 9913 // Static shared libs cannot be updated once installed since they 9914 // use synthetic package name which includes the version code, so 9915 // not need to update other packages's shared lib dependencies. 9916 } 9917 9918 if (!hasStaticSharedLibs 9919 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9920 // Only system apps can add new dynamic shared libraries. 9921 if (pkg.libraryNames != null) { 9922 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9923 String name = pkg.libraryNames.get(i); 9924 boolean allowed = false; 9925 if (pkg.isUpdatedSystemApp()) { 9926 // New library entries can only be added through the 9927 // system image. This is important to get rid of a lot 9928 // of nasty edge cases: for example if we allowed a non- 9929 // system update of the app to add a library, then uninstalling 9930 // the update would make the library go away, and assumptions 9931 // we made such as through app install filtering would now 9932 // have allowed apps on the device which aren't compatible 9933 // with it. Better to just have the restriction here, be 9934 // conservative, and create many fewer cases that can negatively 9935 // impact the user experience. 9936 final PackageSetting sysPs = mSettings 9937 .getDisabledSystemPkgLPr(pkg.packageName); 9938 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9939 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9940 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9941 allowed = true; 9942 break; 9943 } 9944 } 9945 } 9946 } else { 9947 allowed = true; 9948 } 9949 if (allowed) { 9950 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9951 SharedLibraryInfo.VERSION_UNDEFINED, 9952 SharedLibraryInfo.TYPE_DYNAMIC, 9953 pkg.packageName, pkg.mVersionCode)) { 9954 Slog.w(TAG, "Package " + pkg.packageName + " library " 9955 + name + " already exists; skipping"); 9956 } 9957 } else { 9958 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9959 + name + " that is not declared on system image; skipping"); 9960 } 9961 } 9962 9963 if ((scanFlags & SCAN_BOOTING) == 0) { 9964 // If we are not booting, we need to update any applications 9965 // that are clients of our shared library. If we are booting, 9966 // this will all be done once the scan is complete. 9967 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9968 } 9969 } 9970 } 9971 } 9972 9973 if ((scanFlags & SCAN_BOOTING) != 0) { 9974 // No apps can run during boot scan, so they don't need to be frozen 9975 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9976 // Caller asked to not kill app, so it's probably not frozen 9977 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9978 // Caller asked us to ignore frozen check for some reason; they 9979 // probably didn't know the package name 9980 } else { 9981 // We're doing major surgery on this package, so it better be frozen 9982 // right now to keep it from launching 9983 checkPackageFrozen(pkgName); 9984 } 9985 9986 // Also need to kill any apps that are dependent on the library. 9987 if (clientLibPkgs != null) { 9988 for (int i=0; i<clientLibPkgs.size(); i++) { 9989 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9990 killApplication(clientPkg.applicationInfo.packageName, 9991 clientPkg.applicationInfo.uid, "update lib"); 9992 } 9993 } 9994 9995 // writer 9996 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9997 9998 synchronized (mPackages) { 9999 // We don't expect installation to fail beyond this point 10000 10001 if (pkgSetting.pkg != null) { 10002 // Note that |user| might be null during the initial boot scan. If a codePath 10003 // for an app has changed during a boot scan, it's due to an app update that's 10004 // part of the system partition and marker changes must be applied to all users. 10005 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 10006 final int[] userIds = resolveUserIds(userId); 10007 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 10008 } 10009 10010 // Add the new setting to mSettings 10011 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10012 // Add the new setting to mPackages 10013 mPackages.put(pkg.applicationInfo.packageName, pkg); 10014 // Make sure we don't accidentally delete its data. 10015 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10016 while (iter.hasNext()) { 10017 PackageCleanItem item = iter.next(); 10018 if (pkgName.equals(item.packageName)) { 10019 iter.remove(); 10020 } 10021 } 10022 10023 // Add the package's KeySets to the global KeySetManagerService 10024 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10025 ksms.addScannedPackageLPw(pkg); 10026 10027 int N = pkg.providers.size(); 10028 StringBuilder r = null; 10029 int i; 10030 for (i=0; i<N; i++) { 10031 PackageParser.Provider p = pkg.providers.get(i); 10032 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10033 p.info.processName); 10034 mProviders.addProvider(p); 10035 p.syncable = p.info.isSyncable; 10036 if (p.info.authority != null) { 10037 String names[] = p.info.authority.split(";"); 10038 p.info.authority = null; 10039 for (int j = 0; j < names.length; j++) { 10040 if (j == 1 && p.syncable) { 10041 // We only want the first authority for a provider to possibly be 10042 // syncable, so if we already added this provider using a different 10043 // authority clear the syncable flag. We copy the provider before 10044 // changing it because the mProviders object contains a reference 10045 // to a provider that we don't want to change. 10046 // Only do this for the second authority since the resulting provider 10047 // object can be the same for all future authorities for this provider. 10048 p = new PackageParser.Provider(p); 10049 p.syncable = false; 10050 } 10051 if (!mProvidersByAuthority.containsKey(names[j])) { 10052 mProvidersByAuthority.put(names[j], p); 10053 if (p.info.authority == null) { 10054 p.info.authority = names[j]; 10055 } else { 10056 p.info.authority = p.info.authority + ";" + names[j]; 10057 } 10058 if (DEBUG_PACKAGE_SCANNING) { 10059 if (chatty) 10060 Log.d(TAG, "Registered content provider: " + names[j] 10061 + ", className = " + p.info.name + ", isSyncable = " 10062 + p.info.isSyncable); 10063 } 10064 } else { 10065 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10066 Slog.w(TAG, "Skipping provider name " + names[j] + 10067 " (in package " + pkg.applicationInfo.packageName + 10068 "): name already used by " 10069 + ((other != null && other.getComponentName() != null) 10070 ? other.getComponentName().getPackageName() : "?")); 10071 } 10072 } 10073 } 10074 if (chatty) { 10075 if (r == null) { 10076 r = new StringBuilder(256); 10077 } else { 10078 r.append(' '); 10079 } 10080 r.append(p.info.name); 10081 } 10082 } 10083 if (r != null) { 10084 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10085 } 10086 10087 N = pkg.services.size(); 10088 r = null; 10089 for (i=0; i<N; i++) { 10090 PackageParser.Service s = pkg.services.get(i); 10091 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10092 s.info.processName); 10093 mServices.addService(s); 10094 if (chatty) { 10095 if (r == null) { 10096 r = new StringBuilder(256); 10097 } else { 10098 r.append(' '); 10099 } 10100 r.append(s.info.name); 10101 } 10102 } 10103 if (r != null) { 10104 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10105 } 10106 10107 N = pkg.receivers.size(); 10108 r = null; 10109 for (i=0; i<N; i++) { 10110 PackageParser.Activity a = pkg.receivers.get(i); 10111 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10112 a.info.processName); 10113 mReceivers.addActivity(a, "receiver"); 10114 if (chatty) { 10115 if (r == null) { 10116 r = new StringBuilder(256); 10117 } else { 10118 r.append(' '); 10119 } 10120 r.append(a.info.name); 10121 } 10122 } 10123 if (r != null) { 10124 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10125 } 10126 10127 N = pkg.activities.size(); 10128 r = null; 10129 for (i=0; i<N; i++) { 10130 PackageParser.Activity a = pkg.activities.get(i); 10131 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10132 a.info.processName); 10133 mActivities.addActivity(a, "activity"); 10134 if (chatty) { 10135 if (r == null) { 10136 r = new StringBuilder(256); 10137 } else { 10138 r.append(' '); 10139 } 10140 r.append(a.info.name); 10141 } 10142 } 10143 if (r != null) { 10144 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10145 } 10146 10147 N = pkg.permissionGroups.size(); 10148 r = null; 10149 for (i=0; i<N; i++) { 10150 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10151 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10152 final String curPackageName = cur == null ? null : cur.info.packageName; 10153 // Dont allow ephemeral apps to define new permission groups. 10154 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10155 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10156 + pg.info.packageName 10157 + " ignored: instant apps cannot define new permission groups."); 10158 continue; 10159 } 10160 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10161 if (cur == null || isPackageUpdate) { 10162 mPermissionGroups.put(pg.info.name, pg); 10163 if (chatty) { 10164 if (r == null) { 10165 r = new StringBuilder(256); 10166 } else { 10167 r.append(' '); 10168 } 10169 if (isPackageUpdate) { 10170 r.append("UPD:"); 10171 } 10172 r.append(pg.info.name); 10173 } 10174 } else { 10175 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10176 + pg.info.packageName + " ignored: original from " 10177 + cur.info.packageName); 10178 if (chatty) { 10179 if (r == null) { 10180 r = new StringBuilder(256); 10181 } else { 10182 r.append(' '); 10183 } 10184 r.append("DUP:"); 10185 r.append(pg.info.name); 10186 } 10187 } 10188 } 10189 if (r != null) { 10190 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10191 } 10192 10193 N = pkg.permissions.size(); 10194 r = null; 10195 for (i=0; i<N; i++) { 10196 PackageParser.Permission p = pkg.permissions.get(i); 10197 10198 // Dont allow ephemeral apps to define new permissions. 10199 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10200 Slog.w(TAG, "Permission " + p.info.name + " from package " 10201 + p.info.packageName 10202 + " ignored: instant apps cannot define new permissions."); 10203 continue; 10204 } 10205 10206 // Assume by default that we did not install this permission into the system. 10207 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10208 10209 // Now that permission groups have a special meaning, we ignore permission 10210 // groups for legacy apps to prevent unexpected behavior. In particular, 10211 // permissions for one app being granted to someone just becase they happen 10212 // to be in a group defined by another app (before this had no implications). 10213 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10214 p.group = mPermissionGroups.get(p.info.group); 10215 // Warn for a permission in an unknown group. 10216 if (p.info.group != null && p.group == null) { 10217 Slog.w(TAG, "Permission " + p.info.name + " from package " 10218 + p.info.packageName + " in an unknown group " + p.info.group); 10219 } 10220 } 10221 10222 ArrayMap<String, BasePermission> permissionMap = 10223 p.tree ? mSettings.mPermissionTrees 10224 : mSettings.mPermissions; 10225 BasePermission bp = permissionMap.get(p.info.name); 10226 10227 // Allow system apps to redefine non-system permissions 10228 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10229 final boolean currentOwnerIsSystem = (bp.perm != null 10230 && isSystemApp(bp.perm.owner)); 10231 if (isSystemApp(p.owner)) { 10232 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10233 // It's a built-in permission and no owner, take ownership now 10234 bp.packageSetting = pkgSetting; 10235 bp.perm = p; 10236 bp.uid = pkg.applicationInfo.uid; 10237 bp.sourcePackage = p.info.packageName; 10238 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10239 } else if (!currentOwnerIsSystem) { 10240 String msg = "New decl " + p.owner + " of permission " 10241 + p.info.name + " is system; overriding " + bp.sourcePackage; 10242 reportSettingsProblem(Log.WARN, msg); 10243 bp = null; 10244 } 10245 } 10246 } 10247 10248 if (bp == null) { 10249 bp = new BasePermission(p.info.name, p.info.packageName, 10250 BasePermission.TYPE_NORMAL); 10251 permissionMap.put(p.info.name, bp); 10252 } 10253 10254 if (bp.perm == null) { 10255 if (bp.sourcePackage == null 10256 || bp.sourcePackage.equals(p.info.packageName)) { 10257 BasePermission tree = findPermissionTreeLP(p.info.name); 10258 if (tree == null 10259 || tree.sourcePackage.equals(p.info.packageName)) { 10260 bp.packageSetting = pkgSetting; 10261 bp.perm = p; 10262 bp.uid = pkg.applicationInfo.uid; 10263 bp.sourcePackage = p.info.packageName; 10264 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10265 if (chatty) { 10266 if (r == null) { 10267 r = new StringBuilder(256); 10268 } else { 10269 r.append(' '); 10270 } 10271 r.append(p.info.name); 10272 } 10273 } else { 10274 Slog.w(TAG, "Permission " + p.info.name + " from package " 10275 + p.info.packageName + " ignored: base tree " 10276 + tree.name + " is from package " 10277 + tree.sourcePackage); 10278 } 10279 } else { 10280 Slog.w(TAG, "Permission " + p.info.name + " from package " 10281 + p.info.packageName + " ignored: original from " 10282 + bp.sourcePackage); 10283 } 10284 } else if (chatty) { 10285 if (r == null) { 10286 r = new StringBuilder(256); 10287 } else { 10288 r.append(' '); 10289 } 10290 r.append("DUP:"); 10291 r.append(p.info.name); 10292 } 10293 if (bp.perm == p) { 10294 bp.protectionLevel = p.info.protectionLevel; 10295 } 10296 } 10297 10298 if (r != null) { 10299 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10300 } 10301 10302 N = pkg.instrumentation.size(); 10303 r = null; 10304 for (i=0; i<N; i++) { 10305 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10306 a.info.packageName = pkg.applicationInfo.packageName; 10307 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10308 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10309 a.info.splitNames = pkg.splitNames; 10310 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10311 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10312 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10313 a.info.dataDir = pkg.applicationInfo.dataDir; 10314 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10315 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10316 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10317 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10318 mInstrumentation.put(a.getComponentName(), a); 10319 if (chatty) { 10320 if (r == null) { 10321 r = new StringBuilder(256); 10322 } else { 10323 r.append(' '); 10324 } 10325 r.append(a.info.name); 10326 } 10327 } 10328 if (r != null) { 10329 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10330 } 10331 10332 if (pkg.protectedBroadcasts != null) { 10333 N = pkg.protectedBroadcasts.size(); 10334 for (i=0; i<N; i++) { 10335 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10336 } 10337 } 10338 } 10339 10340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10341 } 10342 10343 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10344 PackageParser.Package update, int[] userIds) { 10345 if (existing.applicationInfo == null || update.applicationInfo == null) { 10346 // This isn't due to an app installation. 10347 return; 10348 } 10349 10350 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10351 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10352 10353 // The codePath hasn't changed, so there's nothing for us to do. 10354 if (Objects.equals(oldCodePath, newCodePath)) { 10355 return; 10356 } 10357 10358 File canonicalNewCodePath; 10359 try { 10360 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10361 } catch (IOException e) { 10362 Slog.w(TAG, "Failed to get canonical path.", e); 10363 return; 10364 } 10365 10366 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10367 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10368 // that the last component of the path (i.e, the name) doesn't need canonicalization 10369 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10370 // but may change in the future. Hopefully this function won't exist at that point. 10371 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10372 oldCodePath.getName()); 10373 10374 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10375 // with "@". 10376 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10377 if (!oldMarkerPrefix.endsWith("@")) { 10378 oldMarkerPrefix += "@"; 10379 } 10380 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10381 if (!newMarkerPrefix.endsWith("@")) { 10382 newMarkerPrefix += "@"; 10383 } 10384 10385 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10386 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10387 for (String updatedPath : updatedPaths) { 10388 String updatedPathName = new File(updatedPath).getName(); 10389 markerSuffixes.add(updatedPathName.replace('/', '@')); 10390 } 10391 10392 for (int userId : userIds) { 10393 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10394 10395 for (String markerSuffix : markerSuffixes) { 10396 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10397 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10398 if (oldForeignUseMark.exists()) { 10399 try { 10400 Os.rename(oldForeignUseMark.getAbsolutePath(), 10401 newForeignUseMark.getAbsolutePath()); 10402 } catch (ErrnoException e) { 10403 Slog.w(TAG, "Failed to rename foreign use marker", e); 10404 oldForeignUseMark.delete(); 10405 } 10406 } 10407 } 10408 } 10409 } 10410 10411 /** 10412 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10413 * is derived purely on the basis of the contents of {@code scanFile} and 10414 * {@code cpuAbiOverride}. 10415 * 10416 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10417 */ 10418 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10419 String cpuAbiOverride, boolean extractLibs, 10420 File appLib32InstallDir) 10421 throws PackageManagerException { 10422 // Give ourselves some initial paths; we'll come back for another 10423 // pass once we've determined ABI below. 10424 setNativeLibraryPaths(pkg, appLib32InstallDir); 10425 10426 // We would never need to extract libs for forward-locked and external packages, 10427 // since the container service will do it for us. We shouldn't attempt to 10428 // extract libs from system app when it was not updated. 10429 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10430 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10431 extractLibs = false; 10432 } 10433 10434 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10435 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10436 10437 NativeLibraryHelper.Handle handle = null; 10438 try { 10439 handle = NativeLibraryHelper.Handle.create(pkg); 10440 // TODO(multiArch): This can be null for apps that didn't go through the 10441 // usual installation process. We can calculate it again, like we 10442 // do during install time. 10443 // 10444 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10445 // unnecessary. 10446 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10447 10448 // Null out the abis so that they can be recalculated. 10449 pkg.applicationInfo.primaryCpuAbi = null; 10450 pkg.applicationInfo.secondaryCpuAbi = null; 10451 if (isMultiArch(pkg.applicationInfo)) { 10452 // Warn if we've set an abiOverride for multi-lib packages.. 10453 // By definition, we need to copy both 32 and 64 bit libraries for 10454 // such packages. 10455 if (pkg.cpuAbiOverride != null 10456 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10457 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10458 } 10459 10460 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10461 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10462 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10463 if (extractLibs) { 10464 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10465 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10466 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10467 useIsaSpecificSubdirs); 10468 } else { 10469 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10470 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10471 } 10472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10473 } 10474 10475 maybeThrowExceptionForMultiArchCopy( 10476 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10477 10478 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10479 if (extractLibs) { 10480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10481 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10482 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10483 useIsaSpecificSubdirs); 10484 } else { 10485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10486 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10487 } 10488 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10489 } 10490 10491 maybeThrowExceptionForMultiArchCopy( 10492 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10493 10494 if (abi64 >= 0) { 10495 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10496 } 10497 10498 if (abi32 >= 0) { 10499 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10500 if (abi64 >= 0) { 10501 if (pkg.use32bitAbi) { 10502 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10503 pkg.applicationInfo.primaryCpuAbi = abi; 10504 } else { 10505 pkg.applicationInfo.secondaryCpuAbi = abi; 10506 } 10507 } else { 10508 pkg.applicationInfo.primaryCpuAbi = abi; 10509 } 10510 } 10511 10512 } else { 10513 String[] abiList = (cpuAbiOverride != null) ? 10514 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10515 10516 // Enable gross and lame hacks for apps that are built with old 10517 // SDK tools. We must scan their APKs for renderscript bitcode and 10518 // not launch them if it's present. Don't bother checking on devices 10519 // that don't have 64 bit support. 10520 boolean needsRenderScriptOverride = false; 10521 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10522 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10523 abiList = Build.SUPPORTED_32_BIT_ABIS; 10524 needsRenderScriptOverride = true; 10525 } 10526 10527 final int copyRet; 10528 if (extractLibs) { 10529 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10530 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10531 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10532 } else { 10533 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10534 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10535 } 10536 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10537 10538 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10539 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10540 "Error unpackaging native libs for app, errorCode=" + copyRet); 10541 } 10542 10543 if (copyRet >= 0) { 10544 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10545 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10546 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10547 } else if (needsRenderScriptOverride) { 10548 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10549 } 10550 } 10551 } catch (IOException ioe) { 10552 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10553 } finally { 10554 IoUtils.closeQuietly(handle); 10555 } 10556 10557 // Now that we've calculated the ABIs and determined if it's an internal app, 10558 // we will go ahead and populate the nativeLibraryPath. 10559 setNativeLibraryPaths(pkg, appLib32InstallDir); 10560 } 10561 10562 /** 10563 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10564 * i.e, so that all packages can be run inside a single process if required. 10565 * 10566 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10567 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10568 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10569 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10570 * updating a package that belongs to a shared user. 10571 * 10572 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10573 * adds unnecessary complexity. 10574 */ 10575 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10576 PackageParser.Package scannedPackage) { 10577 String requiredInstructionSet = null; 10578 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10579 requiredInstructionSet = VMRuntime.getInstructionSet( 10580 scannedPackage.applicationInfo.primaryCpuAbi); 10581 } 10582 10583 PackageSetting requirer = null; 10584 for (PackageSetting ps : packagesForUser) { 10585 // If packagesForUser contains scannedPackage, we skip it. This will happen 10586 // when scannedPackage is an update of an existing package. Without this check, 10587 // we will never be able to change the ABI of any package belonging to a shared 10588 // user, even if it's compatible with other packages. 10589 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10590 if (ps.primaryCpuAbiString == null) { 10591 continue; 10592 } 10593 10594 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10595 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10596 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10597 // this but there's not much we can do. 10598 String errorMessage = "Instruction set mismatch, " 10599 + ((requirer == null) ? "[caller]" : requirer) 10600 + " requires " + requiredInstructionSet + " whereas " + ps 10601 + " requires " + instructionSet; 10602 Slog.w(TAG, errorMessage); 10603 } 10604 10605 if (requiredInstructionSet == null) { 10606 requiredInstructionSet = instructionSet; 10607 requirer = ps; 10608 } 10609 } 10610 } 10611 10612 if (requiredInstructionSet != null) { 10613 String adjustedAbi; 10614 if (requirer != null) { 10615 // requirer != null implies that either scannedPackage was null or that scannedPackage 10616 // did not require an ABI, in which case we have to adjust scannedPackage to match 10617 // the ABI of the set (which is the same as requirer's ABI) 10618 adjustedAbi = requirer.primaryCpuAbiString; 10619 if (scannedPackage != null) { 10620 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10621 } 10622 } else { 10623 // requirer == null implies that we're updating all ABIs in the set to 10624 // match scannedPackage. 10625 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10626 } 10627 10628 for (PackageSetting ps : packagesForUser) { 10629 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10630 if (ps.primaryCpuAbiString != null) { 10631 continue; 10632 } 10633 10634 ps.primaryCpuAbiString = adjustedAbi; 10635 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10636 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10637 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10638 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10639 + " (requirer=" 10640 + (requirer == null ? "null" : requirer.pkg.packageName) 10641 + ", scannedPackage=" 10642 + (scannedPackage != null ? scannedPackage.packageName : "null") 10643 + ")"); 10644 try { 10645 mInstaller.rmdex(ps.codePathString, 10646 getDexCodeInstructionSet(getPreferredInstructionSet())); 10647 } catch (InstallerException ignored) { 10648 } 10649 } 10650 } 10651 } 10652 } 10653 } 10654 10655 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10656 synchronized (mPackages) { 10657 mResolverReplaced = true; 10658 // Set up information for custom user intent resolution activity. 10659 mResolveActivity.applicationInfo = pkg.applicationInfo; 10660 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10661 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10662 mResolveActivity.processName = pkg.applicationInfo.packageName; 10663 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10664 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10665 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10666 mResolveActivity.theme = 0; 10667 mResolveActivity.exported = true; 10668 mResolveActivity.enabled = true; 10669 mResolveInfo.activityInfo = mResolveActivity; 10670 mResolveInfo.priority = 0; 10671 mResolveInfo.preferredOrder = 0; 10672 mResolveInfo.match = 0; 10673 mResolveComponentName = mCustomResolverComponentName; 10674 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10675 mResolveComponentName); 10676 } 10677 } 10678 10679 private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) { 10680 if (installerComponent == null) { 10681 if (DEBUG_EPHEMERAL) { 10682 Slog.d(TAG, "Clear ephemeral installer activity"); 10683 } 10684 mInstantAppInstallerActivity.applicationInfo = null; 10685 return; 10686 } 10687 10688 if (DEBUG_EPHEMERAL) { 10689 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10690 } 10691 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10692 // Set up information for ephemeral installer activity 10693 mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo; 10694 mInstantAppInstallerActivity.name = installerComponent.getClassName(); 10695 mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName; 10696 mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName; 10697 mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10698 mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10699 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10700 mInstantAppInstallerActivity.theme = 0; 10701 mInstantAppInstallerActivity.exported = true; 10702 mInstantAppInstallerActivity.enabled = true; 10703 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10704 mInstantAppInstallerInfo.priority = 0; 10705 mInstantAppInstallerInfo.preferredOrder = 1; 10706 mInstantAppInstallerInfo.isDefault = true; 10707 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10708 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10709 } 10710 10711 private static String calculateBundledApkRoot(final String codePathString) { 10712 final File codePath = new File(codePathString); 10713 final File codeRoot; 10714 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10715 codeRoot = Environment.getRootDirectory(); 10716 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10717 codeRoot = Environment.getOemDirectory(); 10718 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10719 codeRoot = Environment.getVendorDirectory(); 10720 } else { 10721 // Unrecognized code path; take its top real segment as the apk root: 10722 // e.g. /something/app/blah.apk => /something 10723 try { 10724 File f = codePath.getCanonicalFile(); 10725 File parent = f.getParentFile(); // non-null because codePath is a file 10726 File tmp; 10727 while ((tmp = parent.getParentFile()) != null) { 10728 f = parent; 10729 parent = tmp; 10730 } 10731 codeRoot = f; 10732 Slog.w(TAG, "Unrecognized code path " 10733 + codePath + " - using " + codeRoot); 10734 } catch (IOException e) { 10735 // Can't canonicalize the code path -- shenanigans? 10736 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10737 return Environment.getRootDirectory().getPath(); 10738 } 10739 } 10740 return codeRoot.getPath(); 10741 } 10742 10743 /** 10744 * Derive and set the location of native libraries for the given package, 10745 * which varies depending on where and how the package was installed. 10746 */ 10747 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10748 final ApplicationInfo info = pkg.applicationInfo; 10749 final String codePath = pkg.codePath; 10750 final File codeFile = new File(codePath); 10751 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10752 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10753 10754 info.nativeLibraryRootDir = null; 10755 info.nativeLibraryRootRequiresIsa = false; 10756 info.nativeLibraryDir = null; 10757 info.secondaryNativeLibraryDir = null; 10758 10759 if (isApkFile(codeFile)) { 10760 // Monolithic install 10761 if (bundledApp) { 10762 // If "/system/lib64/apkname" exists, assume that is the per-package 10763 // native library directory to use; otherwise use "/system/lib/apkname". 10764 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10765 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10766 getPrimaryInstructionSet(info)); 10767 10768 // This is a bundled system app so choose the path based on the ABI. 10769 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10770 // is just the default path. 10771 final String apkName = deriveCodePathName(codePath); 10772 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10773 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10774 apkName).getAbsolutePath(); 10775 10776 if (info.secondaryCpuAbi != null) { 10777 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10778 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10779 secondaryLibDir, apkName).getAbsolutePath(); 10780 } 10781 } else if (asecApp) { 10782 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10783 .getAbsolutePath(); 10784 } else { 10785 final String apkName = deriveCodePathName(codePath); 10786 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10787 .getAbsolutePath(); 10788 } 10789 10790 info.nativeLibraryRootRequiresIsa = false; 10791 info.nativeLibraryDir = info.nativeLibraryRootDir; 10792 } else { 10793 // Cluster install 10794 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10795 info.nativeLibraryRootRequiresIsa = true; 10796 10797 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10798 getPrimaryInstructionSet(info)).getAbsolutePath(); 10799 10800 if (info.secondaryCpuAbi != null) { 10801 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10802 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10803 } 10804 } 10805 } 10806 10807 /** 10808 * Calculate the abis and roots for a bundled app. These can uniquely 10809 * be determined from the contents of the system partition, i.e whether 10810 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10811 * of this information, and instead assume that the system was built 10812 * sensibly. 10813 */ 10814 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10815 PackageSetting pkgSetting) { 10816 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10817 10818 // If "/system/lib64/apkname" exists, assume that is the per-package 10819 // native library directory to use; otherwise use "/system/lib/apkname". 10820 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10821 setBundledAppAbi(pkg, apkRoot, apkName); 10822 // pkgSetting might be null during rescan following uninstall of updates 10823 // to a bundled app, so accommodate that possibility. The settings in 10824 // that case will be established later from the parsed package. 10825 // 10826 // If the settings aren't null, sync them up with what we've just derived. 10827 // note that apkRoot isn't stored in the package settings. 10828 if (pkgSetting != null) { 10829 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10830 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10831 } 10832 } 10833 10834 /** 10835 * Deduces the ABI of a bundled app and sets the relevant fields on the 10836 * parsed pkg object. 10837 * 10838 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10839 * under which system libraries are installed. 10840 * @param apkName the name of the installed package. 10841 */ 10842 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10843 final File codeFile = new File(pkg.codePath); 10844 10845 final boolean has64BitLibs; 10846 final boolean has32BitLibs; 10847 if (isApkFile(codeFile)) { 10848 // Monolithic install 10849 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10850 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10851 } else { 10852 // Cluster install 10853 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10854 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10855 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10856 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10857 has64BitLibs = (new File(rootDir, isa)).exists(); 10858 } else { 10859 has64BitLibs = false; 10860 } 10861 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10862 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10863 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10864 has32BitLibs = (new File(rootDir, isa)).exists(); 10865 } else { 10866 has32BitLibs = false; 10867 } 10868 } 10869 10870 if (has64BitLibs && !has32BitLibs) { 10871 // The package has 64 bit libs, but not 32 bit libs. Its primary 10872 // ABI should be 64 bit. We can safely assume here that the bundled 10873 // native libraries correspond to the most preferred ABI in the list. 10874 10875 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10876 pkg.applicationInfo.secondaryCpuAbi = null; 10877 } else if (has32BitLibs && !has64BitLibs) { 10878 // The package has 32 bit libs but not 64 bit libs. Its primary 10879 // ABI should be 32 bit. 10880 10881 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10882 pkg.applicationInfo.secondaryCpuAbi = null; 10883 } else if (has32BitLibs && has64BitLibs) { 10884 // The application has both 64 and 32 bit bundled libraries. We check 10885 // here that the app declares multiArch support, and warn if it doesn't. 10886 // 10887 // We will be lenient here and record both ABIs. The primary will be the 10888 // ABI that's higher on the list, i.e, a device that's configured to prefer 10889 // 64 bit apps will see a 64 bit primary ABI, 10890 10891 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10892 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10893 } 10894 10895 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10896 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10897 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10898 } else { 10899 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10900 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10901 } 10902 } else { 10903 pkg.applicationInfo.primaryCpuAbi = null; 10904 pkg.applicationInfo.secondaryCpuAbi = null; 10905 } 10906 } 10907 10908 private void killApplication(String pkgName, int appId, String reason) { 10909 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10910 } 10911 10912 private void killApplication(String pkgName, int appId, int userId, String reason) { 10913 // Request the ActivityManager to kill the process(only for existing packages) 10914 // so that we do not end up in a confused state while the user is still using the older 10915 // version of the application while the new one gets installed. 10916 final long token = Binder.clearCallingIdentity(); 10917 try { 10918 IActivityManager am = ActivityManager.getService(); 10919 if (am != null) { 10920 try { 10921 am.killApplication(pkgName, appId, userId, reason); 10922 } catch (RemoteException e) { 10923 } 10924 } 10925 } finally { 10926 Binder.restoreCallingIdentity(token); 10927 } 10928 } 10929 10930 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10931 // Remove the parent package setting 10932 PackageSetting ps = (PackageSetting) pkg.mExtras; 10933 if (ps != null) { 10934 removePackageLI(ps, chatty); 10935 } 10936 // Remove the child package setting 10937 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10938 for (int i = 0; i < childCount; i++) { 10939 PackageParser.Package childPkg = pkg.childPackages.get(i); 10940 ps = (PackageSetting) childPkg.mExtras; 10941 if (ps != null) { 10942 removePackageLI(ps, chatty); 10943 } 10944 } 10945 } 10946 10947 void removePackageLI(PackageSetting ps, boolean chatty) { 10948 if (DEBUG_INSTALL) { 10949 if (chatty) 10950 Log.d(TAG, "Removing package " + ps.name); 10951 } 10952 10953 // writer 10954 synchronized (mPackages) { 10955 mPackages.remove(ps.name); 10956 final PackageParser.Package pkg = ps.pkg; 10957 if (pkg != null) { 10958 cleanPackageDataStructuresLILPw(pkg, chatty); 10959 } 10960 } 10961 } 10962 10963 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10964 if (DEBUG_INSTALL) { 10965 if (chatty) 10966 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10967 } 10968 10969 // writer 10970 synchronized (mPackages) { 10971 // Remove the parent package 10972 mPackages.remove(pkg.applicationInfo.packageName); 10973 cleanPackageDataStructuresLILPw(pkg, chatty); 10974 10975 // Remove the child packages 10976 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10977 for (int i = 0; i < childCount; i++) { 10978 PackageParser.Package childPkg = pkg.childPackages.get(i); 10979 mPackages.remove(childPkg.applicationInfo.packageName); 10980 cleanPackageDataStructuresLILPw(childPkg, chatty); 10981 } 10982 } 10983 } 10984 10985 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10986 int N = pkg.providers.size(); 10987 StringBuilder r = null; 10988 int i; 10989 for (i=0; i<N; i++) { 10990 PackageParser.Provider p = pkg.providers.get(i); 10991 mProviders.removeProvider(p); 10992 if (p.info.authority == null) { 10993 10994 /* There was another ContentProvider with this authority when 10995 * this app was installed so this authority is null, 10996 * Ignore it as we don't have to unregister the provider. 10997 */ 10998 continue; 10999 } 11000 String names[] = p.info.authority.split(";"); 11001 for (int j = 0; j < names.length; j++) { 11002 if (mProvidersByAuthority.get(names[j]) == p) { 11003 mProvidersByAuthority.remove(names[j]); 11004 if (DEBUG_REMOVE) { 11005 if (chatty) 11006 Log.d(TAG, "Unregistered content provider: " + names[j] 11007 + ", className = " + p.info.name + ", isSyncable = " 11008 + p.info.isSyncable); 11009 } 11010 } 11011 } 11012 if (DEBUG_REMOVE && chatty) { 11013 if (r == null) { 11014 r = new StringBuilder(256); 11015 } else { 11016 r.append(' '); 11017 } 11018 r.append(p.info.name); 11019 } 11020 } 11021 if (r != null) { 11022 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11023 } 11024 11025 N = pkg.services.size(); 11026 r = null; 11027 for (i=0; i<N; i++) { 11028 PackageParser.Service s = pkg.services.get(i); 11029 mServices.removeService(s); 11030 if (chatty) { 11031 if (r == null) { 11032 r = new StringBuilder(256); 11033 } else { 11034 r.append(' '); 11035 } 11036 r.append(s.info.name); 11037 } 11038 } 11039 if (r != null) { 11040 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11041 } 11042 11043 N = pkg.receivers.size(); 11044 r = null; 11045 for (i=0; i<N; i++) { 11046 PackageParser.Activity a = pkg.receivers.get(i); 11047 mReceivers.removeActivity(a, "receiver"); 11048 if (DEBUG_REMOVE && chatty) { 11049 if (r == null) { 11050 r = new StringBuilder(256); 11051 } else { 11052 r.append(' '); 11053 } 11054 r.append(a.info.name); 11055 } 11056 } 11057 if (r != null) { 11058 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11059 } 11060 11061 N = pkg.activities.size(); 11062 r = null; 11063 for (i=0; i<N; i++) { 11064 PackageParser.Activity a = pkg.activities.get(i); 11065 mActivities.removeActivity(a, "activity"); 11066 if (DEBUG_REMOVE && chatty) { 11067 if (r == null) { 11068 r = new StringBuilder(256); 11069 } else { 11070 r.append(' '); 11071 } 11072 r.append(a.info.name); 11073 } 11074 } 11075 if (r != null) { 11076 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11077 } 11078 11079 N = pkg.permissions.size(); 11080 r = null; 11081 for (i=0; i<N; i++) { 11082 PackageParser.Permission p = pkg.permissions.get(i); 11083 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11084 if (bp == null) { 11085 bp = mSettings.mPermissionTrees.get(p.info.name); 11086 } 11087 if (bp != null && bp.perm == p) { 11088 bp.perm = null; 11089 if (DEBUG_REMOVE && chatty) { 11090 if (r == null) { 11091 r = new StringBuilder(256); 11092 } else { 11093 r.append(' '); 11094 } 11095 r.append(p.info.name); 11096 } 11097 } 11098 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11099 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11100 if (appOpPkgs != null) { 11101 appOpPkgs.remove(pkg.packageName); 11102 } 11103 } 11104 } 11105 if (r != null) { 11106 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11107 } 11108 11109 N = pkg.requestedPermissions.size(); 11110 r = null; 11111 for (i=0; i<N; i++) { 11112 String perm = pkg.requestedPermissions.get(i); 11113 BasePermission bp = mSettings.mPermissions.get(perm); 11114 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11115 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11116 if (appOpPkgs != null) { 11117 appOpPkgs.remove(pkg.packageName); 11118 if (appOpPkgs.isEmpty()) { 11119 mAppOpPermissionPackages.remove(perm); 11120 } 11121 } 11122 } 11123 } 11124 if (r != null) { 11125 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11126 } 11127 11128 N = pkg.instrumentation.size(); 11129 r = null; 11130 for (i=0; i<N; i++) { 11131 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11132 mInstrumentation.remove(a.getComponentName()); 11133 if (DEBUG_REMOVE && chatty) { 11134 if (r == null) { 11135 r = new StringBuilder(256); 11136 } else { 11137 r.append(' '); 11138 } 11139 r.append(a.info.name); 11140 } 11141 } 11142 if (r != null) { 11143 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11144 } 11145 11146 r = null; 11147 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11148 // Only system apps can hold shared libraries. 11149 if (pkg.libraryNames != null) { 11150 for (i = 0; i < pkg.libraryNames.size(); i++) { 11151 String name = pkg.libraryNames.get(i); 11152 if (removeSharedLibraryLPw(name, 0)) { 11153 if (DEBUG_REMOVE && chatty) { 11154 if (r == null) { 11155 r = new StringBuilder(256); 11156 } else { 11157 r.append(' '); 11158 } 11159 r.append(name); 11160 } 11161 } 11162 } 11163 } 11164 } 11165 11166 r = null; 11167 11168 // Any package can hold static shared libraries. 11169 if (pkg.staticSharedLibName != null) { 11170 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11171 if (DEBUG_REMOVE && chatty) { 11172 if (r == null) { 11173 r = new StringBuilder(256); 11174 } else { 11175 r.append(' '); 11176 } 11177 r.append(pkg.staticSharedLibName); 11178 } 11179 } 11180 } 11181 11182 if (r != null) { 11183 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11184 } 11185 } 11186 11187 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11188 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11189 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11190 return true; 11191 } 11192 } 11193 return false; 11194 } 11195 11196 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11197 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11198 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11199 11200 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11201 // Update the parent permissions 11202 updatePermissionsLPw(pkg.packageName, pkg, flags); 11203 // Update the child permissions 11204 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11205 for (int i = 0; i < childCount; i++) { 11206 PackageParser.Package childPkg = pkg.childPackages.get(i); 11207 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11208 } 11209 } 11210 11211 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11212 int flags) { 11213 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11214 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11215 } 11216 11217 private void updatePermissionsLPw(String changingPkg, 11218 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11219 // Make sure there are no dangling permission trees. 11220 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11221 while (it.hasNext()) { 11222 final BasePermission bp = it.next(); 11223 if (bp.packageSetting == null) { 11224 // We may not yet have parsed the package, so just see if 11225 // we still know about its settings. 11226 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11227 } 11228 if (bp.packageSetting == null) { 11229 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11230 + " from package " + bp.sourcePackage); 11231 it.remove(); 11232 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11233 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11234 Slog.i(TAG, "Removing old permission tree: " + bp.name 11235 + " from package " + bp.sourcePackage); 11236 flags |= UPDATE_PERMISSIONS_ALL; 11237 it.remove(); 11238 } 11239 } 11240 } 11241 11242 // Make sure all dynamic permissions have been assigned to a package, 11243 // and make sure there are no dangling permissions. 11244 it = mSettings.mPermissions.values().iterator(); 11245 while (it.hasNext()) { 11246 final BasePermission bp = it.next(); 11247 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11248 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11249 + bp.name + " pkg=" + bp.sourcePackage 11250 + " info=" + bp.pendingInfo); 11251 if (bp.packageSetting == null && bp.pendingInfo != null) { 11252 final BasePermission tree = findPermissionTreeLP(bp.name); 11253 if (tree != null && tree.perm != null) { 11254 bp.packageSetting = tree.packageSetting; 11255 bp.perm = new PackageParser.Permission(tree.perm.owner, 11256 new PermissionInfo(bp.pendingInfo)); 11257 bp.perm.info.packageName = tree.perm.info.packageName; 11258 bp.perm.info.name = bp.name; 11259 bp.uid = tree.uid; 11260 } 11261 } 11262 } 11263 if (bp.packageSetting == null) { 11264 // We may not yet have parsed the package, so just see if 11265 // we still know about its settings. 11266 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11267 } 11268 if (bp.packageSetting == null) { 11269 Slog.w(TAG, "Removing dangling permission: " + bp.name 11270 + " from package " + bp.sourcePackage); 11271 it.remove(); 11272 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11273 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11274 Slog.i(TAG, "Removing old permission: " + bp.name 11275 + " from package " + bp.sourcePackage); 11276 flags |= UPDATE_PERMISSIONS_ALL; 11277 it.remove(); 11278 } 11279 } 11280 } 11281 11282 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11283 // Now update the permissions for all packages, in particular 11284 // replace the granted permissions of the system packages. 11285 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11286 for (PackageParser.Package pkg : mPackages.values()) { 11287 if (pkg != pkgInfo) { 11288 // Only replace for packages on requested volume 11289 final String volumeUuid = getVolumeUuidForPackage(pkg); 11290 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11291 && Objects.equals(replaceVolumeUuid, volumeUuid); 11292 grantPermissionsLPw(pkg, replace, changingPkg); 11293 } 11294 } 11295 } 11296 11297 if (pkgInfo != null) { 11298 // Only replace for packages on requested volume 11299 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11300 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11301 && Objects.equals(replaceVolumeUuid, volumeUuid); 11302 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11303 } 11304 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11305 } 11306 11307 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11308 String packageOfInterest) { 11309 // IMPORTANT: There are two types of permissions: install and runtime. 11310 // Install time permissions are granted when the app is installed to 11311 // all device users and users added in the future. Runtime permissions 11312 // are granted at runtime explicitly to specific users. Normal and signature 11313 // protected permissions are install time permissions. Dangerous permissions 11314 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11315 // otherwise they are runtime permissions. This function does not manage 11316 // runtime permissions except for the case an app targeting Lollipop MR1 11317 // being upgraded to target a newer SDK, in which case dangerous permissions 11318 // are transformed from install time to runtime ones. 11319 11320 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11321 if (ps == null) { 11322 return; 11323 } 11324 11325 PermissionsState permissionsState = ps.getPermissionsState(); 11326 PermissionsState origPermissions = permissionsState; 11327 11328 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11329 11330 boolean runtimePermissionsRevoked = false; 11331 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11332 11333 boolean changedInstallPermission = false; 11334 11335 if (replace) { 11336 ps.installPermissionsFixed = false; 11337 if (!ps.isSharedUser()) { 11338 origPermissions = new PermissionsState(permissionsState); 11339 permissionsState.reset(); 11340 } else { 11341 // We need to know only about runtime permission changes since the 11342 // calling code always writes the install permissions state but 11343 // the runtime ones are written only if changed. The only cases of 11344 // changed runtime permissions here are promotion of an install to 11345 // runtime and revocation of a runtime from a shared user. 11346 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11347 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11348 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11349 runtimePermissionsRevoked = true; 11350 } 11351 } 11352 } 11353 11354 permissionsState.setGlobalGids(mGlobalGids); 11355 11356 final int N = pkg.requestedPermissions.size(); 11357 for (int i=0; i<N; i++) { 11358 final String name = pkg.requestedPermissions.get(i); 11359 final BasePermission bp = mSettings.mPermissions.get(name); 11360 11361 if (DEBUG_INSTALL) { 11362 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11363 } 11364 11365 if (bp == null || bp.packageSetting == null) { 11366 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11367 Slog.w(TAG, "Unknown permission " + name 11368 + " in package " + pkg.packageName); 11369 } 11370 continue; 11371 } 11372 11373 11374 // Limit ephemeral apps to ephemeral allowed permissions. 11375 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11376 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11377 + pkg.packageName); 11378 continue; 11379 } 11380 11381 final String perm = bp.name; 11382 boolean allowedSig = false; 11383 int grant = GRANT_DENIED; 11384 11385 // Keep track of app op permissions. 11386 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11387 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11388 if (pkgs == null) { 11389 pkgs = new ArraySet<>(); 11390 mAppOpPermissionPackages.put(bp.name, pkgs); 11391 } 11392 pkgs.add(pkg.packageName); 11393 } 11394 11395 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11396 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11397 >= Build.VERSION_CODES.M; 11398 switch (level) { 11399 case PermissionInfo.PROTECTION_NORMAL: { 11400 // For all apps normal permissions are install time ones. 11401 grant = GRANT_INSTALL; 11402 } break; 11403 11404 case PermissionInfo.PROTECTION_DANGEROUS: { 11405 // If a permission review is required for legacy apps we represent 11406 // their permissions as always granted runtime ones since we need 11407 // to keep the review required permission flag per user while an 11408 // install permission's state is shared across all users. 11409 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11410 // For legacy apps dangerous permissions are install time ones. 11411 grant = GRANT_INSTALL; 11412 } else if (origPermissions.hasInstallPermission(bp.name)) { 11413 // For legacy apps that became modern, install becomes runtime. 11414 grant = GRANT_UPGRADE; 11415 } else if (mPromoteSystemApps 11416 && isSystemApp(ps) 11417 && mExistingSystemPackages.contains(ps.name)) { 11418 // For legacy system apps, install becomes runtime. 11419 // We cannot check hasInstallPermission() for system apps since those 11420 // permissions were granted implicitly and not persisted pre-M. 11421 grant = GRANT_UPGRADE; 11422 } else { 11423 // For modern apps keep runtime permissions unchanged. 11424 grant = GRANT_RUNTIME; 11425 } 11426 } break; 11427 11428 case PermissionInfo.PROTECTION_SIGNATURE: { 11429 // For all apps signature permissions are install time ones. 11430 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11431 if (allowedSig) { 11432 grant = GRANT_INSTALL; 11433 } 11434 } break; 11435 } 11436 11437 if (DEBUG_INSTALL) { 11438 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11439 } 11440 11441 if (grant != GRANT_DENIED) { 11442 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11443 // If this is an existing, non-system package, then 11444 // we can't add any new permissions to it. 11445 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11446 // Except... if this is a permission that was added 11447 // to the platform (note: need to only do this when 11448 // updating the platform). 11449 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11450 grant = GRANT_DENIED; 11451 } 11452 } 11453 } 11454 11455 switch (grant) { 11456 case GRANT_INSTALL: { 11457 // Revoke this as runtime permission to handle the case of 11458 // a runtime permission being downgraded to an install one. 11459 // Also in permission review mode we keep dangerous permissions 11460 // for legacy apps 11461 for (int userId : UserManagerService.getInstance().getUserIds()) { 11462 if (origPermissions.getRuntimePermissionState( 11463 bp.name, userId) != null) { 11464 // Revoke the runtime permission and clear the flags. 11465 origPermissions.revokeRuntimePermission(bp, userId); 11466 origPermissions.updatePermissionFlags(bp, userId, 11467 PackageManager.MASK_PERMISSION_FLAGS, 0); 11468 // If we revoked a permission permission, we have to write. 11469 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11470 changedRuntimePermissionUserIds, userId); 11471 } 11472 } 11473 // Grant an install permission. 11474 if (permissionsState.grantInstallPermission(bp) != 11475 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11476 changedInstallPermission = true; 11477 } 11478 } break; 11479 11480 case GRANT_RUNTIME: { 11481 // Grant previously granted runtime permissions. 11482 for (int userId : UserManagerService.getInstance().getUserIds()) { 11483 PermissionState permissionState = origPermissions 11484 .getRuntimePermissionState(bp.name, userId); 11485 int flags = permissionState != null 11486 ? permissionState.getFlags() : 0; 11487 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11488 // Don't propagate the permission in a permission review mode if 11489 // the former was revoked, i.e. marked to not propagate on upgrade. 11490 // Note that in a permission review mode install permissions are 11491 // represented as constantly granted runtime ones since we need to 11492 // keep a per user state associated with the permission. Also the 11493 // revoke on upgrade flag is no longer applicable and is reset. 11494 final boolean revokeOnUpgrade = (flags & PackageManager 11495 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11496 if (revokeOnUpgrade) { 11497 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11498 // Since we changed the flags, we have to write. 11499 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11500 changedRuntimePermissionUserIds, userId); 11501 } 11502 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11503 if (permissionsState.grantRuntimePermission(bp, userId) == 11504 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11505 // If we cannot put the permission as it was, 11506 // we have to write. 11507 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11508 changedRuntimePermissionUserIds, userId); 11509 } 11510 } 11511 11512 // If the app supports runtime permissions no need for a review. 11513 if (mPermissionReviewRequired 11514 && appSupportsRuntimePermissions 11515 && (flags & PackageManager 11516 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11517 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11518 // Since we changed the flags, we have to write. 11519 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11520 changedRuntimePermissionUserIds, userId); 11521 } 11522 } else if (mPermissionReviewRequired 11523 && !appSupportsRuntimePermissions) { 11524 // For legacy apps that need a permission review, every new 11525 // runtime permission is granted but it is pending a review. 11526 // We also need to review only platform defined runtime 11527 // permissions as these are the only ones the platform knows 11528 // how to disable the API to simulate revocation as legacy 11529 // apps don't expect to run with revoked permissions. 11530 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11531 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11532 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11533 // We changed the flags, hence have to write. 11534 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11535 changedRuntimePermissionUserIds, userId); 11536 } 11537 } 11538 if (permissionsState.grantRuntimePermission(bp, userId) 11539 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11540 // We changed the permission, hence have to write. 11541 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11542 changedRuntimePermissionUserIds, userId); 11543 } 11544 } 11545 // Propagate the permission flags. 11546 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11547 } 11548 } break; 11549 11550 case GRANT_UPGRADE: { 11551 // Grant runtime permissions for a previously held install permission. 11552 PermissionState permissionState = origPermissions 11553 .getInstallPermissionState(bp.name); 11554 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11555 11556 if (origPermissions.revokeInstallPermission(bp) 11557 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11558 // We will be transferring the permission flags, so clear them. 11559 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11560 PackageManager.MASK_PERMISSION_FLAGS, 0); 11561 changedInstallPermission = true; 11562 } 11563 11564 // If the permission is not to be promoted to runtime we ignore it and 11565 // also its other flags as they are not applicable to install permissions. 11566 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11567 for (int userId : currentUserIds) { 11568 if (permissionsState.grantRuntimePermission(bp, userId) != 11569 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11570 // Transfer the permission flags. 11571 permissionsState.updatePermissionFlags(bp, userId, 11572 flags, flags); 11573 // If we granted the permission, we have to write. 11574 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11575 changedRuntimePermissionUserIds, userId); 11576 } 11577 } 11578 } 11579 } break; 11580 11581 default: { 11582 if (packageOfInterest == null 11583 || packageOfInterest.equals(pkg.packageName)) { 11584 Slog.w(TAG, "Not granting permission " + perm 11585 + " to package " + pkg.packageName 11586 + " because it was previously installed without"); 11587 } 11588 } break; 11589 } 11590 } else { 11591 if (permissionsState.revokeInstallPermission(bp) != 11592 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11593 // Also drop the permission flags. 11594 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11595 PackageManager.MASK_PERMISSION_FLAGS, 0); 11596 changedInstallPermission = true; 11597 Slog.i(TAG, "Un-granting permission " + perm 11598 + " from package " + pkg.packageName 11599 + " (protectionLevel=" + bp.protectionLevel 11600 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11601 + ")"); 11602 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11603 // Don't print warning for app op permissions, since it is fine for them 11604 // not to be granted, there is a UI for the user to decide. 11605 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11606 Slog.w(TAG, "Not granting permission " + perm 11607 + " to package " + pkg.packageName 11608 + " (protectionLevel=" + bp.protectionLevel 11609 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11610 + ")"); 11611 } 11612 } 11613 } 11614 } 11615 11616 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11617 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11618 // This is the first that we have heard about this package, so the 11619 // permissions we have now selected are fixed until explicitly 11620 // changed. 11621 ps.installPermissionsFixed = true; 11622 } 11623 11624 // Persist the runtime permissions state for users with changes. If permissions 11625 // were revoked because no app in the shared user declares them we have to 11626 // write synchronously to avoid losing runtime permissions state. 11627 for (int userId : changedRuntimePermissionUserIds) { 11628 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11629 } 11630 } 11631 11632 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11633 boolean allowed = false; 11634 final int NP = PackageParser.NEW_PERMISSIONS.length; 11635 for (int ip=0; ip<NP; ip++) { 11636 final PackageParser.NewPermissionInfo npi 11637 = PackageParser.NEW_PERMISSIONS[ip]; 11638 if (npi.name.equals(perm) 11639 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11640 allowed = true; 11641 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11642 + pkg.packageName); 11643 break; 11644 } 11645 } 11646 return allowed; 11647 } 11648 11649 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11650 BasePermission bp, PermissionsState origPermissions) { 11651 boolean privilegedPermission = (bp.protectionLevel 11652 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11653 boolean privappPermissionsDisable = 11654 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11655 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11656 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11657 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11658 && !platformPackage && platformPermission) { 11659 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11660 .getPrivAppPermissions(pkg.packageName); 11661 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11662 if (!whitelisted) { 11663 Slog.w(TAG, "Privileged permission " + perm + " for package " 11664 + pkg.packageName + " - not in privapp-permissions whitelist"); 11665 // Only report violations for apps on system image 11666 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11667 if (mPrivappPermissionsViolations == null) { 11668 mPrivappPermissionsViolations = new ArraySet<>(); 11669 } 11670 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11671 } 11672 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11673 return false; 11674 } 11675 } 11676 } 11677 boolean allowed = (compareSignatures( 11678 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11679 == PackageManager.SIGNATURE_MATCH) 11680 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11681 == PackageManager.SIGNATURE_MATCH); 11682 if (!allowed && privilegedPermission) { 11683 if (isSystemApp(pkg)) { 11684 // For updated system applications, a system permission 11685 // is granted only if it had been defined by the original application. 11686 if (pkg.isUpdatedSystemApp()) { 11687 final PackageSetting sysPs = mSettings 11688 .getDisabledSystemPkgLPr(pkg.packageName); 11689 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11690 // If the original was granted this permission, we take 11691 // that grant decision as read and propagate it to the 11692 // update. 11693 if (sysPs.isPrivileged()) { 11694 allowed = true; 11695 } 11696 } else { 11697 // The system apk may have been updated with an older 11698 // version of the one on the data partition, but which 11699 // granted a new system permission that it didn't have 11700 // before. In this case we do want to allow the app to 11701 // now get the new permission if the ancestral apk is 11702 // privileged to get it. 11703 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11704 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11705 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11706 allowed = true; 11707 break; 11708 } 11709 } 11710 } 11711 // Also if a privileged parent package on the system image or any of 11712 // its children requested a privileged permission, the updated child 11713 // packages can also get the permission. 11714 if (pkg.parentPackage != null) { 11715 final PackageSetting disabledSysParentPs = mSettings 11716 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11717 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11718 && disabledSysParentPs.isPrivileged()) { 11719 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11720 allowed = true; 11721 } else if (disabledSysParentPs.pkg.childPackages != null) { 11722 final int count = disabledSysParentPs.pkg.childPackages.size(); 11723 for (int i = 0; i < count; i++) { 11724 PackageParser.Package disabledSysChildPkg = 11725 disabledSysParentPs.pkg.childPackages.get(i); 11726 if (isPackageRequestingPermission(disabledSysChildPkg, 11727 perm)) { 11728 allowed = true; 11729 break; 11730 } 11731 } 11732 } 11733 } 11734 } 11735 } 11736 } else { 11737 allowed = isPrivilegedApp(pkg); 11738 } 11739 } 11740 } 11741 if (!allowed) { 11742 if (!allowed && (bp.protectionLevel 11743 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11744 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11745 // If this was a previously normal/dangerous permission that got moved 11746 // to a system permission as part of the runtime permission redesign, then 11747 // we still want to blindly grant it to old apps. 11748 allowed = true; 11749 } 11750 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11751 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11752 // If this permission is to be granted to the system installer and 11753 // this app is an installer, then it gets the permission. 11754 allowed = true; 11755 } 11756 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11757 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11758 // If this permission is to be granted to the system verifier and 11759 // this app is a verifier, then it gets the permission. 11760 allowed = true; 11761 } 11762 if (!allowed && (bp.protectionLevel 11763 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11764 && isSystemApp(pkg)) { 11765 // Any pre-installed system app is allowed to get this permission. 11766 allowed = true; 11767 } 11768 if (!allowed && (bp.protectionLevel 11769 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11770 // For development permissions, a development permission 11771 // is granted only if it was already granted. 11772 allowed = origPermissions.hasInstallPermission(perm); 11773 } 11774 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11775 && pkg.packageName.equals(mSetupWizardPackage)) { 11776 // If this permission is to be granted to the system setup wizard and 11777 // this app is a setup wizard, then it gets the permission. 11778 allowed = true; 11779 } 11780 } 11781 return allowed; 11782 } 11783 11784 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11785 final int permCount = pkg.requestedPermissions.size(); 11786 for (int j = 0; j < permCount; j++) { 11787 String requestedPermission = pkg.requestedPermissions.get(j); 11788 if (permission.equals(requestedPermission)) { 11789 return true; 11790 } 11791 } 11792 return false; 11793 } 11794 11795 final class ActivityIntentResolver 11796 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11797 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11798 boolean defaultOnly, int userId) { 11799 if (!sUserManager.exists(userId)) return null; 11800 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11801 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11802 } 11803 11804 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11805 int userId) { 11806 if (!sUserManager.exists(userId)) return null; 11807 mFlags = flags; 11808 return super.queryIntent(intent, resolvedType, 11809 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11810 userId); 11811 } 11812 11813 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11814 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11815 if (!sUserManager.exists(userId)) return null; 11816 if (packageActivities == null) { 11817 return null; 11818 } 11819 mFlags = flags; 11820 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11821 final int N = packageActivities.size(); 11822 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11823 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11824 11825 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11826 for (int i = 0; i < N; ++i) { 11827 intentFilters = packageActivities.get(i).intents; 11828 if (intentFilters != null && intentFilters.size() > 0) { 11829 PackageParser.ActivityIntentInfo[] array = 11830 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11831 intentFilters.toArray(array); 11832 listCut.add(array); 11833 } 11834 } 11835 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11836 } 11837 11838 /** 11839 * Finds a privileged activity that matches the specified activity names. 11840 */ 11841 private PackageParser.Activity findMatchingActivity( 11842 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11843 for (PackageParser.Activity sysActivity : activityList) { 11844 if (sysActivity.info.name.equals(activityInfo.name)) { 11845 return sysActivity; 11846 } 11847 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11848 return sysActivity; 11849 } 11850 if (sysActivity.info.targetActivity != null) { 11851 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11852 return sysActivity; 11853 } 11854 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11855 return sysActivity; 11856 } 11857 } 11858 } 11859 return null; 11860 } 11861 11862 public class IterGenerator<E> { 11863 public Iterator<E> generate(ActivityIntentInfo info) { 11864 return null; 11865 } 11866 } 11867 11868 public class ActionIterGenerator extends IterGenerator<String> { 11869 @Override 11870 public Iterator<String> generate(ActivityIntentInfo info) { 11871 return info.actionsIterator(); 11872 } 11873 } 11874 11875 public class CategoriesIterGenerator extends IterGenerator<String> { 11876 @Override 11877 public Iterator<String> generate(ActivityIntentInfo info) { 11878 return info.categoriesIterator(); 11879 } 11880 } 11881 11882 public class SchemesIterGenerator extends IterGenerator<String> { 11883 @Override 11884 public Iterator<String> generate(ActivityIntentInfo info) { 11885 return info.schemesIterator(); 11886 } 11887 } 11888 11889 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11890 @Override 11891 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11892 return info.authoritiesIterator(); 11893 } 11894 } 11895 11896 /** 11897 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11898 * MODIFIED. Do not pass in a list that should not be changed. 11899 */ 11900 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11901 IterGenerator<T> generator, Iterator<T> searchIterator) { 11902 // loop through the set of actions; every one must be found in the intent filter 11903 while (searchIterator.hasNext()) { 11904 // we must have at least one filter in the list to consider a match 11905 if (intentList.size() == 0) { 11906 break; 11907 } 11908 11909 final T searchAction = searchIterator.next(); 11910 11911 // loop through the set of intent filters 11912 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11913 while (intentIter.hasNext()) { 11914 final ActivityIntentInfo intentInfo = intentIter.next(); 11915 boolean selectionFound = false; 11916 11917 // loop through the intent filter's selection criteria; at least one 11918 // of them must match the searched criteria 11919 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11920 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11921 final T intentSelection = intentSelectionIter.next(); 11922 if (intentSelection != null && intentSelection.equals(searchAction)) { 11923 selectionFound = true; 11924 break; 11925 } 11926 } 11927 11928 // the selection criteria wasn't found in this filter's set; this filter 11929 // is not a potential match 11930 if (!selectionFound) { 11931 intentIter.remove(); 11932 } 11933 } 11934 } 11935 } 11936 11937 private boolean isProtectedAction(ActivityIntentInfo filter) { 11938 final Iterator<String> actionsIter = filter.actionsIterator(); 11939 while (actionsIter != null && actionsIter.hasNext()) { 11940 final String filterAction = actionsIter.next(); 11941 if (PROTECTED_ACTIONS.contains(filterAction)) { 11942 return true; 11943 } 11944 } 11945 return false; 11946 } 11947 11948 /** 11949 * Adjusts the priority of the given intent filter according to policy. 11950 * <p> 11951 * <ul> 11952 * <li>The priority for non privileged applications is capped to '0'</li> 11953 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11954 * <li>The priority for unbundled updates to privileged applications is capped to the 11955 * priority defined on the system partition</li> 11956 * </ul> 11957 * <p> 11958 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11959 * allowed to obtain any priority on any action. 11960 */ 11961 private void adjustPriority( 11962 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11963 // nothing to do; priority is fine as-is 11964 if (intent.getPriority() <= 0) { 11965 return; 11966 } 11967 11968 final ActivityInfo activityInfo = intent.activity.info; 11969 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11970 11971 final boolean privilegedApp = 11972 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11973 if (!privilegedApp) { 11974 // non-privileged applications can never define a priority >0 11975 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11976 + " package: " + applicationInfo.packageName 11977 + " activity: " + intent.activity.className 11978 + " origPrio: " + intent.getPriority()); 11979 intent.setPriority(0); 11980 return; 11981 } 11982 11983 if (systemActivities == null) { 11984 // the system package is not disabled; we're parsing the system partition 11985 if (isProtectedAction(intent)) { 11986 if (mDeferProtectedFilters) { 11987 // We can't deal with these just yet. No component should ever obtain a 11988 // >0 priority for a protected actions, with ONE exception -- the setup 11989 // wizard. The setup wizard, however, cannot be known until we're able to 11990 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11991 // until all intent filters have been processed. Chicken, meet egg. 11992 // Let the filter temporarily have a high priority and rectify the 11993 // priorities after all system packages have been scanned. 11994 mProtectedFilters.add(intent); 11995 if (DEBUG_FILTERS) { 11996 Slog.i(TAG, "Protected action; save for later;" 11997 + " package: " + applicationInfo.packageName 11998 + " activity: " + intent.activity.className 11999 + " origPrio: " + intent.getPriority()); 12000 } 12001 return; 12002 } else { 12003 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12004 Slog.i(TAG, "No setup wizard;" 12005 + " All protected intents capped to priority 0"); 12006 } 12007 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12008 if (DEBUG_FILTERS) { 12009 Slog.i(TAG, "Found setup wizard;" 12010 + " allow priority " + intent.getPriority() + ";" 12011 + " package: " + intent.activity.info.packageName 12012 + " activity: " + intent.activity.className 12013 + " priority: " + intent.getPriority()); 12014 } 12015 // setup wizard gets whatever it wants 12016 return; 12017 } 12018 Slog.w(TAG, "Protected action; cap priority to 0;" 12019 + " package: " + intent.activity.info.packageName 12020 + " activity: " + intent.activity.className 12021 + " origPrio: " + intent.getPriority()); 12022 intent.setPriority(0); 12023 return; 12024 } 12025 } 12026 // privileged apps on the system image get whatever priority they request 12027 return; 12028 } 12029 12030 // privileged app unbundled update ... try to find the same activity 12031 final PackageParser.Activity foundActivity = 12032 findMatchingActivity(systemActivities, activityInfo); 12033 if (foundActivity == null) { 12034 // this is a new activity; it cannot obtain >0 priority 12035 if (DEBUG_FILTERS) { 12036 Slog.i(TAG, "New activity; cap priority to 0;" 12037 + " package: " + applicationInfo.packageName 12038 + " activity: " + intent.activity.className 12039 + " origPrio: " + intent.getPriority()); 12040 } 12041 intent.setPriority(0); 12042 return; 12043 } 12044 12045 // found activity, now check for filter equivalence 12046 12047 // a shallow copy is enough; we modify the list, not its contents 12048 final List<ActivityIntentInfo> intentListCopy = 12049 new ArrayList<>(foundActivity.intents); 12050 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12051 12052 // find matching action subsets 12053 final Iterator<String> actionsIterator = intent.actionsIterator(); 12054 if (actionsIterator != null) { 12055 getIntentListSubset( 12056 intentListCopy, new ActionIterGenerator(), actionsIterator); 12057 if (intentListCopy.size() == 0) { 12058 // no more intents to match; we're not equivalent 12059 if (DEBUG_FILTERS) { 12060 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12061 + " package: " + applicationInfo.packageName 12062 + " activity: " + intent.activity.className 12063 + " origPrio: " + intent.getPriority()); 12064 } 12065 intent.setPriority(0); 12066 return; 12067 } 12068 } 12069 12070 // find matching category subsets 12071 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12072 if (categoriesIterator != null) { 12073 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12074 categoriesIterator); 12075 if (intentListCopy.size() == 0) { 12076 // no more intents to match; we're not equivalent 12077 if (DEBUG_FILTERS) { 12078 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12079 + " package: " + applicationInfo.packageName 12080 + " activity: " + intent.activity.className 12081 + " origPrio: " + intent.getPriority()); 12082 } 12083 intent.setPriority(0); 12084 return; 12085 } 12086 } 12087 12088 // find matching schemes subsets 12089 final Iterator<String> schemesIterator = intent.schemesIterator(); 12090 if (schemesIterator != null) { 12091 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12092 schemesIterator); 12093 if (intentListCopy.size() == 0) { 12094 // no more intents to match; we're not equivalent 12095 if (DEBUG_FILTERS) { 12096 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12097 + " package: " + applicationInfo.packageName 12098 + " activity: " + intent.activity.className 12099 + " origPrio: " + intent.getPriority()); 12100 } 12101 intent.setPriority(0); 12102 return; 12103 } 12104 } 12105 12106 // find matching authorities subsets 12107 final Iterator<IntentFilter.AuthorityEntry> 12108 authoritiesIterator = intent.authoritiesIterator(); 12109 if (authoritiesIterator != null) { 12110 getIntentListSubset(intentListCopy, 12111 new AuthoritiesIterGenerator(), 12112 authoritiesIterator); 12113 if (intentListCopy.size() == 0) { 12114 // no more intents to match; we're not equivalent 12115 if (DEBUG_FILTERS) { 12116 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12117 + " package: " + applicationInfo.packageName 12118 + " activity: " + intent.activity.className 12119 + " origPrio: " + intent.getPriority()); 12120 } 12121 intent.setPriority(0); 12122 return; 12123 } 12124 } 12125 12126 // we found matching filter(s); app gets the max priority of all intents 12127 int cappedPriority = 0; 12128 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12129 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12130 } 12131 if (intent.getPriority() > cappedPriority) { 12132 if (DEBUG_FILTERS) { 12133 Slog.i(TAG, "Found matching filter(s);" 12134 + " cap priority to " + cappedPriority + ";" 12135 + " package: " + applicationInfo.packageName 12136 + " activity: " + intent.activity.className 12137 + " origPrio: " + intent.getPriority()); 12138 } 12139 intent.setPriority(cappedPriority); 12140 return; 12141 } 12142 // all this for nothing; the requested priority was <= what was on the system 12143 } 12144 12145 public final void addActivity(PackageParser.Activity a, String type) { 12146 mActivities.put(a.getComponentName(), a); 12147 if (DEBUG_SHOW_INFO) 12148 Log.v( 12149 TAG, " " + type + " " + 12150 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12151 if (DEBUG_SHOW_INFO) 12152 Log.v(TAG, " Class=" + a.info.name); 12153 final int NI = a.intents.size(); 12154 for (int j=0; j<NI; j++) { 12155 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12156 if ("activity".equals(type)) { 12157 final PackageSetting ps = 12158 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12159 final List<PackageParser.Activity> systemActivities = 12160 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12161 adjustPriority(systemActivities, intent); 12162 } 12163 if (DEBUG_SHOW_INFO) { 12164 Log.v(TAG, " IntentFilter:"); 12165 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12166 } 12167 if (!intent.debugCheck()) { 12168 Log.w(TAG, "==> For Activity " + a.info.name); 12169 } 12170 addFilter(intent); 12171 } 12172 } 12173 12174 public final void removeActivity(PackageParser.Activity a, String type) { 12175 mActivities.remove(a.getComponentName()); 12176 if (DEBUG_SHOW_INFO) { 12177 Log.v(TAG, " " + type + " " 12178 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12179 : a.info.name) + ":"); 12180 Log.v(TAG, " Class=" + a.info.name); 12181 } 12182 final int NI = a.intents.size(); 12183 for (int j=0; j<NI; j++) { 12184 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12185 if (DEBUG_SHOW_INFO) { 12186 Log.v(TAG, " IntentFilter:"); 12187 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12188 } 12189 removeFilter(intent); 12190 } 12191 } 12192 12193 @Override 12194 protected boolean allowFilterResult( 12195 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12196 ActivityInfo filterAi = filter.activity.info; 12197 for (int i=dest.size()-1; i>=0; i--) { 12198 ActivityInfo destAi = dest.get(i).activityInfo; 12199 if (destAi.name == filterAi.name 12200 && destAi.packageName == filterAi.packageName) { 12201 return false; 12202 } 12203 } 12204 return true; 12205 } 12206 12207 @Override 12208 protected ActivityIntentInfo[] newArray(int size) { 12209 return new ActivityIntentInfo[size]; 12210 } 12211 12212 @Override 12213 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12214 if (!sUserManager.exists(userId)) return true; 12215 PackageParser.Package p = filter.activity.owner; 12216 if (p != null) { 12217 PackageSetting ps = (PackageSetting)p.mExtras; 12218 if (ps != null) { 12219 // System apps are never considered stopped for purposes of 12220 // filtering, because there may be no way for the user to 12221 // actually re-launch them. 12222 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12223 && ps.getStopped(userId); 12224 } 12225 } 12226 return false; 12227 } 12228 12229 @Override 12230 protected boolean isPackageForFilter(String packageName, 12231 PackageParser.ActivityIntentInfo info) { 12232 return packageName.equals(info.activity.owner.packageName); 12233 } 12234 12235 @Override 12236 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12237 int match, int userId) { 12238 if (!sUserManager.exists(userId)) return null; 12239 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12240 return null; 12241 } 12242 final PackageParser.Activity activity = info.activity; 12243 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12244 if (ps == null) { 12245 return null; 12246 } 12247 final PackageUserState userState = ps.readUserState(userId); 12248 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12249 userState, userId); 12250 if (ai == null) { 12251 return null; 12252 } 12253 final boolean matchVisibleToInstantApp = 12254 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12255 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12256 // throw out filters that aren't visible to ephemeral apps 12257 if (matchVisibleToInstantApp 12258 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12259 return null; 12260 } 12261 // throw out ephemeral filters if we're not explicitly requesting them 12262 if (!isInstantApp && userState.instantApp) { 12263 return null; 12264 } 12265 final ResolveInfo res = new ResolveInfo(); 12266 res.activityInfo = ai; 12267 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12268 res.filter = info; 12269 } 12270 if (info != null) { 12271 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12272 } 12273 res.priority = info.getPriority(); 12274 res.preferredOrder = activity.owner.mPreferredOrder; 12275 //System.out.println("Result: " + res.activityInfo.className + 12276 // " = " + res.priority); 12277 res.match = match; 12278 res.isDefault = info.hasDefault; 12279 res.labelRes = info.labelRes; 12280 res.nonLocalizedLabel = info.nonLocalizedLabel; 12281 if (userNeedsBadging(userId)) { 12282 res.noResourceId = true; 12283 } else { 12284 res.icon = info.icon; 12285 } 12286 res.iconResourceId = info.icon; 12287 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12288 return res; 12289 } 12290 12291 @Override 12292 protected void sortResults(List<ResolveInfo> results) { 12293 Collections.sort(results, mResolvePrioritySorter); 12294 } 12295 12296 @Override 12297 protected void dumpFilter(PrintWriter out, String prefix, 12298 PackageParser.ActivityIntentInfo filter) { 12299 out.print(prefix); out.print( 12300 Integer.toHexString(System.identityHashCode(filter.activity))); 12301 out.print(' '); 12302 filter.activity.printComponentShortName(out); 12303 out.print(" filter "); 12304 out.println(Integer.toHexString(System.identityHashCode(filter))); 12305 } 12306 12307 @Override 12308 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12309 return filter.activity; 12310 } 12311 12312 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12313 PackageParser.Activity activity = (PackageParser.Activity)label; 12314 out.print(prefix); out.print( 12315 Integer.toHexString(System.identityHashCode(activity))); 12316 out.print(' '); 12317 activity.printComponentShortName(out); 12318 if (count > 1) { 12319 out.print(" ("); out.print(count); out.print(" filters)"); 12320 } 12321 out.println(); 12322 } 12323 12324 // Keys are String (activity class name), values are Activity. 12325 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12326 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12327 private int mFlags; 12328 } 12329 12330 private final class ServiceIntentResolver 12331 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12332 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12333 boolean defaultOnly, int userId) { 12334 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12335 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12336 } 12337 12338 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12339 int userId) { 12340 if (!sUserManager.exists(userId)) return null; 12341 mFlags = flags; 12342 return super.queryIntent(intent, resolvedType, 12343 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12344 userId); 12345 } 12346 12347 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12348 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12349 if (!sUserManager.exists(userId)) return null; 12350 if (packageServices == null) { 12351 return null; 12352 } 12353 mFlags = flags; 12354 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12355 final int N = packageServices.size(); 12356 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12357 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12358 12359 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12360 for (int i = 0; i < N; ++i) { 12361 intentFilters = packageServices.get(i).intents; 12362 if (intentFilters != null && intentFilters.size() > 0) { 12363 PackageParser.ServiceIntentInfo[] array = 12364 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12365 intentFilters.toArray(array); 12366 listCut.add(array); 12367 } 12368 } 12369 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12370 } 12371 12372 public final void addService(PackageParser.Service s) { 12373 mServices.put(s.getComponentName(), s); 12374 if (DEBUG_SHOW_INFO) { 12375 Log.v(TAG, " " 12376 + (s.info.nonLocalizedLabel != null 12377 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12378 Log.v(TAG, " Class=" + s.info.name); 12379 } 12380 final int NI = s.intents.size(); 12381 int j; 12382 for (j=0; j<NI; j++) { 12383 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12384 if (DEBUG_SHOW_INFO) { 12385 Log.v(TAG, " IntentFilter:"); 12386 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12387 } 12388 if (!intent.debugCheck()) { 12389 Log.w(TAG, "==> For Service " + s.info.name); 12390 } 12391 addFilter(intent); 12392 } 12393 } 12394 12395 public final void removeService(PackageParser.Service s) { 12396 mServices.remove(s.getComponentName()); 12397 if (DEBUG_SHOW_INFO) { 12398 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12399 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12400 Log.v(TAG, " Class=" + s.info.name); 12401 } 12402 final int NI = s.intents.size(); 12403 int j; 12404 for (j=0; j<NI; j++) { 12405 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12406 if (DEBUG_SHOW_INFO) { 12407 Log.v(TAG, " IntentFilter:"); 12408 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12409 } 12410 removeFilter(intent); 12411 } 12412 } 12413 12414 @Override 12415 protected boolean allowFilterResult( 12416 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12417 ServiceInfo filterSi = filter.service.info; 12418 for (int i=dest.size()-1; i>=0; i--) { 12419 ServiceInfo destAi = dest.get(i).serviceInfo; 12420 if (destAi.name == filterSi.name 12421 && destAi.packageName == filterSi.packageName) { 12422 return false; 12423 } 12424 } 12425 return true; 12426 } 12427 12428 @Override 12429 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12430 return new PackageParser.ServiceIntentInfo[size]; 12431 } 12432 12433 @Override 12434 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12435 if (!sUserManager.exists(userId)) return true; 12436 PackageParser.Package p = filter.service.owner; 12437 if (p != null) { 12438 PackageSetting ps = (PackageSetting)p.mExtras; 12439 if (ps != null) { 12440 // System apps are never considered stopped for purposes of 12441 // filtering, because there may be no way for the user to 12442 // actually re-launch them. 12443 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12444 && ps.getStopped(userId); 12445 } 12446 } 12447 return false; 12448 } 12449 12450 @Override 12451 protected boolean isPackageForFilter(String packageName, 12452 PackageParser.ServiceIntentInfo info) { 12453 return packageName.equals(info.service.owner.packageName); 12454 } 12455 12456 @Override 12457 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12458 int match, int userId) { 12459 if (!sUserManager.exists(userId)) return null; 12460 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12461 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12462 return null; 12463 } 12464 final PackageParser.Service service = info.service; 12465 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12466 if (ps == null) { 12467 return null; 12468 } 12469 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12470 ps.readUserState(userId), userId); 12471 if (si == null) { 12472 return null; 12473 } 12474 final ResolveInfo res = new ResolveInfo(); 12475 res.serviceInfo = si; 12476 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12477 res.filter = filter; 12478 } 12479 res.priority = info.getPriority(); 12480 res.preferredOrder = service.owner.mPreferredOrder; 12481 res.match = match; 12482 res.isDefault = info.hasDefault; 12483 res.labelRes = info.labelRes; 12484 res.nonLocalizedLabel = info.nonLocalizedLabel; 12485 res.icon = info.icon; 12486 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12487 return res; 12488 } 12489 12490 @Override 12491 protected void sortResults(List<ResolveInfo> results) { 12492 Collections.sort(results, mResolvePrioritySorter); 12493 } 12494 12495 @Override 12496 protected void dumpFilter(PrintWriter out, String prefix, 12497 PackageParser.ServiceIntentInfo filter) { 12498 out.print(prefix); out.print( 12499 Integer.toHexString(System.identityHashCode(filter.service))); 12500 out.print(' '); 12501 filter.service.printComponentShortName(out); 12502 out.print(" filter "); 12503 out.println(Integer.toHexString(System.identityHashCode(filter))); 12504 } 12505 12506 @Override 12507 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12508 return filter.service; 12509 } 12510 12511 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12512 PackageParser.Service service = (PackageParser.Service)label; 12513 out.print(prefix); out.print( 12514 Integer.toHexString(System.identityHashCode(service))); 12515 out.print(' '); 12516 service.printComponentShortName(out); 12517 if (count > 1) { 12518 out.print(" ("); out.print(count); out.print(" filters)"); 12519 } 12520 out.println(); 12521 } 12522 12523// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12524// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12525// final List<ResolveInfo> retList = Lists.newArrayList(); 12526// while (i.hasNext()) { 12527// final ResolveInfo resolveInfo = (ResolveInfo) i; 12528// if (isEnabledLP(resolveInfo.serviceInfo)) { 12529// retList.add(resolveInfo); 12530// } 12531// } 12532// return retList; 12533// } 12534 12535 // Keys are String (activity class name), values are Activity. 12536 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12537 = new ArrayMap<ComponentName, PackageParser.Service>(); 12538 private int mFlags; 12539 } 12540 12541 private final class ProviderIntentResolver 12542 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12543 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12544 boolean defaultOnly, int userId) { 12545 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12546 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12547 } 12548 12549 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12550 int userId) { 12551 if (!sUserManager.exists(userId)) 12552 return null; 12553 mFlags = flags; 12554 return super.queryIntent(intent, resolvedType, 12555 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12556 userId); 12557 } 12558 12559 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12560 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12561 if (!sUserManager.exists(userId)) 12562 return null; 12563 if (packageProviders == null) { 12564 return null; 12565 } 12566 mFlags = flags; 12567 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12568 final int N = packageProviders.size(); 12569 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12570 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12571 12572 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12573 for (int i = 0; i < N; ++i) { 12574 intentFilters = packageProviders.get(i).intents; 12575 if (intentFilters != null && intentFilters.size() > 0) { 12576 PackageParser.ProviderIntentInfo[] array = 12577 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12578 intentFilters.toArray(array); 12579 listCut.add(array); 12580 } 12581 } 12582 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12583 } 12584 12585 public final void addProvider(PackageParser.Provider p) { 12586 if (mProviders.containsKey(p.getComponentName())) { 12587 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12588 return; 12589 } 12590 12591 mProviders.put(p.getComponentName(), p); 12592 if (DEBUG_SHOW_INFO) { 12593 Log.v(TAG, " " 12594 + (p.info.nonLocalizedLabel != null 12595 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12596 Log.v(TAG, " Class=" + p.info.name); 12597 } 12598 final int NI = p.intents.size(); 12599 int j; 12600 for (j = 0; j < NI; j++) { 12601 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12602 if (DEBUG_SHOW_INFO) { 12603 Log.v(TAG, " IntentFilter:"); 12604 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12605 } 12606 if (!intent.debugCheck()) { 12607 Log.w(TAG, "==> For Provider " + p.info.name); 12608 } 12609 addFilter(intent); 12610 } 12611 } 12612 12613 public final void removeProvider(PackageParser.Provider p) { 12614 mProviders.remove(p.getComponentName()); 12615 if (DEBUG_SHOW_INFO) { 12616 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12617 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12618 Log.v(TAG, " Class=" + p.info.name); 12619 } 12620 final int NI = p.intents.size(); 12621 int j; 12622 for (j = 0; j < NI; j++) { 12623 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12624 if (DEBUG_SHOW_INFO) { 12625 Log.v(TAG, " IntentFilter:"); 12626 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12627 } 12628 removeFilter(intent); 12629 } 12630 } 12631 12632 @Override 12633 protected boolean allowFilterResult( 12634 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12635 ProviderInfo filterPi = filter.provider.info; 12636 for (int i = dest.size() - 1; i >= 0; i--) { 12637 ProviderInfo destPi = dest.get(i).providerInfo; 12638 if (destPi.name == filterPi.name 12639 && destPi.packageName == filterPi.packageName) { 12640 return false; 12641 } 12642 } 12643 return true; 12644 } 12645 12646 @Override 12647 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12648 return new PackageParser.ProviderIntentInfo[size]; 12649 } 12650 12651 @Override 12652 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12653 if (!sUserManager.exists(userId)) 12654 return true; 12655 PackageParser.Package p = filter.provider.owner; 12656 if (p != null) { 12657 PackageSetting ps = (PackageSetting) p.mExtras; 12658 if (ps != null) { 12659 // System apps are never considered stopped for purposes of 12660 // filtering, because there may be no way for the user to 12661 // actually re-launch them. 12662 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12663 && ps.getStopped(userId); 12664 } 12665 } 12666 return false; 12667 } 12668 12669 @Override 12670 protected boolean isPackageForFilter(String packageName, 12671 PackageParser.ProviderIntentInfo info) { 12672 return packageName.equals(info.provider.owner.packageName); 12673 } 12674 12675 @Override 12676 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12677 int match, int userId) { 12678 if (!sUserManager.exists(userId)) 12679 return null; 12680 final PackageParser.ProviderIntentInfo info = filter; 12681 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12682 return null; 12683 } 12684 final PackageParser.Provider provider = info.provider; 12685 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12686 if (ps == null) { 12687 return null; 12688 } 12689 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12690 ps.readUserState(userId), userId); 12691 if (pi == null) { 12692 return null; 12693 } 12694 final ResolveInfo res = new ResolveInfo(); 12695 res.providerInfo = pi; 12696 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12697 res.filter = filter; 12698 } 12699 res.priority = info.getPriority(); 12700 res.preferredOrder = provider.owner.mPreferredOrder; 12701 res.match = match; 12702 res.isDefault = info.hasDefault; 12703 res.labelRes = info.labelRes; 12704 res.nonLocalizedLabel = info.nonLocalizedLabel; 12705 res.icon = info.icon; 12706 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12707 return res; 12708 } 12709 12710 @Override 12711 protected void sortResults(List<ResolveInfo> results) { 12712 Collections.sort(results, mResolvePrioritySorter); 12713 } 12714 12715 @Override 12716 protected void dumpFilter(PrintWriter out, String prefix, 12717 PackageParser.ProviderIntentInfo filter) { 12718 out.print(prefix); 12719 out.print( 12720 Integer.toHexString(System.identityHashCode(filter.provider))); 12721 out.print(' '); 12722 filter.provider.printComponentShortName(out); 12723 out.print(" filter "); 12724 out.println(Integer.toHexString(System.identityHashCode(filter))); 12725 } 12726 12727 @Override 12728 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12729 return filter.provider; 12730 } 12731 12732 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12733 PackageParser.Provider provider = (PackageParser.Provider)label; 12734 out.print(prefix); out.print( 12735 Integer.toHexString(System.identityHashCode(provider))); 12736 out.print(' '); 12737 provider.printComponentShortName(out); 12738 if (count > 1) { 12739 out.print(" ("); out.print(count); out.print(" filters)"); 12740 } 12741 out.println(); 12742 } 12743 12744 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12745 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12746 private int mFlags; 12747 } 12748 12749 static final class EphemeralIntentResolver 12750 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12751 /** 12752 * The result that has the highest defined order. Ordering applies on a 12753 * per-package basis. Mapping is from package name to Pair of order and 12754 * EphemeralResolveInfo. 12755 * <p> 12756 * NOTE: This is implemented as a field variable for convenience and efficiency. 12757 * By having a field variable, we're able to track filter ordering as soon as 12758 * a non-zero order is defined. Otherwise, multiple loops across the result set 12759 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12760 * this needs to be contained entirely within {@link #filterResults()}. 12761 */ 12762 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12763 12764 @Override 12765 protected AuxiliaryResolveInfo[] newArray(int size) { 12766 return new AuxiliaryResolveInfo[size]; 12767 } 12768 12769 @Override 12770 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12771 return true; 12772 } 12773 12774 @Override 12775 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12776 int userId) { 12777 if (!sUserManager.exists(userId)) { 12778 return null; 12779 } 12780 final String packageName = responseObj.resolveInfo.getPackageName(); 12781 final Integer order = responseObj.getOrder(); 12782 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12783 mOrderResult.get(packageName); 12784 // ordering is enabled and this item's order isn't high enough 12785 if (lastOrderResult != null && lastOrderResult.first >= order) { 12786 return null; 12787 } 12788 final EphemeralResolveInfo res = responseObj.resolveInfo; 12789 if (order > 0) { 12790 // non-zero order, enable ordering 12791 mOrderResult.put(packageName, new Pair<>(order, res)); 12792 } 12793 return responseObj; 12794 } 12795 12796 @Override 12797 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12798 // only do work if ordering is enabled [most of the time it won't be] 12799 if (mOrderResult.size() == 0) { 12800 return; 12801 } 12802 int resultSize = results.size(); 12803 for (int i = 0; i < resultSize; i++) { 12804 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12805 final String packageName = info.getPackageName(); 12806 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12807 if (savedInfo == null) { 12808 // package doesn't having ordering 12809 continue; 12810 } 12811 if (savedInfo.second == info) { 12812 // circled back to the highest ordered item; remove from order list 12813 mOrderResult.remove(savedInfo); 12814 if (mOrderResult.size() == 0) { 12815 // no more ordered items 12816 break; 12817 } 12818 continue; 12819 } 12820 // item has a worse order, remove it from the result list 12821 results.remove(i); 12822 resultSize--; 12823 i--; 12824 } 12825 } 12826 } 12827 12828 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12829 new Comparator<ResolveInfo>() { 12830 public int compare(ResolveInfo r1, ResolveInfo r2) { 12831 int v1 = r1.priority; 12832 int v2 = r2.priority; 12833 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12834 if (v1 != v2) { 12835 return (v1 > v2) ? -1 : 1; 12836 } 12837 v1 = r1.preferredOrder; 12838 v2 = r2.preferredOrder; 12839 if (v1 != v2) { 12840 return (v1 > v2) ? -1 : 1; 12841 } 12842 if (r1.isDefault != r2.isDefault) { 12843 return r1.isDefault ? -1 : 1; 12844 } 12845 v1 = r1.match; 12846 v2 = r2.match; 12847 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12848 if (v1 != v2) { 12849 return (v1 > v2) ? -1 : 1; 12850 } 12851 if (r1.system != r2.system) { 12852 return r1.system ? -1 : 1; 12853 } 12854 if (r1.activityInfo != null) { 12855 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12856 } 12857 if (r1.serviceInfo != null) { 12858 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12859 } 12860 if (r1.providerInfo != null) { 12861 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12862 } 12863 return 0; 12864 } 12865 }; 12866 12867 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12868 new Comparator<ProviderInfo>() { 12869 public int compare(ProviderInfo p1, ProviderInfo p2) { 12870 final int v1 = p1.initOrder; 12871 final int v2 = p2.initOrder; 12872 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12873 } 12874 }; 12875 12876 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12877 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12878 final int[] userIds) { 12879 mHandler.post(new Runnable() { 12880 @Override 12881 public void run() { 12882 try { 12883 final IActivityManager am = ActivityManager.getService(); 12884 if (am == null) return; 12885 final int[] resolvedUserIds; 12886 if (userIds == null) { 12887 resolvedUserIds = am.getRunningUserIds(); 12888 } else { 12889 resolvedUserIds = userIds; 12890 } 12891 for (int id : resolvedUserIds) { 12892 final Intent intent = new Intent(action, 12893 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12894 if (extras != null) { 12895 intent.putExtras(extras); 12896 } 12897 if (targetPkg != null) { 12898 intent.setPackage(targetPkg); 12899 } 12900 // Modify the UID when posting to other users 12901 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12902 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12903 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12904 intent.putExtra(Intent.EXTRA_UID, uid); 12905 } 12906 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12907 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12908 if (DEBUG_BROADCASTS) { 12909 RuntimeException here = new RuntimeException("here"); 12910 here.fillInStackTrace(); 12911 Slog.d(TAG, "Sending to user " + id + ": " 12912 + intent.toShortString(false, true, false, false) 12913 + " " + intent.getExtras(), here); 12914 } 12915 am.broadcastIntent(null, intent, null, finishedReceiver, 12916 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12917 null, finishedReceiver != null, false, id); 12918 } 12919 } catch (RemoteException ex) { 12920 } 12921 } 12922 }); 12923 } 12924 12925 /** 12926 * Check if the external storage media is available. This is true if there 12927 * is a mounted external storage medium or if the external storage is 12928 * emulated. 12929 */ 12930 private boolean isExternalMediaAvailable() { 12931 return mMediaMounted || Environment.isExternalStorageEmulated(); 12932 } 12933 12934 @Override 12935 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12936 // writer 12937 synchronized (mPackages) { 12938 if (!isExternalMediaAvailable()) { 12939 // If the external storage is no longer mounted at this point, 12940 // the caller may not have been able to delete all of this 12941 // packages files and can not delete any more. Bail. 12942 return null; 12943 } 12944 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12945 if (lastPackage != null) { 12946 pkgs.remove(lastPackage); 12947 } 12948 if (pkgs.size() > 0) { 12949 return pkgs.get(0); 12950 } 12951 } 12952 return null; 12953 } 12954 12955 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12956 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12957 userId, andCode ? 1 : 0, packageName); 12958 if (mSystemReady) { 12959 msg.sendToTarget(); 12960 } else { 12961 if (mPostSystemReadyMessages == null) { 12962 mPostSystemReadyMessages = new ArrayList<>(); 12963 } 12964 mPostSystemReadyMessages.add(msg); 12965 } 12966 } 12967 12968 void startCleaningPackages() { 12969 // reader 12970 if (!isExternalMediaAvailable()) { 12971 return; 12972 } 12973 synchronized (mPackages) { 12974 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12975 return; 12976 } 12977 } 12978 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12979 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12980 IActivityManager am = ActivityManager.getService(); 12981 if (am != null) { 12982 try { 12983 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12984 UserHandle.USER_SYSTEM); 12985 } catch (RemoteException e) { 12986 } 12987 } 12988 } 12989 12990 @Override 12991 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12992 int installFlags, String installerPackageName, int userId) { 12993 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12994 12995 final int callingUid = Binder.getCallingUid(); 12996 enforceCrossUserPermission(callingUid, userId, 12997 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12998 12999 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13000 try { 13001 if (observer != null) { 13002 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13003 } 13004 } catch (RemoteException re) { 13005 } 13006 return; 13007 } 13008 13009 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13010 installFlags |= PackageManager.INSTALL_FROM_ADB; 13011 13012 } else { 13013 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13014 // about installerPackageName. 13015 13016 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13017 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13018 } 13019 13020 UserHandle user; 13021 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13022 user = UserHandle.ALL; 13023 } else { 13024 user = new UserHandle(userId); 13025 } 13026 13027 // Only system components can circumvent runtime permissions when installing. 13028 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13029 && mContext.checkCallingOrSelfPermission(Manifest.permission 13030 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13031 throw new SecurityException("You need the " 13032 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13033 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13034 } 13035 13036 final File originFile = new File(originPath); 13037 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13038 13039 final Message msg = mHandler.obtainMessage(INIT_COPY); 13040 final VerificationInfo verificationInfo = new VerificationInfo( 13041 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13042 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13043 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13044 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13045 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13046 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13047 msg.obj = params; 13048 13049 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13050 System.identityHashCode(msg.obj)); 13051 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13052 System.identityHashCode(msg.obj)); 13053 13054 mHandler.sendMessage(msg); 13055 } 13056 13057 13058 /** 13059 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13060 * it is acting on behalf on an enterprise or the user). 13061 * 13062 * Note that the ordering of the conditionals in this method is important. The checks we perform 13063 * are as follows, in this order: 13064 * 13065 * 1) If the install is being performed by a system app, we can trust the app to have set the 13066 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13067 * what it is. 13068 * 2) If the install is being performed by a device or profile owner app, the install reason 13069 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13070 * set the install reason correctly. If the app targets an older SDK version where install 13071 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13072 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13073 * 3) In all other cases, the install is being performed by a regular app that is neither part 13074 * of the system nor a device or profile owner. We have no reason to believe that this app is 13075 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13076 * set to enterprise policy and if so, change it to unknown instead. 13077 */ 13078 private int fixUpInstallReason(String installerPackageName, int installerUid, 13079 int installReason) { 13080 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13081 == PERMISSION_GRANTED) { 13082 // If the install is being performed by a system app, we trust that app to have set the 13083 // install reason correctly. 13084 return installReason; 13085 } 13086 13087 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13088 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13089 if (dpm != null) { 13090 ComponentName owner = null; 13091 try { 13092 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13093 if (owner == null) { 13094 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13095 } 13096 } catch (RemoteException e) { 13097 } 13098 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13099 // If the install is being performed by a device or profile owner, the install 13100 // reason should be enterprise policy. 13101 return PackageManager.INSTALL_REASON_POLICY; 13102 } 13103 } 13104 13105 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13106 // If the install is being performed by a regular app (i.e. neither system app nor 13107 // device or profile owner), we have no reason to believe that the app is acting on 13108 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13109 // change it to unknown instead. 13110 return PackageManager.INSTALL_REASON_UNKNOWN; 13111 } 13112 13113 // If the install is being performed by a regular app and the install reason was set to any 13114 // value but enterprise policy, leave the install reason unchanged. 13115 return installReason; 13116 } 13117 13118 void installStage(String packageName, File stagedDir, String stagedCid, 13119 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13120 String installerPackageName, int installerUid, UserHandle user, 13121 Certificate[][] certificates) { 13122 if (DEBUG_EPHEMERAL) { 13123 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13124 Slog.d(TAG, "Ephemeral install of " + packageName); 13125 } 13126 } 13127 final VerificationInfo verificationInfo = new VerificationInfo( 13128 sessionParams.originatingUri, sessionParams.referrerUri, 13129 sessionParams.originatingUid, installerUid); 13130 13131 final OriginInfo origin; 13132 if (stagedDir != null) { 13133 origin = OriginInfo.fromStagedFile(stagedDir); 13134 } else { 13135 origin = OriginInfo.fromStagedContainer(stagedCid); 13136 } 13137 13138 final Message msg = mHandler.obtainMessage(INIT_COPY); 13139 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13140 sessionParams.installReason); 13141 final InstallParams params = new InstallParams(origin, null, observer, 13142 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13143 verificationInfo, user, sessionParams.abiOverride, 13144 sessionParams.grantedRuntimePermissions, certificates, installReason); 13145 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13146 msg.obj = params; 13147 13148 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13149 System.identityHashCode(msg.obj)); 13150 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13151 System.identityHashCode(msg.obj)); 13152 13153 mHandler.sendMessage(msg); 13154 } 13155 13156 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13157 int userId) { 13158 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13159 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13160 } 13161 13162 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13163 int appId, int... userIds) { 13164 if (ArrayUtils.isEmpty(userIds)) { 13165 return; 13166 } 13167 Bundle extras = new Bundle(1); 13168 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13169 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13170 13171 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13172 packageName, extras, 0, null, null, userIds); 13173 if (isSystem) { 13174 mHandler.post(() -> { 13175 for (int userId : userIds) { 13176 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13177 } 13178 } 13179 ); 13180 } 13181 } 13182 13183 /** 13184 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13185 * automatically without needing an explicit launch. 13186 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13187 */ 13188 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13189 // If user is not running, the app didn't miss any broadcast 13190 if (!mUserManagerInternal.isUserRunning(userId)) { 13191 return; 13192 } 13193 final IActivityManager am = ActivityManager.getService(); 13194 try { 13195 // Deliver LOCKED_BOOT_COMPLETED first 13196 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13197 .setPackage(packageName); 13198 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13199 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13200 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13201 13202 // Deliver BOOT_COMPLETED only if user is unlocked 13203 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13204 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13205 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13206 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13207 } 13208 } catch (RemoteException e) { 13209 throw e.rethrowFromSystemServer(); 13210 } 13211 } 13212 13213 @Override 13214 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13215 int userId) { 13216 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13217 PackageSetting pkgSetting; 13218 final int uid = Binder.getCallingUid(); 13219 enforceCrossUserPermission(uid, userId, 13220 true /* requireFullPermission */, true /* checkShell */, 13221 "setApplicationHiddenSetting for user " + userId); 13222 13223 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13224 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13225 return false; 13226 } 13227 13228 long callingId = Binder.clearCallingIdentity(); 13229 try { 13230 boolean sendAdded = false; 13231 boolean sendRemoved = false; 13232 // writer 13233 synchronized (mPackages) { 13234 pkgSetting = mSettings.mPackages.get(packageName); 13235 if (pkgSetting == null) { 13236 return false; 13237 } 13238 // Do not allow "android" is being disabled 13239 if ("android".equals(packageName)) { 13240 Slog.w(TAG, "Cannot hide package: android"); 13241 return false; 13242 } 13243 // Cannot hide static shared libs as they are considered 13244 // a part of the using app (emulating static linking). Also 13245 // static libs are installed always on internal storage. 13246 PackageParser.Package pkg = mPackages.get(packageName); 13247 if (pkg != null && pkg.staticSharedLibName != null) { 13248 Slog.w(TAG, "Cannot hide package: " + packageName 13249 + " providing static shared library: " 13250 + pkg.staticSharedLibName); 13251 return false; 13252 } 13253 // Only allow protected packages to hide themselves. 13254 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13255 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13256 Slog.w(TAG, "Not hiding protected package: " + packageName); 13257 return false; 13258 } 13259 13260 if (pkgSetting.getHidden(userId) != hidden) { 13261 pkgSetting.setHidden(hidden, userId); 13262 mSettings.writePackageRestrictionsLPr(userId); 13263 if (hidden) { 13264 sendRemoved = true; 13265 } else { 13266 sendAdded = true; 13267 } 13268 } 13269 } 13270 if (sendAdded) { 13271 sendPackageAddedForUser(packageName, pkgSetting, userId); 13272 return true; 13273 } 13274 if (sendRemoved) { 13275 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13276 "hiding pkg"); 13277 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13278 return true; 13279 } 13280 } finally { 13281 Binder.restoreCallingIdentity(callingId); 13282 } 13283 return false; 13284 } 13285 13286 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13287 int userId) { 13288 final PackageRemovedInfo info = new PackageRemovedInfo(); 13289 info.removedPackage = packageName; 13290 info.removedUsers = new int[] {userId}; 13291 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13292 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13293 } 13294 13295 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13296 if (pkgList.length > 0) { 13297 Bundle extras = new Bundle(1); 13298 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13299 13300 sendPackageBroadcast( 13301 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13302 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13303 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13304 new int[] {userId}); 13305 } 13306 } 13307 13308 /** 13309 * Returns true if application is not found or there was an error. Otherwise it returns 13310 * the hidden state of the package for the given user. 13311 */ 13312 @Override 13313 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13314 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13315 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13316 true /* requireFullPermission */, false /* checkShell */, 13317 "getApplicationHidden for user " + userId); 13318 PackageSetting pkgSetting; 13319 long callingId = Binder.clearCallingIdentity(); 13320 try { 13321 // writer 13322 synchronized (mPackages) { 13323 pkgSetting = mSettings.mPackages.get(packageName); 13324 if (pkgSetting == null) { 13325 return true; 13326 } 13327 return pkgSetting.getHidden(userId); 13328 } 13329 } finally { 13330 Binder.restoreCallingIdentity(callingId); 13331 } 13332 } 13333 13334 /** 13335 * @hide 13336 */ 13337 @Override 13338 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13339 int installReason) { 13340 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13341 null); 13342 PackageSetting pkgSetting; 13343 final int uid = Binder.getCallingUid(); 13344 enforceCrossUserPermission(uid, userId, 13345 true /* requireFullPermission */, true /* checkShell */, 13346 "installExistingPackage for user " + userId); 13347 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13348 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13349 } 13350 13351 long callingId = Binder.clearCallingIdentity(); 13352 try { 13353 boolean installed = false; 13354 final boolean instantApp = 13355 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13356 final boolean fullApp = 13357 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13358 13359 // writer 13360 synchronized (mPackages) { 13361 pkgSetting = mSettings.mPackages.get(packageName); 13362 if (pkgSetting == null) { 13363 return PackageManager.INSTALL_FAILED_INVALID_URI; 13364 } 13365 if (!pkgSetting.getInstalled(userId)) { 13366 pkgSetting.setInstalled(true, userId); 13367 pkgSetting.setHidden(false, userId); 13368 pkgSetting.setInstallReason(installReason, userId); 13369 mSettings.writePackageRestrictionsLPr(userId); 13370 mSettings.writeKernelMappingLPr(pkgSetting); 13371 installed = true; 13372 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13373 // upgrade app from instant to full; we don't allow app downgrade 13374 installed = true; 13375 } 13376 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13377 } 13378 13379 if (installed) { 13380 if (pkgSetting.pkg != null) { 13381 synchronized (mInstallLock) { 13382 // We don't need to freeze for a brand new install 13383 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13384 } 13385 } 13386 sendPackageAddedForUser(packageName, pkgSetting, userId); 13387 synchronized (mPackages) { 13388 updateSequenceNumberLP(packageName, new int[]{ userId }); 13389 } 13390 } 13391 } finally { 13392 Binder.restoreCallingIdentity(callingId); 13393 } 13394 13395 return PackageManager.INSTALL_SUCCEEDED; 13396 } 13397 13398 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13399 boolean instantApp, boolean fullApp) { 13400 // no state specified; do nothing 13401 if (!instantApp && !fullApp) { 13402 return; 13403 } 13404 if (userId != UserHandle.USER_ALL) { 13405 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13406 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13407 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13408 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13409 } 13410 } else { 13411 for (int currentUserId : sUserManager.getUserIds()) { 13412 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13413 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13414 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13415 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13416 } 13417 } 13418 } 13419 } 13420 13421 boolean isUserRestricted(int userId, String restrictionKey) { 13422 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13423 if (restrictions.getBoolean(restrictionKey, false)) { 13424 Log.w(TAG, "User is restricted: " + restrictionKey); 13425 return true; 13426 } 13427 return false; 13428 } 13429 13430 @Override 13431 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13432 int userId) { 13433 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13434 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13435 true /* requireFullPermission */, true /* checkShell */, 13436 "setPackagesSuspended for user " + userId); 13437 13438 if (ArrayUtils.isEmpty(packageNames)) { 13439 return packageNames; 13440 } 13441 13442 // List of package names for whom the suspended state has changed. 13443 List<String> changedPackages = new ArrayList<>(packageNames.length); 13444 // List of package names for whom the suspended state is not set as requested in this 13445 // method. 13446 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13447 long callingId = Binder.clearCallingIdentity(); 13448 try { 13449 for (int i = 0; i < packageNames.length; i++) { 13450 String packageName = packageNames[i]; 13451 boolean changed = false; 13452 final int appId; 13453 synchronized (mPackages) { 13454 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13455 if (pkgSetting == null) { 13456 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13457 + "\". Skipping suspending/un-suspending."); 13458 unactionedPackages.add(packageName); 13459 continue; 13460 } 13461 appId = pkgSetting.appId; 13462 if (pkgSetting.getSuspended(userId) != suspended) { 13463 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13464 unactionedPackages.add(packageName); 13465 continue; 13466 } 13467 pkgSetting.setSuspended(suspended, userId); 13468 mSettings.writePackageRestrictionsLPr(userId); 13469 changed = true; 13470 changedPackages.add(packageName); 13471 } 13472 } 13473 13474 if (changed && suspended) { 13475 killApplication(packageName, UserHandle.getUid(userId, appId), 13476 "suspending package"); 13477 } 13478 } 13479 } finally { 13480 Binder.restoreCallingIdentity(callingId); 13481 } 13482 13483 if (!changedPackages.isEmpty()) { 13484 sendPackagesSuspendedForUser(changedPackages.toArray( 13485 new String[changedPackages.size()]), userId, suspended); 13486 } 13487 13488 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13489 } 13490 13491 @Override 13492 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13493 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13494 true /* requireFullPermission */, false /* checkShell */, 13495 "isPackageSuspendedForUser for user " + userId); 13496 synchronized (mPackages) { 13497 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13498 if (pkgSetting == null) { 13499 throw new IllegalArgumentException("Unknown target package: " + packageName); 13500 } 13501 return pkgSetting.getSuspended(userId); 13502 } 13503 } 13504 13505 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13506 if (isPackageDeviceAdmin(packageName, userId)) { 13507 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13508 + "\": has an active device admin"); 13509 return false; 13510 } 13511 13512 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13513 if (packageName.equals(activeLauncherPackageName)) { 13514 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13515 + "\": contains the active launcher"); 13516 return false; 13517 } 13518 13519 if (packageName.equals(mRequiredInstallerPackage)) { 13520 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13521 + "\": required for package installation"); 13522 return false; 13523 } 13524 13525 if (packageName.equals(mRequiredUninstallerPackage)) { 13526 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13527 + "\": required for package uninstallation"); 13528 return false; 13529 } 13530 13531 if (packageName.equals(mRequiredVerifierPackage)) { 13532 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13533 + "\": required for package verification"); 13534 return false; 13535 } 13536 13537 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13538 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13539 + "\": is the default dialer"); 13540 return false; 13541 } 13542 13543 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13544 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13545 + "\": protected package"); 13546 return false; 13547 } 13548 13549 // Cannot suspend static shared libs as they are considered 13550 // a part of the using app (emulating static linking). Also 13551 // static libs are installed always on internal storage. 13552 PackageParser.Package pkg = mPackages.get(packageName); 13553 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13554 Slog.w(TAG, "Cannot suspend package: " + packageName 13555 + " providing static shared library: " 13556 + pkg.staticSharedLibName); 13557 return false; 13558 } 13559 13560 return true; 13561 } 13562 13563 private String getActiveLauncherPackageName(int userId) { 13564 Intent intent = new Intent(Intent.ACTION_MAIN); 13565 intent.addCategory(Intent.CATEGORY_HOME); 13566 ResolveInfo resolveInfo = resolveIntent( 13567 intent, 13568 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13569 PackageManager.MATCH_DEFAULT_ONLY, 13570 userId); 13571 13572 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13573 } 13574 13575 private String getDefaultDialerPackageName(int userId) { 13576 synchronized (mPackages) { 13577 return mSettings.getDefaultDialerPackageNameLPw(userId); 13578 } 13579 } 13580 13581 @Override 13582 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13583 mContext.enforceCallingOrSelfPermission( 13584 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13585 "Only package verification agents can verify applications"); 13586 13587 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13588 final PackageVerificationResponse response = new PackageVerificationResponse( 13589 verificationCode, Binder.getCallingUid()); 13590 msg.arg1 = id; 13591 msg.obj = response; 13592 mHandler.sendMessage(msg); 13593 } 13594 13595 @Override 13596 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13597 long millisecondsToDelay) { 13598 mContext.enforceCallingOrSelfPermission( 13599 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13600 "Only package verification agents can extend verification timeouts"); 13601 13602 final PackageVerificationState state = mPendingVerification.get(id); 13603 final PackageVerificationResponse response = new PackageVerificationResponse( 13604 verificationCodeAtTimeout, Binder.getCallingUid()); 13605 13606 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13607 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13608 } 13609 if (millisecondsToDelay < 0) { 13610 millisecondsToDelay = 0; 13611 } 13612 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13613 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13614 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13615 } 13616 13617 if ((state != null) && !state.timeoutExtended()) { 13618 state.extendTimeout(); 13619 13620 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13621 msg.arg1 = id; 13622 msg.obj = response; 13623 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13624 } 13625 } 13626 13627 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13628 int verificationCode, UserHandle user) { 13629 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13630 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13631 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13632 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13633 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13634 13635 mContext.sendBroadcastAsUser(intent, user, 13636 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13637 } 13638 13639 private ComponentName matchComponentForVerifier(String packageName, 13640 List<ResolveInfo> receivers) { 13641 ActivityInfo targetReceiver = null; 13642 13643 final int NR = receivers.size(); 13644 for (int i = 0; i < NR; i++) { 13645 final ResolveInfo info = receivers.get(i); 13646 if (info.activityInfo == null) { 13647 continue; 13648 } 13649 13650 if (packageName.equals(info.activityInfo.packageName)) { 13651 targetReceiver = info.activityInfo; 13652 break; 13653 } 13654 } 13655 13656 if (targetReceiver == null) { 13657 return null; 13658 } 13659 13660 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13661 } 13662 13663 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13664 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13665 if (pkgInfo.verifiers.length == 0) { 13666 return null; 13667 } 13668 13669 final int N = pkgInfo.verifiers.length; 13670 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13671 for (int i = 0; i < N; i++) { 13672 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13673 13674 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13675 receivers); 13676 if (comp == null) { 13677 continue; 13678 } 13679 13680 final int verifierUid = getUidForVerifier(verifierInfo); 13681 if (verifierUid == -1) { 13682 continue; 13683 } 13684 13685 if (DEBUG_VERIFY) { 13686 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13687 + " with the correct signature"); 13688 } 13689 sufficientVerifiers.add(comp); 13690 verificationState.addSufficientVerifier(verifierUid); 13691 } 13692 13693 return sufficientVerifiers; 13694 } 13695 13696 private int getUidForVerifier(VerifierInfo verifierInfo) { 13697 synchronized (mPackages) { 13698 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13699 if (pkg == null) { 13700 return -1; 13701 } else if (pkg.mSignatures.length != 1) { 13702 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13703 + " has more than one signature; ignoring"); 13704 return -1; 13705 } 13706 13707 /* 13708 * If the public key of the package's signature does not match 13709 * our expected public key, then this is a different package and 13710 * we should skip. 13711 */ 13712 13713 final byte[] expectedPublicKey; 13714 try { 13715 final Signature verifierSig = pkg.mSignatures[0]; 13716 final PublicKey publicKey = verifierSig.getPublicKey(); 13717 expectedPublicKey = publicKey.getEncoded(); 13718 } catch (CertificateException e) { 13719 return -1; 13720 } 13721 13722 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13723 13724 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13725 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13726 + " does not have the expected public key; ignoring"); 13727 return -1; 13728 } 13729 13730 return pkg.applicationInfo.uid; 13731 } 13732 } 13733 13734 @Override 13735 public void finishPackageInstall(int token, boolean didLaunch) { 13736 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13737 13738 if (DEBUG_INSTALL) { 13739 Slog.v(TAG, "BM finishing package install for " + token); 13740 } 13741 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13742 13743 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13744 mHandler.sendMessage(msg); 13745 } 13746 13747 /** 13748 * Get the verification agent timeout. 13749 * 13750 * @return verification timeout in milliseconds 13751 */ 13752 private long getVerificationTimeout() { 13753 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13754 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13755 DEFAULT_VERIFICATION_TIMEOUT); 13756 } 13757 13758 /** 13759 * Get the default verification agent response code. 13760 * 13761 * @return default verification response code 13762 */ 13763 private int getDefaultVerificationResponse() { 13764 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13765 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13766 DEFAULT_VERIFICATION_RESPONSE); 13767 } 13768 13769 /** 13770 * Check whether or not package verification has been enabled. 13771 * 13772 * @return true if verification should be performed 13773 */ 13774 private boolean isVerificationEnabled(int userId, int installFlags) { 13775 if (!DEFAULT_VERIFY_ENABLE) { 13776 return false; 13777 } 13778 // Ephemeral apps don't get the full verification treatment 13779 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13780 if (DEBUG_EPHEMERAL) { 13781 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13782 } 13783 return false; 13784 } 13785 13786 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13787 13788 // Check if installing from ADB 13789 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13790 // Do not run verification in a test harness environment 13791 if (ActivityManager.isRunningInTestHarness()) { 13792 return false; 13793 } 13794 if (ensureVerifyAppsEnabled) { 13795 return true; 13796 } 13797 // Check if the developer does not want package verification for ADB installs 13798 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13799 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13800 return false; 13801 } 13802 } 13803 13804 if (ensureVerifyAppsEnabled) { 13805 return true; 13806 } 13807 13808 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13809 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13810 } 13811 13812 @Override 13813 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13814 throws RemoteException { 13815 mContext.enforceCallingOrSelfPermission( 13816 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13817 "Only intentfilter verification agents can verify applications"); 13818 13819 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13820 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13821 Binder.getCallingUid(), verificationCode, failedDomains); 13822 msg.arg1 = id; 13823 msg.obj = response; 13824 mHandler.sendMessage(msg); 13825 } 13826 13827 @Override 13828 public int getIntentVerificationStatus(String packageName, int userId) { 13829 synchronized (mPackages) { 13830 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13831 } 13832 } 13833 13834 @Override 13835 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13836 mContext.enforceCallingOrSelfPermission( 13837 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13838 13839 boolean result = false; 13840 synchronized (mPackages) { 13841 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13842 } 13843 if (result) { 13844 scheduleWritePackageRestrictionsLocked(userId); 13845 } 13846 return result; 13847 } 13848 13849 @Override 13850 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13851 String packageName) { 13852 synchronized (mPackages) { 13853 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13854 } 13855 } 13856 13857 @Override 13858 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13859 if (TextUtils.isEmpty(packageName)) { 13860 return ParceledListSlice.emptyList(); 13861 } 13862 synchronized (mPackages) { 13863 PackageParser.Package pkg = mPackages.get(packageName); 13864 if (pkg == null || pkg.activities == null) { 13865 return ParceledListSlice.emptyList(); 13866 } 13867 final int count = pkg.activities.size(); 13868 ArrayList<IntentFilter> result = new ArrayList<>(); 13869 for (int n=0; n<count; n++) { 13870 PackageParser.Activity activity = pkg.activities.get(n); 13871 if (activity.intents != null && activity.intents.size() > 0) { 13872 result.addAll(activity.intents); 13873 } 13874 } 13875 return new ParceledListSlice<>(result); 13876 } 13877 } 13878 13879 @Override 13880 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13881 mContext.enforceCallingOrSelfPermission( 13882 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13883 13884 synchronized (mPackages) { 13885 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13886 if (packageName != null) { 13887 result |= updateIntentVerificationStatus(packageName, 13888 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13889 userId); 13890 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13891 packageName, userId); 13892 } 13893 return result; 13894 } 13895 } 13896 13897 @Override 13898 public String getDefaultBrowserPackageName(int userId) { 13899 synchronized (mPackages) { 13900 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13901 } 13902 } 13903 13904 /** 13905 * Get the "allow unknown sources" setting. 13906 * 13907 * @return the current "allow unknown sources" setting 13908 */ 13909 private int getUnknownSourcesSettings() { 13910 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13911 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13912 -1); 13913 } 13914 13915 @Override 13916 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13917 final int uid = Binder.getCallingUid(); 13918 // writer 13919 synchronized (mPackages) { 13920 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13921 if (targetPackageSetting == null) { 13922 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13923 } 13924 13925 PackageSetting installerPackageSetting; 13926 if (installerPackageName != null) { 13927 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13928 if (installerPackageSetting == null) { 13929 throw new IllegalArgumentException("Unknown installer package: " 13930 + installerPackageName); 13931 } 13932 } else { 13933 installerPackageSetting = null; 13934 } 13935 13936 Signature[] callerSignature; 13937 Object obj = mSettings.getUserIdLPr(uid); 13938 if (obj != null) { 13939 if (obj instanceof SharedUserSetting) { 13940 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13941 } else if (obj instanceof PackageSetting) { 13942 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13943 } else { 13944 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13945 } 13946 } else { 13947 throw new SecurityException("Unknown calling UID: " + uid); 13948 } 13949 13950 // Verify: can't set installerPackageName to a package that is 13951 // not signed with the same cert as the caller. 13952 if (installerPackageSetting != null) { 13953 if (compareSignatures(callerSignature, 13954 installerPackageSetting.signatures.mSignatures) 13955 != PackageManager.SIGNATURE_MATCH) { 13956 throw new SecurityException( 13957 "Caller does not have same cert as new installer package " 13958 + installerPackageName); 13959 } 13960 } 13961 13962 // Verify: if target already has an installer package, it must 13963 // be signed with the same cert as the caller. 13964 if (targetPackageSetting.installerPackageName != null) { 13965 PackageSetting setting = mSettings.mPackages.get( 13966 targetPackageSetting.installerPackageName); 13967 // If the currently set package isn't valid, then it's always 13968 // okay to change it. 13969 if (setting != null) { 13970 if (compareSignatures(callerSignature, 13971 setting.signatures.mSignatures) 13972 != PackageManager.SIGNATURE_MATCH) { 13973 throw new SecurityException( 13974 "Caller does not have same cert as old installer package " 13975 + targetPackageSetting.installerPackageName); 13976 } 13977 } 13978 } 13979 13980 // Okay! 13981 targetPackageSetting.installerPackageName = installerPackageName; 13982 if (installerPackageName != null) { 13983 mSettings.mInstallerPackages.add(installerPackageName); 13984 } 13985 scheduleWriteSettingsLocked(); 13986 } 13987 } 13988 13989 @Override 13990 public void setApplicationCategoryHint(String packageName, int categoryHint, 13991 String callerPackageName) { 13992 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13993 callerPackageName); 13994 synchronized (mPackages) { 13995 PackageSetting ps = mSettings.mPackages.get(packageName); 13996 if (ps == null) { 13997 throw new IllegalArgumentException("Unknown target package " + packageName); 13998 } 13999 14000 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14001 throw new IllegalArgumentException("Calling package " + callerPackageName 14002 + " is not installer for " + packageName); 14003 } 14004 14005 if (ps.categoryHint != categoryHint) { 14006 ps.categoryHint = categoryHint; 14007 scheduleWriteSettingsLocked(); 14008 } 14009 } 14010 } 14011 14012 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14013 // Queue up an async operation since the package installation may take a little while. 14014 mHandler.post(new Runnable() { 14015 public void run() { 14016 mHandler.removeCallbacks(this); 14017 // Result object to be returned 14018 PackageInstalledInfo res = new PackageInstalledInfo(); 14019 res.setReturnCode(currentStatus); 14020 res.uid = -1; 14021 res.pkg = null; 14022 res.removedInfo = null; 14023 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14024 args.doPreInstall(res.returnCode); 14025 synchronized (mInstallLock) { 14026 installPackageTracedLI(args, res); 14027 } 14028 args.doPostInstall(res.returnCode, res.uid); 14029 } 14030 14031 // A restore should be performed at this point if (a) the install 14032 // succeeded, (b) the operation is not an update, and (c) the new 14033 // package has not opted out of backup participation. 14034 final boolean update = res.removedInfo != null 14035 && res.removedInfo.removedPackage != null; 14036 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14037 boolean doRestore = !update 14038 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14039 14040 // Set up the post-install work request bookkeeping. This will be used 14041 // and cleaned up by the post-install event handling regardless of whether 14042 // there's a restore pass performed. Token values are >= 1. 14043 int token; 14044 if (mNextInstallToken < 0) mNextInstallToken = 1; 14045 token = mNextInstallToken++; 14046 14047 PostInstallData data = new PostInstallData(args, res); 14048 mRunningInstalls.put(token, data); 14049 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14050 14051 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14052 // Pass responsibility to the Backup Manager. It will perform a 14053 // restore if appropriate, then pass responsibility back to the 14054 // Package Manager to run the post-install observer callbacks 14055 // and broadcasts. 14056 IBackupManager bm = IBackupManager.Stub.asInterface( 14057 ServiceManager.getService(Context.BACKUP_SERVICE)); 14058 if (bm != null) { 14059 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14060 + " to BM for possible restore"); 14061 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14062 try { 14063 // TODO: http://b/22388012 14064 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14065 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14066 } else { 14067 doRestore = false; 14068 } 14069 } catch (RemoteException e) { 14070 // can't happen; the backup manager is local 14071 } catch (Exception e) { 14072 Slog.e(TAG, "Exception trying to enqueue restore", e); 14073 doRestore = false; 14074 } 14075 } else { 14076 Slog.e(TAG, "Backup Manager not found!"); 14077 doRestore = false; 14078 } 14079 } 14080 14081 if (!doRestore) { 14082 // No restore possible, or the Backup Manager was mysteriously not 14083 // available -- just fire the post-install work request directly. 14084 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14085 14086 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14087 14088 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14089 mHandler.sendMessage(msg); 14090 } 14091 } 14092 }); 14093 } 14094 14095 /** 14096 * Callback from PackageSettings whenever an app is first transitioned out of the 14097 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14098 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14099 * here whether the app is the target of an ongoing install, and only send the 14100 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14101 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14102 * handling. 14103 */ 14104 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14105 // Serialize this with the rest of the install-process message chain. In the 14106 // restore-at-install case, this Runnable will necessarily run before the 14107 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14108 // are coherent. In the non-restore case, the app has already completed install 14109 // and been launched through some other means, so it is not in a problematic 14110 // state for observers to see the FIRST_LAUNCH signal. 14111 mHandler.post(new Runnable() { 14112 @Override 14113 public void run() { 14114 for (int i = 0; i < mRunningInstalls.size(); i++) { 14115 final PostInstallData data = mRunningInstalls.valueAt(i); 14116 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14117 continue; 14118 } 14119 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14120 // right package; but is it for the right user? 14121 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14122 if (userId == data.res.newUsers[uIndex]) { 14123 if (DEBUG_BACKUP) { 14124 Slog.i(TAG, "Package " + pkgName 14125 + " being restored so deferring FIRST_LAUNCH"); 14126 } 14127 return; 14128 } 14129 } 14130 } 14131 } 14132 // didn't find it, so not being restored 14133 if (DEBUG_BACKUP) { 14134 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14135 } 14136 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14137 } 14138 }); 14139 } 14140 14141 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14142 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14143 installerPkg, null, userIds); 14144 } 14145 14146 private abstract class HandlerParams { 14147 private static final int MAX_RETRIES = 4; 14148 14149 /** 14150 * Number of times startCopy() has been attempted and had a non-fatal 14151 * error. 14152 */ 14153 private int mRetries = 0; 14154 14155 /** User handle for the user requesting the information or installation. */ 14156 private final UserHandle mUser; 14157 String traceMethod; 14158 int traceCookie; 14159 14160 HandlerParams(UserHandle user) { 14161 mUser = user; 14162 } 14163 14164 UserHandle getUser() { 14165 return mUser; 14166 } 14167 14168 HandlerParams setTraceMethod(String traceMethod) { 14169 this.traceMethod = traceMethod; 14170 return this; 14171 } 14172 14173 HandlerParams setTraceCookie(int traceCookie) { 14174 this.traceCookie = traceCookie; 14175 return this; 14176 } 14177 14178 final boolean startCopy() { 14179 boolean res; 14180 try { 14181 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14182 14183 if (++mRetries > MAX_RETRIES) { 14184 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14185 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14186 handleServiceError(); 14187 return false; 14188 } else { 14189 handleStartCopy(); 14190 res = true; 14191 } 14192 } catch (RemoteException e) { 14193 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14194 mHandler.sendEmptyMessage(MCS_RECONNECT); 14195 res = false; 14196 } 14197 handleReturnCode(); 14198 return res; 14199 } 14200 14201 final void serviceError() { 14202 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14203 handleServiceError(); 14204 handleReturnCode(); 14205 } 14206 14207 abstract void handleStartCopy() throws RemoteException; 14208 abstract void handleServiceError(); 14209 abstract void handleReturnCode(); 14210 } 14211 14212 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14213 for (File path : paths) { 14214 try { 14215 mcs.clearDirectory(path.getAbsolutePath()); 14216 } catch (RemoteException e) { 14217 } 14218 } 14219 } 14220 14221 static class OriginInfo { 14222 /** 14223 * Location where install is coming from, before it has been 14224 * copied/renamed into place. This could be a single monolithic APK 14225 * file, or a cluster directory. This location may be untrusted. 14226 */ 14227 final File file; 14228 final String cid; 14229 14230 /** 14231 * Flag indicating that {@link #file} or {@link #cid} has already been 14232 * staged, meaning downstream users don't need to defensively copy the 14233 * contents. 14234 */ 14235 final boolean staged; 14236 14237 /** 14238 * Flag indicating that {@link #file} or {@link #cid} is an already 14239 * installed app that is being moved. 14240 */ 14241 final boolean existing; 14242 14243 final String resolvedPath; 14244 final File resolvedFile; 14245 14246 static OriginInfo fromNothing() { 14247 return new OriginInfo(null, null, false, false); 14248 } 14249 14250 static OriginInfo fromUntrustedFile(File file) { 14251 return new OriginInfo(file, null, false, false); 14252 } 14253 14254 static OriginInfo fromExistingFile(File file) { 14255 return new OriginInfo(file, null, false, true); 14256 } 14257 14258 static OriginInfo fromStagedFile(File file) { 14259 return new OriginInfo(file, null, true, false); 14260 } 14261 14262 static OriginInfo fromStagedContainer(String cid) { 14263 return new OriginInfo(null, cid, true, false); 14264 } 14265 14266 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14267 this.file = file; 14268 this.cid = cid; 14269 this.staged = staged; 14270 this.existing = existing; 14271 14272 if (cid != null) { 14273 resolvedPath = PackageHelper.getSdDir(cid); 14274 resolvedFile = new File(resolvedPath); 14275 } else if (file != null) { 14276 resolvedPath = file.getAbsolutePath(); 14277 resolvedFile = file; 14278 } else { 14279 resolvedPath = null; 14280 resolvedFile = null; 14281 } 14282 } 14283 } 14284 14285 static class MoveInfo { 14286 final int moveId; 14287 final String fromUuid; 14288 final String toUuid; 14289 final String packageName; 14290 final String dataAppName; 14291 final int appId; 14292 final String seinfo; 14293 final int targetSdkVersion; 14294 14295 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14296 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14297 this.moveId = moveId; 14298 this.fromUuid = fromUuid; 14299 this.toUuid = toUuid; 14300 this.packageName = packageName; 14301 this.dataAppName = dataAppName; 14302 this.appId = appId; 14303 this.seinfo = seinfo; 14304 this.targetSdkVersion = targetSdkVersion; 14305 } 14306 } 14307 14308 static class VerificationInfo { 14309 /** A constant used to indicate that a uid value is not present. */ 14310 public static final int NO_UID = -1; 14311 14312 /** URI referencing where the package was downloaded from. */ 14313 final Uri originatingUri; 14314 14315 /** HTTP referrer URI associated with the originatingURI. */ 14316 final Uri referrer; 14317 14318 /** UID of the application that the install request originated from. */ 14319 final int originatingUid; 14320 14321 /** UID of application requesting the install */ 14322 final int installerUid; 14323 14324 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14325 this.originatingUri = originatingUri; 14326 this.referrer = referrer; 14327 this.originatingUid = originatingUid; 14328 this.installerUid = installerUid; 14329 } 14330 } 14331 14332 class InstallParams extends HandlerParams { 14333 final OriginInfo origin; 14334 final MoveInfo move; 14335 final IPackageInstallObserver2 observer; 14336 int installFlags; 14337 final String installerPackageName; 14338 final String volumeUuid; 14339 private InstallArgs mArgs; 14340 private int mRet; 14341 final String packageAbiOverride; 14342 final String[] grantedRuntimePermissions; 14343 final VerificationInfo verificationInfo; 14344 final Certificate[][] certificates; 14345 final int installReason; 14346 14347 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14348 int installFlags, String installerPackageName, String volumeUuid, 14349 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14350 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14351 super(user); 14352 this.origin = origin; 14353 this.move = move; 14354 this.observer = observer; 14355 this.installFlags = installFlags; 14356 this.installerPackageName = installerPackageName; 14357 this.volumeUuid = volumeUuid; 14358 this.verificationInfo = verificationInfo; 14359 this.packageAbiOverride = packageAbiOverride; 14360 this.grantedRuntimePermissions = grantedPermissions; 14361 this.certificates = certificates; 14362 this.installReason = installReason; 14363 } 14364 14365 @Override 14366 public String toString() { 14367 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14368 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14369 } 14370 14371 private int installLocationPolicy(PackageInfoLite pkgLite) { 14372 String packageName = pkgLite.packageName; 14373 int installLocation = pkgLite.installLocation; 14374 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14375 // reader 14376 synchronized (mPackages) { 14377 // Currently installed package which the new package is attempting to replace or 14378 // null if no such package is installed. 14379 PackageParser.Package installedPkg = mPackages.get(packageName); 14380 // Package which currently owns the data which the new package will own if installed. 14381 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14382 // will be null whereas dataOwnerPkg will contain information about the package 14383 // which was uninstalled while keeping its data. 14384 PackageParser.Package dataOwnerPkg = installedPkg; 14385 if (dataOwnerPkg == null) { 14386 PackageSetting ps = mSettings.mPackages.get(packageName); 14387 if (ps != null) { 14388 dataOwnerPkg = ps.pkg; 14389 } 14390 } 14391 14392 if (dataOwnerPkg != null) { 14393 // If installed, the package will get access to data left on the device by its 14394 // predecessor. As a security measure, this is permited only if this is not a 14395 // version downgrade or if the predecessor package is marked as debuggable and 14396 // a downgrade is explicitly requested. 14397 // 14398 // On debuggable platform builds, downgrades are permitted even for 14399 // non-debuggable packages to make testing easier. Debuggable platform builds do 14400 // not offer security guarantees and thus it's OK to disable some security 14401 // mechanisms to make debugging/testing easier on those builds. However, even on 14402 // debuggable builds downgrades of packages are permitted only if requested via 14403 // installFlags. This is because we aim to keep the behavior of debuggable 14404 // platform builds as close as possible to the behavior of non-debuggable 14405 // platform builds. 14406 final boolean downgradeRequested = 14407 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14408 final boolean packageDebuggable = 14409 (dataOwnerPkg.applicationInfo.flags 14410 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14411 final boolean downgradePermitted = 14412 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14413 if (!downgradePermitted) { 14414 try { 14415 checkDowngrade(dataOwnerPkg, pkgLite); 14416 } catch (PackageManagerException e) { 14417 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14418 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14419 } 14420 } 14421 } 14422 14423 if (installedPkg != null) { 14424 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14425 // Check for updated system application. 14426 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14427 if (onSd) { 14428 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14429 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14430 } 14431 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14432 } else { 14433 if (onSd) { 14434 // Install flag overrides everything. 14435 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14436 } 14437 // If current upgrade specifies particular preference 14438 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14439 // Application explicitly specified internal. 14440 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14441 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14442 // App explictly prefers external. Let policy decide 14443 } else { 14444 // Prefer previous location 14445 if (isExternal(installedPkg)) { 14446 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14447 } 14448 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14449 } 14450 } 14451 } else { 14452 // Invalid install. Return error code 14453 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14454 } 14455 } 14456 } 14457 // All the special cases have been taken care of. 14458 // Return result based on recommended install location. 14459 if (onSd) { 14460 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14461 } 14462 return pkgLite.recommendedInstallLocation; 14463 } 14464 14465 /* 14466 * Invoke remote method to get package information and install 14467 * location values. Override install location based on default 14468 * policy if needed and then create install arguments based 14469 * on the install location. 14470 */ 14471 public void handleStartCopy() throws RemoteException { 14472 int ret = PackageManager.INSTALL_SUCCEEDED; 14473 14474 // If we're already staged, we've firmly committed to an install location 14475 if (origin.staged) { 14476 if (origin.file != null) { 14477 installFlags |= PackageManager.INSTALL_INTERNAL; 14478 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14479 } else if (origin.cid != null) { 14480 installFlags |= PackageManager.INSTALL_EXTERNAL; 14481 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14482 } else { 14483 throw new IllegalStateException("Invalid stage location"); 14484 } 14485 } 14486 14487 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14488 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14489 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14490 PackageInfoLite pkgLite = null; 14491 14492 if (onInt && onSd) { 14493 // Check if both bits are set. 14494 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14495 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14496 } else if (onSd && ephemeral) { 14497 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14498 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14499 } else { 14500 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14501 packageAbiOverride); 14502 14503 if (DEBUG_EPHEMERAL && ephemeral) { 14504 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14505 } 14506 14507 /* 14508 * If we have too little free space, try to free cache 14509 * before giving up. 14510 */ 14511 if (!origin.staged && pkgLite.recommendedInstallLocation 14512 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14513 // TODO: focus freeing disk space on the target device 14514 final StorageManager storage = StorageManager.from(mContext); 14515 final long lowThreshold = storage.getStorageLowBytes( 14516 Environment.getDataDirectory()); 14517 14518 final long sizeBytes = mContainerService.calculateInstalledSize( 14519 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14520 14521 try { 14522 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14523 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14524 installFlags, packageAbiOverride); 14525 } catch (InstallerException e) { 14526 Slog.w(TAG, "Failed to free cache", e); 14527 } 14528 14529 /* 14530 * The cache free must have deleted the file we 14531 * downloaded to install. 14532 * 14533 * TODO: fix the "freeCache" call to not delete 14534 * the file we care about. 14535 */ 14536 if (pkgLite.recommendedInstallLocation 14537 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14538 pkgLite.recommendedInstallLocation 14539 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14540 } 14541 } 14542 } 14543 14544 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14545 int loc = pkgLite.recommendedInstallLocation; 14546 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14547 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14548 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14549 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14550 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14551 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14552 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14553 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14554 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14555 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14556 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14557 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14558 } else { 14559 // Override with defaults if needed. 14560 loc = installLocationPolicy(pkgLite); 14561 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14562 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14563 } else if (!onSd && !onInt) { 14564 // Override install location with flags 14565 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14566 // Set the flag to install on external media. 14567 installFlags |= PackageManager.INSTALL_EXTERNAL; 14568 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14569 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14570 if (DEBUG_EPHEMERAL) { 14571 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14572 } 14573 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14574 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14575 |PackageManager.INSTALL_INTERNAL); 14576 } else { 14577 // Make sure the flag for installing on external 14578 // media is unset 14579 installFlags |= PackageManager.INSTALL_INTERNAL; 14580 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14581 } 14582 } 14583 } 14584 } 14585 14586 final InstallArgs args = createInstallArgs(this); 14587 mArgs = args; 14588 14589 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14590 // TODO: http://b/22976637 14591 // Apps installed for "all" users use the device owner to verify the app 14592 UserHandle verifierUser = getUser(); 14593 if (verifierUser == UserHandle.ALL) { 14594 verifierUser = UserHandle.SYSTEM; 14595 } 14596 14597 /* 14598 * Determine if we have any installed package verifiers. If we 14599 * do, then we'll defer to them to verify the packages. 14600 */ 14601 final int requiredUid = mRequiredVerifierPackage == null ? -1 14602 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14603 verifierUser.getIdentifier()); 14604 if (!origin.existing && requiredUid != -1 14605 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14606 final Intent verification = new Intent( 14607 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14608 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14609 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14610 PACKAGE_MIME_TYPE); 14611 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14612 14613 // Query all live verifiers based on current user state 14614 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14615 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14616 14617 if (DEBUG_VERIFY) { 14618 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14619 + verification.toString() + " with " + pkgLite.verifiers.length 14620 + " optional verifiers"); 14621 } 14622 14623 final int verificationId = mPendingVerificationToken++; 14624 14625 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14626 14627 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14628 installerPackageName); 14629 14630 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14631 installFlags); 14632 14633 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14634 pkgLite.packageName); 14635 14636 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14637 pkgLite.versionCode); 14638 14639 if (verificationInfo != null) { 14640 if (verificationInfo.originatingUri != null) { 14641 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14642 verificationInfo.originatingUri); 14643 } 14644 if (verificationInfo.referrer != null) { 14645 verification.putExtra(Intent.EXTRA_REFERRER, 14646 verificationInfo.referrer); 14647 } 14648 if (verificationInfo.originatingUid >= 0) { 14649 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14650 verificationInfo.originatingUid); 14651 } 14652 if (verificationInfo.installerUid >= 0) { 14653 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14654 verificationInfo.installerUid); 14655 } 14656 } 14657 14658 final PackageVerificationState verificationState = new PackageVerificationState( 14659 requiredUid, args); 14660 14661 mPendingVerification.append(verificationId, verificationState); 14662 14663 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14664 receivers, verificationState); 14665 14666 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14667 final long idleDuration = getVerificationTimeout(); 14668 14669 /* 14670 * If any sufficient verifiers were listed in the package 14671 * manifest, attempt to ask them. 14672 */ 14673 if (sufficientVerifiers != null) { 14674 final int N = sufficientVerifiers.size(); 14675 if (N == 0) { 14676 Slog.i(TAG, "Additional verifiers required, but none installed."); 14677 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14678 } else { 14679 for (int i = 0; i < N; i++) { 14680 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14681 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14682 verifierComponent.getPackageName(), idleDuration, 14683 verifierUser.getIdentifier(), false, "package verifier"); 14684 14685 final Intent sufficientIntent = new Intent(verification); 14686 sufficientIntent.setComponent(verifierComponent); 14687 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14688 } 14689 } 14690 } 14691 14692 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14693 mRequiredVerifierPackage, receivers); 14694 if (ret == PackageManager.INSTALL_SUCCEEDED 14695 && mRequiredVerifierPackage != null) { 14696 Trace.asyncTraceBegin( 14697 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14698 /* 14699 * Send the intent to the required verification agent, 14700 * but only start the verification timeout after the 14701 * target BroadcastReceivers have run. 14702 */ 14703 verification.setComponent(requiredVerifierComponent); 14704 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14705 requiredVerifierComponent.getPackageName(), idleDuration, 14706 verifierUser.getIdentifier(), false, "package verifier"); 14707 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14708 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14709 new BroadcastReceiver() { 14710 @Override 14711 public void onReceive(Context context, Intent intent) { 14712 final Message msg = mHandler 14713 .obtainMessage(CHECK_PENDING_VERIFICATION); 14714 msg.arg1 = verificationId; 14715 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14716 } 14717 }, null, 0, null, null); 14718 14719 /* 14720 * We don't want the copy to proceed until verification 14721 * succeeds, so null out this field. 14722 */ 14723 mArgs = null; 14724 } 14725 } else { 14726 /* 14727 * No package verification is enabled, so immediately start 14728 * the remote call to initiate copy using temporary file. 14729 */ 14730 ret = args.copyApk(mContainerService, true); 14731 } 14732 } 14733 14734 mRet = ret; 14735 } 14736 14737 @Override 14738 void handleReturnCode() { 14739 // If mArgs is null, then MCS couldn't be reached. When it 14740 // reconnects, it will try again to install. At that point, this 14741 // will succeed. 14742 if (mArgs != null) { 14743 processPendingInstall(mArgs, mRet); 14744 } 14745 } 14746 14747 @Override 14748 void handleServiceError() { 14749 mArgs = createInstallArgs(this); 14750 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14751 } 14752 14753 public boolean isForwardLocked() { 14754 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14755 } 14756 } 14757 14758 /** 14759 * Used during creation of InstallArgs 14760 * 14761 * @param installFlags package installation flags 14762 * @return true if should be installed on external storage 14763 */ 14764 private static boolean installOnExternalAsec(int installFlags) { 14765 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14766 return false; 14767 } 14768 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14769 return true; 14770 } 14771 return false; 14772 } 14773 14774 /** 14775 * Used during creation of InstallArgs 14776 * 14777 * @param installFlags package installation flags 14778 * @return true if should be installed as forward locked 14779 */ 14780 private static boolean installForwardLocked(int installFlags) { 14781 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14782 } 14783 14784 private InstallArgs createInstallArgs(InstallParams params) { 14785 if (params.move != null) { 14786 return new MoveInstallArgs(params); 14787 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14788 return new AsecInstallArgs(params); 14789 } else { 14790 return new FileInstallArgs(params); 14791 } 14792 } 14793 14794 /** 14795 * Create args that describe an existing installed package. Typically used 14796 * when cleaning up old installs, or used as a move source. 14797 */ 14798 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14799 String resourcePath, String[] instructionSets) { 14800 final boolean isInAsec; 14801 if (installOnExternalAsec(installFlags)) { 14802 /* Apps on SD card are always in ASEC containers. */ 14803 isInAsec = true; 14804 } else if (installForwardLocked(installFlags) 14805 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14806 /* 14807 * Forward-locked apps are only in ASEC containers if they're the 14808 * new style 14809 */ 14810 isInAsec = true; 14811 } else { 14812 isInAsec = false; 14813 } 14814 14815 if (isInAsec) { 14816 return new AsecInstallArgs(codePath, instructionSets, 14817 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14818 } else { 14819 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14820 } 14821 } 14822 14823 static abstract class InstallArgs { 14824 /** @see InstallParams#origin */ 14825 final OriginInfo origin; 14826 /** @see InstallParams#move */ 14827 final MoveInfo move; 14828 14829 final IPackageInstallObserver2 observer; 14830 // Always refers to PackageManager flags only 14831 final int installFlags; 14832 final String installerPackageName; 14833 final String volumeUuid; 14834 final UserHandle user; 14835 final String abiOverride; 14836 final String[] installGrantPermissions; 14837 /** If non-null, drop an async trace when the install completes */ 14838 final String traceMethod; 14839 final int traceCookie; 14840 final Certificate[][] certificates; 14841 final int installReason; 14842 14843 // The list of instruction sets supported by this app. This is currently 14844 // only used during the rmdex() phase to clean up resources. We can get rid of this 14845 // if we move dex files under the common app path. 14846 /* nullable */ String[] instructionSets; 14847 14848 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14849 int installFlags, String installerPackageName, String volumeUuid, 14850 UserHandle user, String[] instructionSets, 14851 String abiOverride, String[] installGrantPermissions, 14852 String traceMethod, int traceCookie, Certificate[][] certificates, 14853 int installReason) { 14854 this.origin = origin; 14855 this.move = move; 14856 this.installFlags = installFlags; 14857 this.observer = observer; 14858 this.installerPackageName = installerPackageName; 14859 this.volumeUuid = volumeUuid; 14860 this.user = user; 14861 this.instructionSets = instructionSets; 14862 this.abiOverride = abiOverride; 14863 this.installGrantPermissions = installGrantPermissions; 14864 this.traceMethod = traceMethod; 14865 this.traceCookie = traceCookie; 14866 this.certificates = certificates; 14867 this.installReason = installReason; 14868 } 14869 14870 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14871 abstract int doPreInstall(int status); 14872 14873 /** 14874 * Rename package into final resting place. All paths on the given 14875 * scanned package should be updated to reflect the rename. 14876 */ 14877 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14878 abstract int doPostInstall(int status, int uid); 14879 14880 /** @see PackageSettingBase#codePathString */ 14881 abstract String getCodePath(); 14882 /** @see PackageSettingBase#resourcePathString */ 14883 abstract String getResourcePath(); 14884 14885 // Need installer lock especially for dex file removal. 14886 abstract void cleanUpResourcesLI(); 14887 abstract boolean doPostDeleteLI(boolean delete); 14888 14889 /** 14890 * Called before the source arguments are copied. This is used mostly 14891 * for MoveParams when it needs to read the source file to put it in the 14892 * destination. 14893 */ 14894 int doPreCopy() { 14895 return PackageManager.INSTALL_SUCCEEDED; 14896 } 14897 14898 /** 14899 * Called after the source arguments are copied. This is used mostly for 14900 * MoveParams when it needs to read the source file to put it in the 14901 * destination. 14902 */ 14903 int doPostCopy(int uid) { 14904 return PackageManager.INSTALL_SUCCEEDED; 14905 } 14906 14907 protected boolean isFwdLocked() { 14908 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14909 } 14910 14911 protected boolean isExternalAsec() { 14912 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14913 } 14914 14915 protected boolean isEphemeral() { 14916 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14917 } 14918 14919 UserHandle getUser() { 14920 return user; 14921 } 14922 } 14923 14924 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14925 if (!allCodePaths.isEmpty()) { 14926 if (instructionSets == null) { 14927 throw new IllegalStateException("instructionSet == null"); 14928 } 14929 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14930 for (String codePath : allCodePaths) { 14931 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14932 try { 14933 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14934 } catch (InstallerException ignored) { 14935 } 14936 } 14937 } 14938 } 14939 } 14940 14941 /** 14942 * Logic to handle installation of non-ASEC applications, including copying 14943 * and renaming logic. 14944 */ 14945 class FileInstallArgs extends InstallArgs { 14946 private File codeFile; 14947 private File resourceFile; 14948 14949 // Example topology: 14950 // /data/app/com.example/base.apk 14951 // /data/app/com.example/split_foo.apk 14952 // /data/app/com.example/lib/arm/libfoo.so 14953 // /data/app/com.example/lib/arm64/libfoo.so 14954 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14955 14956 /** New install */ 14957 FileInstallArgs(InstallParams params) { 14958 super(params.origin, params.move, params.observer, params.installFlags, 14959 params.installerPackageName, params.volumeUuid, 14960 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14961 params.grantedRuntimePermissions, 14962 params.traceMethod, params.traceCookie, params.certificates, 14963 params.installReason); 14964 if (isFwdLocked()) { 14965 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14966 } 14967 } 14968 14969 /** Existing install */ 14970 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14971 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14972 null, null, null, 0, null /*certificates*/, 14973 PackageManager.INSTALL_REASON_UNKNOWN); 14974 this.codeFile = (codePath != null) ? new File(codePath) : null; 14975 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14976 } 14977 14978 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14979 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14980 try { 14981 return doCopyApk(imcs, temp); 14982 } finally { 14983 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14984 } 14985 } 14986 14987 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14988 if (origin.staged) { 14989 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14990 codeFile = origin.file; 14991 resourceFile = origin.file; 14992 return PackageManager.INSTALL_SUCCEEDED; 14993 } 14994 14995 try { 14996 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14997 final File tempDir = 14998 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14999 codeFile = tempDir; 15000 resourceFile = tempDir; 15001 } catch (IOException e) { 15002 Slog.w(TAG, "Failed to create copy file: " + e); 15003 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15004 } 15005 15006 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15007 @Override 15008 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15009 if (!FileUtils.isValidExtFilename(name)) { 15010 throw new IllegalArgumentException("Invalid filename: " + name); 15011 } 15012 try { 15013 final File file = new File(codeFile, name); 15014 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15015 O_RDWR | O_CREAT, 0644); 15016 Os.chmod(file.getAbsolutePath(), 0644); 15017 return new ParcelFileDescriptor(fd); 15018 } catch (ErrnoException e) { 15019 throw new RemoteException("Failed to open: " + e.getMessage()); 15020 } 15021 } 15022 }; 15023 15024 int ret = PackageManager.INSTALL_SUCCEEDED; 15025 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15026 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15027 Slog.e(TAG, "Failed to copy package"); 15028 return ret; 15029 } 15030 15031 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15032 NativeLibraryHelper.Handle handle = null; 15033 try { 15034 handle = NativeLibraryHelper.Handle.create(codeFile); 15035 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15036 abiOverride); 15037 } catch (IOException e) { 15038 Slog.e(TAG, "Copying native libraries failed", e); 15039 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15040 } finally { 15041 IoUtils.closeQuietly(handle); 15042 } 15043 15044 return ret; 15045 } 15046 15047 int doPreInstall(int status) { 15048 if (status != PackageManager.INSTALL_SUCCEEDED) { 15049 cleanUp(); 15050 } 15051 return status; 15052 } 15053 15054 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15055 if (status != PackageManager.INSTALL_SUCCEEDED) { 15056 cleanUp(); 15057 return false; 15058 } 15059 15060 final File targetDir = codeFile.getParentFile(); 15061 final File beforeCodeFile = codeFile; 15062 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15063 15064 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15065 try { 15066 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15067 } catch (ErrnoException e) { 15068 Slog.w(TAG, "Failed to rename", e); 15069 return false; 15070 } 15071 15072 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15073 Slog.w(TAG, "Failed to restorecon"); 15074 return false; 15075 } 15076 15077 // Reflect the rename internally 15078 codeFile = afterCodeFile; 15079 resourceFile = afterCodeFile; 15080 15081 // Reflect the rename in scanned details 15082 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15083 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15084 afterCodeFile, pkg.baseCodePath)); 15085 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15086 afterCodeFile, pkg.splitCodePaths)); 15087 15088 // Reflect the rename in app info 15089 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15090 pkg.setApplicationInfoCodePath(pkg.codePath); 15091 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15092 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15093 pkg.setApplicationInfoResourcePath(pkg.codePath); 15094 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15095 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15096 15097 return true; 15098 } 15099 15100 int doPostInstall(int status, int uid) { 15101 if (status != PackageManager.INSTALL_SUCCEEDED) { 15102 cleanUp(); 15103 } 15104 return status; 15105 } 15106 15107 @Override 15108 String getCodePath() { 15109 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15110 } 15111 15112 @Override 15113 String getResourcePath() { 15114 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15115 } 15116 15117 private boolean cleanUp() { 15118 if (codeFile == null || !codeFile.exists()) { 15119 return false; 15120 } 15121 15122 removeCodePathLI(codeFile); 15123 15124 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15125 resourceFile.delete(); 15126 } 15127 15128 return true; 15129 } 15130 15131 void cleanUpResourcesLI() { 15132 // Try enumerating all code paths before deleting 15133 List<String> allCodePaths = Collections.EMPTY_LIST; 15134 if (codeFile != null && codeFile.exists()) { 15135 try { 15136 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15137 allCodePaths = pkg.getAllCodePaths(); 15138 } catch (PackageParserException e) { 15139 // Ignored; we tried our best 15140 } 15141 } 15142 15143 cleanUp(); 15144 removeDexFiles(allCodePaths, instructionSets); 15145 } 15146 15147 boolean doPostDeleteLI(boolean delete) { 15148 // XXX err, shouldn't we respect the delete flag? 15149 cleanUpResourcesLI(); 15150 return true; 15151 } 15152 } 15153 15154 private boolean isAsecExternal(String cid) { 15155 final String asecPath = PackageHelper.getSdFilesystem(cid); 15156 return !asecPath.startsWith(mAsecInternalPath); 15157 } 15158 15159 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15160 PackageManagerException { 15161 if (copyRet < 0) { 15162 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15163 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15164 throw new PackageManagerException(copyRet, message); 15165 } 15166 } 15167 } 15168 15169 /** 15170 * Extract the StorageManagerService "container ID" from the full code path of an 15171 * .apk. 15172 */ 15173 static String cidFromCodePath(String fullCodePath) { 15174 int eidx = fullCodePath.lastIndexOf("/"); 15175 String subStr1 = fullCodePath.substring(0, eidx); 15176 int sidx = subStr1.lastIndexOf("/"); 15177 return subStr1.substring(sidx+1, eidx); 15178 } 15179 15180 /** 15181 * Logic to handle installation of ASEC applications, including copying and 15182 * renaming logic. 15183 */ 15184 class AsecInstallArgs extends InstallArgs { 15185 static final String RES_FILE_NAME = "pkg.apk"; 15186 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15187 15188 String cid; 15189 String packagePath; 15190 String resourcePath; 15191 15192 /** New install */ 15193 AsecInstallArgs(InstallParams params) { 15194 super(params.origin, params.move, params.observer, params.installFlags, 15195 params.installerPackageName, params.volumeUuid, 15196 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15197 params.grantedRuntimePermissions, 15198 params.traceMethod, params.traceCookie, params.certificates, 15199 params.installReason); 15200 } 15201 15202 /** Existing install */ 15203 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15204 boolean isExternal, boolean isForwardLocked) { 15205 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15206 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15207 instructionSets, null, null, null, 0, null /*certificates*/, 15208 PackageManager.INSTALL_REASON_UNKNOWN); 15209 // Hackily pretend we're still looking at a full code path 15210 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15211 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15212 } 15213 15214 // Extract cid from fullCodePath 15215 int eidx = fullCodePath.lastIndexOf("/"); 15216 String subStr1 = fullCodePath.substring(0, eidx); 15217 int sidx = subStr1.lastIndexOf("/"); 15218 cid = subStr1.substring(sidx+1, eidx); 15219 setMountPath(subStr1); 15220 } 15221 15222 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15223 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15224 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15225 instructionSets, null, null, null, 0, null /*certificates*/, 15226 PackageManager.INSTALL_REASON_UNKNOWN); 15227 this.cid = cid; 15228 setMountPath(PackageHelper.getSdDir(cid)); 15229 } 15230 15231 void createCopyFile() { 15232 cid = mInstallerService.allocateExternalStageCidLegacy(); 15233 } 15234 15235 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15236 if (origin.staged && origin.cid != null) { 15237 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15238 cid = origin.cid; 15239 setMountPath(PackageHelper.getSdDir(cid)); 15240 return PackageManager.INSTALL_SUCCEEDED; 15241 } 15242 15243 if (temp) { 15244 createCopyFile(); 15245 } else { 15246 /* 15247 * Pre-emptively destroy the container since it's destroyed if 15248 * copying fails due to it existing anyway. 15249 */ 15250 PackageHelper.destroySdDir(cid); 15251 } 15252 15253 final String newMountPath = imcs.copyPackageToContainer( 15254 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15255 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15256 15257 if (newMountPath != null) { 15258 setMountPath(newMountPath); 15259 return PackageManager.INSTALL_SUCCEEDED; 15260 } else { 15261 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15262 } 15263 } 15264 15265 @Override 15266 String getCodePath() { 15267 return packagePath; 15268 } 15269 15270 @Override 15271 String getResourcePath() { 15272 return resourcePath; 15273 } 15274 15275 int doPreInstall(int status) { 15276 if (status != PackageManager.INSTALL_SUCCEEDED) { 15277 // Destroy container 15278 PackageHelper.destroySdDir(cid); 15279 } else { 15280 boolean mounted = PackageHelper.isContainerMounted(cid); 15281 if (!mounted) { 15282 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15283 Process.SYSTEM_UID); 15284 if (newMountPath != null) { 15285 setMountPath(newMountPath); 15286 } else { 15287 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15288 } 15289 } 15290 } 15291 return status; 15292 } 15293 15294 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15295 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15296 String newMountPath = null; 15297 if (PackageHelper.isContainerMounted(cid)) { 15298 // Unmount the container 15299 if (!PackageHelper.unMountSdDir(cid)) { 15300 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15301 return false; 15302 } 15303 } 15304 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15305 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15306 " which might be stale. Will try to clean up."); 15307 // Clean up the stale container and proceed to recreate. 15308 if (!PackageHelper.destroySdDir(newCacheId)) { 15309 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15310 return false; 15311 } 15312 // Successfully cleaned up stale container. Try to rename again. 15313 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15314 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15315 + " inspite of cleaning it up."); 15316 return false; 15317 } 15318 } 15319 if (!PackageHelper.isContainerMounted(newCacheId)) { 15320 Slog.w(TAG, "Mounting container " + newCacheId); 15321 newMountPath = PackageHelper.mountSdDir(newCacheId, 15322 getEncryptKey(), Process.SYSTEM_UID); 15323 } else { 15324 newMountPath = PackageHelper.getSdDir(newCacheId); 15325 } 15326 if (newMountPath == null) { 15327 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15328 return false; 15329 } 15330 Log.i(TAG, "Succesfully renamed " + cid + 15331 " to " + newCacheId + 15332 " at new path: " + newMountPath); 15333 cid = newCacheId; 15334 15335 final File beforeCodeFile = new File(packagePath); 15336 setMountPath(newMountPath); 15337 final File afterCodeFile = new File(packagePath); 15338 15339 // Reflect the rename in scanned details 15340 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15341 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15342 afterCodeFile, pkg.baseCodePath)); 15343 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15344 afterCodeFile, pkg.splitCodePaths)); 15345 15346 // Reflect the rename in app info 15347 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15348 pkg.setApplicationInfoCodePath(pkg.codePath); 15349 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15350 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15351 pkg.setApplicationInfoResourcePath(pkg.codePath); 15352 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15353 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15354 15355 return true; 15356 } 15357 15358 private void setMountPath(String mountPath) { 15359 final File mountFile = new File(mountPath); 15360 15361 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15362 if (monolithicFile.exists()) { 15363 packagePath = monolithicFile.getAbsolutePath(); 15364 if (isFwdLocked()) { 15365 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15366 } else { 15367 resourcePath = packagePath; 15368 } 15369 } else { 15370 packagePath = mountFile.getAbsolutePath(); 15371 resourcePath = packagePath; 15372 } 15373 } 15374 15375 int doPostInstall(int status, int uid) { 15376 if (status != PackageManager.INSTALL_SUCCEEDED) { 15377 cleanUp(); 15378 } else { 15379 final int groupOwner; 15380 final String protectedFile; 15381 if (isFwdLocked()) { 15382 groupOwner = UserHandle.getSharedAppGid(uid); 15383 protectedFile = RES_FILE_NAME; 15384 } else { 15385 groupOwner = -1; 15386 protectedFile = null; 15387 } 15388 15389 if (uid < Process.FIRST_APPLICATION_UID 15390 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15391 Slog.e(TAG, "Failed to finalize " + cid); 15392 PackageHelper.destroySdDir(cid); 15393 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15394 } 15395 15396 boolean mounted = PackageHelper.isContainerMounted(cid); 15397 if (!mounted) { 15398 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15399 } 15400 } 15401 return status; 15402 } 15403 15404 private void cleanUp() { 15405 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15406 15407 // Destroy secure container 15408 PackageHelper.destroySdDir(cid); 15409 } 15410 15411 private List<String> getAllCodePaths() { 15412 final File codeFile = new File(getCodePath()); 15413 if (codeFile != null && codeFile.exists()) { 15414 try { 15415 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15416 return pkg.getAllCodePaths(); 15417 } catch (PackageParserException e) { 15418 // Ignored; we tried our best 15419 } 15420 } 15421 return Collections.EMPTY_LIST; 15422 } 15423 15424 void cleanUpResourcesLI() { 15425 // Enumerate all code paths before deleting 15426 cleanUpResourcesLI(getAllCodePaths()); 15427 } 15428 15429 private void cleanUpResourcesLI(List<String> allCodePaths) { 15430 cleanUp(); 15431 removeDexFiles(allCodePaths, instructionSets); 15432 } 15433 15434 String getPackageName() { 15435 return getAsecPackageName(cid); 15436 } 15437 15438 boolean doPostDeleteLI(boolean delete) { 15439 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15440 final List<String> allCodePaths = getAllCodePaths(); 15441 boolean mounted = PackageHelper.isContainerMounted(cid); 15442 if (mounted) { 15443 // Unmount first 15444 if (PackageHelper.unMountSdDir(cid)) { 15445 mounted = false; 15446 } 15447 } 15448 if (!mounted && delete) { 15449 cleanUpResourcesLI(allCodePaths); 15450 } 15451 return !mounted; 15452 } 15453 15454 @Override 15455 int doPreCopy() { 15456 if (isFwdLocked()) { 15457 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15458 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15459 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15460 } 15461 } 15462 15463 return PackageManager.INSTALL_SUCCEEDED; 15464 } 15465 15466 @Override 15467 int doPostCopy(int uid) { 15468 if (isFwdLocked()) { 15469 if (uid < Process.FIRST_APPLICATION_UID 15470 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15471 RES_FILE_NAME)) { 15472 Slog.e(TAG, "Failed to finalize " + cid); 15473 PackageHelper.destroySdDir(cid); 15474 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15475 } 15476 } 15477 15478 return PackageManager.INSTALL_SUCCEEDED; 15479 } 15480 } 15481 15482 /** 15483 * Logic to handle movement of existing installed applications. 15484 */ 15485 class MoveInstallArgs extends InstallArgs { 15486 private File codeFile; 15487 private File resourceFile; 15488 15489 /** New install */ 15490 MoveInstallArgs(InstallParams params) { 15491 super(params.origin, params.move, params.observer, params.installFlags, 15492 params.installerPackageName, params.volumeUuid, 15493 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15494 params.grantedRuntimePermissions, 15495 params.traceMethod, params.traceCookie, params.certificates, 15496 params.installReason); 15497 } 15498 15499 int copyApk(IMediaContainerService imcs, boolean temp) { 15500 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15501 + move.fromUuid + " to " + move.toUuid); 15502 synchronized (mInstaller) { 15503 try { 15504 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15505 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15506 } catch (InstallerException e) { 15507 Slog.w(TAG, "Failed to move app", e); 15508 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15509 } 15510 } 15511 15512 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15513 resourceFile = codeFile; 15514 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15515 15516 return PackageManager.INSTALL_SUCCEEDED; 15517 } 15518 15519 int doPreInstall(int status) { 15520 if (status != PackageManager.INSTALL_SUCCEEDED) { 15521 cleanUp(move.toUuid); 15522 } 15523 return status; 15524 } 15525 15526 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15527 if (status != PackageManager.INSTALL_SUCCEEDED) { 15528 cleanUp(move.toUuid); 15529 return false; 15530 } 15531 15532 // Reflect the move in app info 15533 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15534 pkg.setApplicationInfoCodePath(pkg.codePath); 15535 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15536 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15537 pkg.setApplicationInfoResourcePath(pkg.codePath); 15538 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15539 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15540 15541 return true; 15542 } 15543 15544 int doPostInstall(int status, int uid) { 15545 if (status == PackageManager.INSTALL_SUCCEEDED) { 15546 cleanUp(move.fromUuid); 15547 } else { 15548 cleanUp(move.toUuid); 15549 } 15550 return status; 15551 } 15552 15553 @Override 15554 String getCodePath() { 15555 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15556 } 15557 15558 @Override 15559 String getResourcePath() { 15560 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15561 } 15562 15563 private boolean cleanUp(String volumeUuid) { 15564 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15565 move.dataAppName); 15566 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15567 final int[] userIds = sUserManager.getUserIds(); 15568 synchronized (mInstallLock) { 15569 // Clean up both app data and code 15570 // All package moves are frozen until finished 15571 for (int userId : userIds) { 15572 try { 15573 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15574 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15575 } catch (InstallerException e) { 15576 Slog.w(TAG, String.valueOf(e)); 15577 } 15578 } 15579 removeCodePathLI(codeFile); 15580 } 15581 return true; 15582 } 15583 15584 void cleanUpResourcesLI() { 15585 throw new UnsupportedOperationException(); 15586 } 15587 15588 boolean doPostDeleteLI(boolean delete) { 15589 throw new UnsupportedOperationException(); 15590 } 15591 } 15592 15593 static String getAsecPackageName(String packageCid) { 15594 int idx = packageCid.lastIndexOf("-"); 15595 if (idx == -1) { 15596 return packageCid; 15597 } 15598 return packageCid.substring(0, idx); 15599 } 15600 15601 // Utility method used to create code paths based on package name and available index. 15602 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15603 String idxStr = ""; 15604 int idx = 1; 15605 // Fall back to default value of idx=1 if prefix is not 15606 // part of oldCodePath 15607 if (oldCodePath != null) { 15608 String subStr = oldCodePath; 15609 // Drop the suffix right away 15610 if (suffix != null && subStr.endsWith(suffix)) { 15611 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15612 } 15613 // If oldCodePath already contains prefix find out the 15614 // ending index to either increment or decrement. 15615 int sidx = subStr.lastIndexOf(prefix); 15616 if (sidx != -1) { 15617 subStr = subStr.substring(sidx + prefix.length()); 15618 if (subStr != null) { 15619 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15620 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15621 } 15622 try { 15623 idx = Integer.parseInt(subStr); 15624 if (idx <= 1) { 15625 idx++; 15626 } else { 15627 idx--; 15628 } 15629 } catch(NumberFormatException e) { 15630 } 15631 } 15632 } 15633 } 15634 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15635 return prefix + idxStr; 15636 } 15637 15638 private File getNextCodePath(File targetDir, String packageName) { 15639 File result; 15640 SecureRandom random = new SecureRandom(); 15641 byte[] bytes = new byte[16]; 15642 do { 15643 random.nextBytes(bytes); 15644 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15645 result = new File(targetDir, packageName + "-" + suffix); 15646 } while (result.exists()); 15647 return result; 15648 } 15649 15650 // Utility method that returns the relative package path with respect 15651 // to the installation directory. Like say for /data/data/com.test-1.apk 15652 // string com.test-1 is returned. 15653 static String deriveCodePathName(String codePath) { 15654 if (codePath == null) { 15655 return null; 15656 } 15657 final File codeFile = new File(codePath); 15658 final String name = codeFile.getName(); 15659 if (codeFile.isDirectory()) { 15660 return name; 15661 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15662 final int lastDot = name.lastIndexOf('.'); 15663 return name.substring(0, lastDot); 15664 } else { 15665 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15666 return null; 15667 } 15668 } 15669 15670 static class PackageInstalledInfo { 15671 String name; 15672 int uid; 15673 // The set of users that originally had this package installed. 15674 int[] origUsers; 15675 // The set of users that now have this package installed. 15676 int[] newUsers; 15677 PackageParser.Package pkg; 15678 int returnCode; 15679 String returnMsg; 15680 PackageRemovedInfo removedInfo; 15681 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15682 15683 public void setError(int code, String msg) { 15684 setReturnCode(code); 15685 setReturnMessage(msg); 15686 Slog.w(TAG, msg); 15687 } 15688 15689 public void setError(String msg, PackageParserException e) { 15690 setReturnCode(e.error); 15691 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15692 Slog.w(TAG, msg, e); 15693 } 15694 15695 public void setError(String msg, PackageManagerException e) { 15696 returnCode = e.error; 15697 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15698 Slog.w(TAG, msg, e); 15699 } 15700 15701 public void setReturnCode(int returnCode) { 15702 this.returnCode = returnCode; 15703 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15704 for (int i = 0; i < childCount; i++) { 15705 addedChildPackages.valueAt(i).returnCode = returnCode; 15706 } 15707 } 15708 15709 private void setReturnMessage(String returnMsg) { 15710 this.returnMsg = returnMsg; 15711 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15712 for (int i = 0; i < childCount; i++) { 15713 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15714 } 15715 } 15716 15717 // In some error cases we want to convey more info back to the observer 15718 String origPackage; 15719 String origPermission; 15720 } 15721 15722 /* 15723 * Install a non-existing package. 15724 */ 15725 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15726 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15727 PackageInstalledInfo res, int installReason) { 15728 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15729 15730 // Remember this for later, in case we need to rollback this install 15731 String pkgName = pkg.packageName; 15732 15733 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15734 15735 synchronized(mPackages) { 15736 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15737 if (renamedPackage != null) { 15738 // A package with the same name is already installed, though 15739 // it has been renamed to an older name. The package we 15740 // are trying to install should be installed as an update to 15741 // the existing one, but that has not been requested, so bail. 15742 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15743 + " without first uninstalling package running as " 15744 + renamedPackage); 15745 return; 15746 } 15747 if (mPackages.containsKey(pkgName)) { 15748 // Don't allow installation over an existing package with the same name. 15749 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15750 + " without first uninstalling."); 15751 return; 15752 } 15753 } 15754 15755 try { 15756 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15757 System.currentTimeMillis(), user); 15758 15759 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15760 15761 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15762 prepareAppDataAfterInstallLIF(newPackage); 15763 15764 } else { 15765 // Remove package from internal structures, but keep around any 15766 // data that might have already existed 15767 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15768 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15769 } 15770 } catch (PackageManagerException e) { 15771 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15772 } 15773 15774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15775 } 15776 15777 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15778 // Can't rotate keys during boot or if sharedUser. 15779 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15780 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15781 return false; 15782 } 15783 // app is using upgradeKeySets; make sure all are valid 15784 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15785 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15786 for (int i = 0; i < upgradeKeySets.length; i++) { 15787 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15788 Slog.wtf(TAG, "Package " 15789 + (oldPs.name != null ? oldPs.name : "<null>") 15790 + " contains upgrade-key-set reference to unknown key-set: " 15791 + upgradeKeySets[i] 15792 + " reverting to signatures check."); 15793 return false; 15794 } 15795 } 15796 return true; 15797 } 15798 15799 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15800 // Upgrade keysets are being used. Determine if new package has a superset of the 15801 // required keys. 15802 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15803 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15804 for (int i = 0; i < upgradeKeySets.length; i++) { 15805 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15806 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15807 return true; 15808 } 15809 } 15810 return false; 15811 } 15812 15813 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15814 try (DigestInputStream digestStream = 15815 new DigestInputStream(new FileInputStream(file), digest)) { 15816 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15817 } 15818 } 15819 15820 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15821 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15822 int installReason) { 15823 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15824 15825 final PackageParser.Package oldPackage; 15826 final String pkgName = pkg.packageName; 15827 final int[] allUsers; 15828 final int[] installedUsers; 15829 15830 synchronized(mPackages) { 15831 oldPackage = mPackages.get(pkgName); 15832 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15833 15834 // don't allow upgrade to target a release SDK from a pre-release SDK 15835 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15836 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15837 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15838 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15839 if (oldTargetsPreRelease 15840 && !newTargetsPreRelease 15841 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15842 Slog.w(TAG, "Can't install package targeting released sdk"); 15843 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15844 return; 15845 } 15846 15847 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15848 15849 // don't allow an upgrade from full to ephemeral 15850 if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) { 15851 // can't downgrade from full to instant 15852 Slog.w(TAG, "Can't replace app with instant app: " + pkgName); 15853 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15854 return; 15855 } 15856 15857 // verify signatures are valid 15858 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15859 if (!checkUpgradeKeySetLP(ps, pkg)) { 15860 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15861 "New package not signed by keys specified by upgrade-keysets: " 15862 + pkgName); 15863 return; 15864 } 15865 } else { 15866 // default to original signature matching 15867 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15868 != PackageManager.SIGNATURE_MATCH) { 15869 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15870 "New package has a different signature: " + pkgName); 15871 return; 15872 } 15873 } 15874 15875 // don't allow a system upgrade unless the upgrade hash matches 15876 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15877 byte[] digestBytes = null; 15878 try { 15879 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15880 updateDigest(digest, new File(pkg.baseCodePath)); 15881 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15882 for (String path : pkg.splitCodePaths) { 15883 updateDigest(digest, new File(path)); 15884 } 15885 } 15886 digestBytes = digest.digest(); 15887 } catch (NoSuchAlgorithmException | IOException e) { 15888 res.setError(INSTALL_FAILED_INVALID_APK, 15889 "Could not compute hash: " + pkgName); 15890 return; 15891 } 15892 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15893 res.setError(INSTALL_FAILED_INVALID_APK, 15894 "New package fails restrict-update check: " + pkgName); 15895 return; 15896 } 15897 // retain upgrade restriction 15898 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15899 } 15900 15901 // Check for shared user id changes 15902 String invalidPackageName = 15903 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15904 if (invalidPackageName != null) { 15905 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15906 "Package " + invalidPackageName + " tried to change user " 15907 + oldPackage.mSharedUserId); 15908 return; 15909 } 15910 15911 // In case of rollback, remember per-user/profile install state 15912 allUsers = sUserManager.getUserIds(); 15913 installedUsers = ps.queryInstalledUsers(allUsers, true); 15914 } 15915 15916 // Update what is removed 15917 res.removedInfo = new PackageRemovedInfo(); 15918 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15919 res.removedInfo.removedPackage = oldPackage.packageName; 15920 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15921 res.removedInfo.isUpdate = true; 15922 res.removedInfo.origUsers = installedUsers; 15923 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15924 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15925 for (int i = 0; i < installedUsers.length; i++) { 15926 final int userId = installedUsers[i]; 15927 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15928 } 15929 15930 final int childCount = (oldPackage.childPackages != null) 15931 ? oldPackage.childPackages.size() : 0; 15932 for (int i = 0; i < childCount; i++) { 15933 boolean childPackageUpdated = false; 15934 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15935 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15936 if (res.addedChildPackages != null) { 15937 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15938 if (childRes != null) { 15939 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15940 childRes.removedInfo.removedPackage = childPkg.packageName; 15941 childRes.removedInfo.isUpdate = true; 15942 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15943 childPackageUpdated = true; 15944 } 15945 } 15946 if (!childPackageUpdated) { 15947 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15948 childRemovedRes.removedPackage = childPkg.packageName; 15949 childRemovedRes.isUpdate = false; 15950 childRemovedRes.dataRemoved = true; 15951 synchronized (mPackages) { 15952 if (childPs != null) { 15953 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15954 } 15955 } 15956 if (res.removedInfo.removedChildPackages == null) { 15957 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15958 } 15959 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15960 } 15961 } 15962 15963 boolean sysPkg = (isSystemApp(oldPackage)); 15964 if (sysPkg) { 15965 // Set the system/privileged flags as needed 15966 final boolean privileged = 15967 (oldPackage.applicationInfo.privateFlags 15968 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15969 final int systemPolicyFlags = policyFlags 15970 | PackageParser.PARSE_IS_SYSTEM 15971 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15972 15973 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15974 user, allUsers, installerPackageName, res, installReason); 15975 } else { 15976 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15977 user, allUsers, installerPackageName, res, installReason); 15978 } 15979 } 15980 15981 public List<String> getPreviousCodePaths(String packageName) { 15982 final PackageSetting ps = mSettings.mPackages.get(packageName); 15983 final List<String> result = new ArrayList<String>(); 15984 if (ps != null && ps.oldCodePaths != null) { 15985 result.addAll(ps.oldCodePaths); 15986 } 15987 return result; 15988 } 15989 15990 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15991 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15992 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15993 int installReason) { 15994 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15995 + deletedPackage); 15996 15997 String pkgName = deletedPackage.packageName; 15998 boolean deletedPkg = true; 15999 boolean addedPkg = false; 16000 boolean updatedSettings = false; 16001 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16002 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16003 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16004 16005 final long origUpdateTime = (pkg.mExtras != null) 16006 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16007 16008 // First delete the existing package while retaining the data directory 16009 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16010 res.removedInfo, true, pkg)) { 16011 // If the existing package wasn't successfully deleted 16012 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16013 deletedPkg = false; 16014 } else { 16015 // Successfully deleted the old package; proceed with replace. 16016 16017 // If deleted package lived in a container, give users a chance to 16018 // relinquish resources before killing. 16019 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16020 if (DEBUG_INSTALL) { 16021 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16022 } 16023 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16024 final ArrayList<String> pkgList = new ArrayList<String>(1); 16025 pkgList.add(deletedPackage.applicationInfo.packageName); 16026 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16027 } 16028 16029 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16030 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16031 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16032 16033 try { 16034 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16035 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16036 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16037 installReason); 16038 16039 // Update the in-memory copy of the previous code paths. 16040 PackageSetting ps = mSettings.mPackages.get(pkgName); 16041 if (!killApp) { 16042 if (ps.oldCodePaths == null) { 16043 ps.oldCodePaths = new ArraySet<>(); 16044 } 16045 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16046 if (deletedPackage.splitCodePaths != null) { 16047 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16048 } 16049 } else { 16050 ps.oldCodePaths = null; 16051 } 16052 if (ps.childPackageNames != null) { 16053 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16054 final String childPkgName = ps.childPackageNames.get(i); 16055 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16056 childPs.oldCodePaths = ps.oldCodePaths; 16057 } 16058 } 16059 // set instant app status, but, only if it's explicitly specified 16060 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16061 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16062 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16063 prepareAppDataAfterInstallLIF(newPackage); 16064 addedPkg = true; 16065 } catch (PackageManagerException e) { 16066 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16067 } 16068 } 16069 16070 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16071 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16072 16073 // Revert all internal state mutations and added folders for the failed install 16074 if (addedPkg) { 16075 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16076 res.removedInfo, true, null); 16077 } 16078 16079 // Restore the old package 16080 if (deletedPkg) { 16081 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16082 File restoreFile = new File(deletedPackage.codePath); 16083 // Parse old package 16084 boolean oldExternal = isExternal(deletedPackage); 16085 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16086 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16087 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16088 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16089 try { 16090 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16091 null); 16092 } catch (PackageManagerException e) { 16093 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16094 + e.getMessage()); 16095 return; 16096 } 16097 16098 synchronized (mPackages) { 16099 // Ensure the installer package name up to date 16100 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16101 16102 // Update permissions for restored package 16103 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16104 16105 mSettings.writeLPr(); 16106 } 16107 16108 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16109 } 16110 } else { 16111 synchronized (mPackages) { 16112 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16113 if (ps != null) { 16114 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16115 if (res.removedInfo.removedChildPackages != null) { 16116 final int childCount = res.removedInfo.removedChildPackages.size(); 16117 // Iterate in reverse as we may modify the collection 16118 for (int i = childCount - 1; i >= 0; i--) { 16119 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16120 if (res.addedChildPackages.containsKey(childPackageName)) { 16121 res.removedInfo.removedChildPackages.removeAt(i); 16122 } else { 16123 PackageRemovedInfo childInfo = res.removedInfo 16124 .removedChildPackages.valueAt(i); 16125 childInfo.removedForAllUsers = mPackages.get( 16126 childInfo.removedPackage) == null; 16127 } 16128 } 16129 } 16130 } 16131 } 16132 } 16133 } 16134 16135 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16136 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16137 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16138 int installReason) { 16139 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16140 + ", old=" + deletedPackage); 16141 16142 final boolean disabledSystem; 16143 16144 // Remove existing system package 16145 removePackageLI(deletedPackage, true); 16146 16147 synchronized (mPackages) { 16148 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16149 } 16150 if (!disabledSystem) { 16151 // We didn't need to disable the .apk as a current system package, 16152 // which means we are replacing another update that is already 16153 // installed. We need to make sure to delete the older one's .apk. 16154 res.removedInfo.args = createInstallArgsForExisting(0, 16155 deletedPackage.applicationInfo.getCodePath(), 16156 deletedPackage.applicationInfo.getResourcePath(), 16157 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16158 } else { 16159 res.removedInfo.args = null; 16160 } 16161 16162 // Successfully disabled the old package. Now proceed with re-installation 16163 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16164 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16165 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16166 16167 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16168 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16169 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16170 16171 PackageParser.Package newPackage = null; 16172 try { 16173 // Add the package to the internal data structures 16174 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16175 16176 // Set the update and install times 16177 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16178 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16179 System.currentTimeMillis()); 16180 16181 // Update the package dynamic state if succeeded 16182 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16183 // Now that the install succeeded make sure we remove data 16184 // directories for any child package the update removed. 16185 final int deletedChildCount = (deletedPackage.childPackages != null) 16186 ? deletedPackage.childPackages.size() : 0; 16187 final int newChildCount = (newPackage.childPackages != null) 16188 ? newPackage.childPackages.size() : 0; 16189 for (int i = 0; i < deletedChildCount; i++) { 16190 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16191 boolean childPackageDeleted = true; 16192 for (int j = 0; j < newChildCount; j++) { 16193 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16194 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16195 childPackageDeleted = false; 16196 break; 16197 } 16198 } 16199 if (childPackageDeleted) { 16200 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16201 deletedChildPkg.packageName); 16202 if (ps != null && res.removedInfo.removedChildPackages != null) { 16203 PackageRemovedInfo removedChildRes = res.removedInfo 16204 .removedChildPackages.get(deletedChildPkg.packageName); 16205 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16206 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16207 } 16208 } 16209 } 16210 16211 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16212 installReason); 16213 prepareAppDataAfterInstallLIF(newPackage); 16214 } 16215 } catch (PackageManagerException e) { 16216 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16217 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16218 } 16219 16220 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16221 // Re installation failed. Restore old information 16222 // Remove new pkg information 16223 if (newPackage != null) { 16224 removeInstalledPackageLI(newPackage, true); 16225 } 16226 // Add back the old system package 16227 try { 16228 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16229 } catch (PackageManagerException e) { 16230 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16231 } 16232 16233 synchronized (mPackages) { 16234 if (disabledSystem) { 16235 enableSystemPackageLPw(deletedPackage); 16236 } 16237 16238 // Ensure the installer package name up to date 16239 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16240 16241 // Update permissions for restored package 16242 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16243 16244 mSettings.writeLPr(); 16245 } 16246 16247 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16248 + " after failed upgrade"); 16249 } 16250 } 16251 16252 /** 16253 * Checks whether the parent or any of the child packages have a change shared 16254 * user. For a package to be a valid update the shred users of the parent and 16255 * the children should match. We may later support changing child shared users. 16256 * @param oldPkg The updated package. 16257 * @param newPkg The update package. 16258 * @return The shared user that change between the versions. 16259 */ 16260 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16261 PackageParser.Package newPkg) { 16262 // Check parent shared user 16263 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16264 return newPkg.packageName; 16265 } 16266 // Check child shared users 16267 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16268 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16269 for (int i = 0; i < newChildCount; i++) { 16270 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16271 // If this child was present, did it have the same shared user? 16272 for (int j = 0; j < oldChildCount; j++) { 16273 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16274 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16275 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16276 return newChildPkg.packageName; 16277 } 16278 } 16279 } 16280 return null; 16281 } 16282 16283 private void removeNativeBinariesLI(PackageSetting ps) { 16284 // Remove the lib path for the parent package 16285 if (ps != null) { 16286 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16287 // Remove the lib path for the child packages 16288 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16289 for (int i = 0; i < childCount; i++) { 16290 PackageSetting childPs = null; 16291 synchronized (mPackages) { 16292 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16293 } 16294 if (childPs != null) { 16295 NativeLibraryHelper.removeNativeBinariesLI(childPs 16296 .legacyNativeLibraryPathString); 16297 } 16298 } 16299 } 16300 } 16301 16302 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16303 // Enable the parent package 16304 mSettings.enableSystemPackageLPw(pkg.packageName); 16305 // Enable the child packages 16306 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16307 for (int i = 0; i < childCount; i++) { 16308 PackageParser.Package childPkg = pkg.childPackages.get(i); 16309 mSettings.enableSystemPackageLPw(childPkg.packageName); 16310 } 16311 } 16312 16313 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16314 PackageParser.Package newPkg) { 16315 // Disable the parent package (parent always replaced) 16316 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16317 // Disable the child packages 16318 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16319 for (int i = 0; i < childCount; i++) { 16320 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16321 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16322 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16323 } 16324 return disabled; 16325 } 16326 16327 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16328 String installerPackageName) { 16329 // Enable the parent package 16330 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16331 // Enable the child packages 16332 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16333 for (int i = 0; i < childCount; i++) { 16334 PackageParser.Package childPkg = pkg.childPackages.get(i); 16335 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16336 } 16337 } 16338 16339 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16340 // Collect all used permissions in the UID 16341 ArraySet<String> usedPermissions = new ArraySet<>(); 16342 final int packageCount = su.packages.size(); 16343 for (int i = 0; i < packageCount; i++) { 16344 PackageSetting ps = su.packages.valueAt(i); 16345 if (ps.pkg == null) { 16346 continue; 16347 } 16348 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16349 for (int j = 0; j < requestedPermCount; j++) { 16350 String permission = ps.pkg.requestedPermissions.get(j); 16351 BasePermission bp = mSettings.mPermissions.get(permission); 16352 if (bp != null) { 16353 usedPermissions.add(permission); 16354 } 16355 } 16356 } 16357 16358 PermissionsState permissionsState = su.getPermissionsState(); 16359 // Prune install permissions 16360 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16361 final int installPermCount = installPermStates.size(); 16362 for (int i = installPermCount - 1; i >= 0; i--) { 16363 PermissionState permissionState = installPermStates.get(i); 16364 if (!usedPermissions.contains(permissionState.getName())) { 16365 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16366 if (bp != null) { 16367 permissionsState.revokeInstallPermission(bp); 16368 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16369 PackageManager.MASK_PERMISSION_FLAGS, 0); 16370 } 16371 } 16372 } 16373 16374 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16375 16376 // Prune runtime permissions 16377 for (int userId : allUserIds) { 16378 List<PermissionState> runtimePermStates = permissionsState 16379 .getRuntimePermissionStates(userId); 16380 final int runtimePermCount = runtimePermStates.size(); 16381 for (int i = runtimePermCount - 1; i >= 0; i--) { 16382 PermissionState permissionState = runtimePermStates.get(i); 16383 if (!usedPermissions.contains(permissionState.getName())) { 16384 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16385 if (bp != null) { 16386 permissionsState.revokeRuntimePermission(bp, userId); 16387 permissionsState.updatePermissionFlags(bp, userId, 16388 PackageManager.MASK_PERMISSION_FLAGS, 0); 16389 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16390 runtimePermissionChangedUserIds, userId); 16391 } 16392 } 16393 } 16394 } 16395 16396 return runtimePermissionChangedUserIds; 16397 } 16398 16399 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16400 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16401 // Update the parent package setting 16402 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16403 res, user, installReason); 16404 // Update the child packages setting 16405 final int childCount = (newPackage.childPackages != null) 16406 ? newPackage.childPackages.size() : 0; 16407 for (int i = 0; i < childCount; i++) { 16408 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16409 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16410 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16411 childRes.origUsers, childRes, user, installReason); 16412 } 16413 } 16414 16415 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16416 String installerPackageName, int[] allUsers, int[] installedForUsers, 16417 PackageInstalledInfo res, UserHandle user, int installReason) { 16418 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16419 16420 String pkgName = newPackage.packageName; 16421 synchronized (mPackages) { 16422 //write settings. the installStatus will be incomplete at this stage. 16423 //note that the new package setting would have already been 16424 //added to mPackages. It hasn't been persisted yet. 16425 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16426 // TODO: Remove this write? It's also written at the end of this method 16427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16428 mSettings.writeLPr(); 16429 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16430 } 16431 16432 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16433 synchronized (mPackages) { 16434 updatePermissionsLPw(newPackage.packageName, newPackage, 16435 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16436 ? UPDATE_PERMISSIONS_ALL : 0)); 16437 // For system-bundled packages, we assume that installing an upgraded version 16438 // of the package implies that the user actually wants to run that new code, 16439 // so we enable the package. 16440 PackageSetting ps = mSettings.mPackages.get(pkgName); 16441 final int userId = user.getIdentifier(); 16442 if (ps != null) { 16443 if (isSystemApp(newPackage)) { 16444 if (DEBUG_INSTALL) { 16445 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16446 } 16447 // Enable system package for requested users 16448 if (res.origUsers != null) { 16449 for (int origUserId : res.origUsers) { 16450 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16451 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16452 origUserId, installerPackageName); 16453 } 16454 } 16455 } 16456 // Also convey the prior install/uninstall state 16457 if (allUsers != null && installedForUsers != null) { 16458 for (int currentUserId : allUsers) { 16459 final boolean installed = ArrayUtils.contains( 16460 installedForUsers, currentUserId); 16461 if (DEBUG_INSTALL) { 16462 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16463 } 16464 ps.setInstalled(installed, currentUserId); 16465 } 16466 // these install state changes will be persisted in the 16467 // upcoming call to mSettings.writeLPr(). 16468 } 16469 } 16470 // It's implied that when a user requests installation, they want the app to be 16471 // installed and enabled. 16472 if (userId != UserHandle.USER_ALL) { 16473 ps.setInstalled(true, userId); 16474 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16475 } 16476 16477 // When replacing an existing package, preserve the original install reason for all 16478 // users that had the package installed before. 16479 final Set<Integer> previousUserIds = new ArraySet<>(); 16480 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16481 final int installReasonCount = res.removedInfo.installReasons.size(); 16482 for (int i = 0; i < installReasonCount; i++) { 16483 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16484 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16485 ps.setInstallReason(previousInstallReason, previousUserId); 16486 previousUserIds.add(previousUserId); 16487 } 16488 } 16489 16490 // Set install reason for users that are having the package newly installed. 16491 if (userId == UserHandle.USER_ALL) { 16492 for (int currentUserId : sUserManager.getUserIds()) { 16493 if (!previousUserIds.contains(currentUserId)) { 16494 ps.setInstallReason(installReason, currentUserId); 16495 } 16496 } 16497 } else if (!previousUserIds.contains(userId)) { 16498 ps.setInstallReason(installReason, userId); 16499 } 16500 mSettings.writeKernelMappingLPr(ps); 16501 } 16502 res.name = pkgName; 16503 res.uid = newPackage.applicationInfo.uid; 16504 res.pkg = newPackage; 16505 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16506 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16507 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16508 //to update install status 16509 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16510 mSettings.writeLPr(); 16511 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16512 } 16513 16514 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16515 } 16516 16517 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16518 try { 16519 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16520 installPackageLI(args, res); 16521 } finally { 16522 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16523 } 16524 } 16525 16526 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16527 final int installFlags = args.installFlags; 16528 final String installerPackageName = args.installerPackageName; 16529 final String volumeUuid = args.volumeUuid; 16530 final File tmpPackageFile = new File(args.getCodePath()); 16531 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16532 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16533 || (args.volumeUuid != null)); 16534 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16535 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16536 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16537 boolean replace = false; 16538 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16539 if (args.move != null) { 16540 // moving a complete application; perform an initial scan on the new install location 16541 scanFlags |= SCAN_INITIAL; 16542 } 16543 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16544 scanFlags |= SCAN_DONT_KILL_APP; 16545 } 16546 if (instantApp) { 16547 scanFlags |= SCAN_AS_INSTANT_APP; 16548 } 16549 if (fullApp) { 16550 scanFlags |= SCAN_AS_FULL_APP; 16551 } 16552 16553 // Result object to be returned 16554 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16555 16556 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16557 16558 // Sanity check 16559 if (instantApp && (forwardLocked || onExternal)) { 16560 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16561 + " external=" + onExternal); 16562 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16563 return; 16564 } 16565 16566 // Retrieve PackageSettings and parse package 16567 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16568 | PackageParser.PARSE_ENFORCE_CODE 16569 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16570 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16571 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16572 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16573 PackageParser pp = new PackageParser(); 16574 pp.setSeparateProcesses(mSeparateProcesses); 16575 pp.setDisplayMetrics(mMetrics); 16576 16577 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16578 final PackageParser.Package pkg; 16579 try { 16580 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16581 } catch (PackageParserException e) { 16582 res.setError("Failed parse during installPackageLI", e); 16583 return; 16584 } finally { 16585 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16586 } 16587 16588// // Ephemeral apps must have target SDK >= O. 16589// // TODO: Update conditional and error message when O gets locked down 16590// if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16591// res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16592// "Ephemeral apps must have target SDK version of at least O"); 16593// return; 16594// } 16595 16596 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16597 // Static shared libraries have synthetic package names 16598 renameStaticSharedLibraryPackage(pkg); 16599 16600 // No static shared libs on external storage 16601 if (onExternal) { 16602 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16603 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16604 "Packages declaring static-shared libs cannot be updated"); 16605 return; 16606 } 16607 } 16608 16609 // If we are installing a clustered package add results for the children 16610 if (pkg.childPackages != null) { 16611 synchronized (mPackages) { 16612 final int childCount = pkg.childPackages.size(); 16613 for (int i = 0; i < childCount; i++) { 16614 PackageParser.Package childPkg = pkg.childPackages.get(i); 16615 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16616 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16617 childRes.pkg = childPkg; 16618 childRes.name = childPkg.packageName; 16619 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16620 if (childPs != null) { 16621 childRes.origUsers = childPs.queryInstalledUsers( 16622 sUserManager.getUserIds(), true); 16623 } 16624 if ((mPackages.containsKey(childPkg.packageName))) { 16625 childRes.removedInfo = new PackageRemovedInfo(); 16626 childRes.removedInfo.removedPackage = childPkg.packageName; 16627 } 16628 if (res.addedChildPackages == null) { 16629 res.addedChildPackages = new ArrayMap<>(); 16630 } 16631 res.addedChildPackages.put(childPkg.packageName, childRes); 16632 } 16633 } 16634 } 16635 16636 // If package doesn't declare API override, mark that we have an install 16637 // time CPU ABI override. 16638 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16639 pkg.cpuAbiOverride = args.abiOverride; 16640 } 16641 16642 String pkgName = res.name = pkg.packageName; 16643 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16644 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16645 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16646 return; 16647 } 16648 } 16649 16650 try { 16651 // either use what we've been given or parse directly from the APK 16652 if (args.certificates != null) { 16653 try { 16654 PackageParser.populateCertificates(pkg, args.certificates); 16655 } catch (PackageParserException e) { 16656 // there was something wrong with the certificates we were given; 16657 // try to pull them from the APK 16658 PackageParser.collectCertificates(pkg, parseFlags); 16659 } 16660 } else { 16661 PackageParser.collectCertificates(pkg, parseFlags); 16662 } 16663 } catch (PackageParserException e) { 16664 res.setError("Failed collect during installPackageLI", e); 16665 return; 16666 } 16667 16668 // Get rid of all references to package scan path via parser. 16669 pp = null; 16670 String oldCodePath = null; 16671 boolean systemApp = false; 16672 synchronized (mPackages) { 16673 // Check if installing already existing package 16674 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16675 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16676 if (pkg.mOriginalPackages != null 16677 && pkg.mOriginalPackages.contains(oldName) 16678 && mPackages.containsKey(oldName)) { 16679 // This package is derived from an original package, 16680 // and this device has been updating from that original 16681 // name. We must continue using the original name, so 16682 // rename the new package here. 16683 pkg.setPackageName(oldName); 16684 pkgName = pkg.packageName; 16685 replace = true; 16686 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16687 + oldName + " pkgName=" + pkgName); 16688 } else if (mPackages.containsKey(pkgName)) { 16689 // This package, under its official name, already exists 16690 // on the device; we should replace it. 16691 replace = true; 16692 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16693 } 16694 16695 // Child packages are installed through the parent package 16696 if (pkg.parentPackage != null) { 16697 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16698 "Package " + pkg.packageName + " is child of package " 16699 + pkg.parentPackage.parentPackage + ". Child packages " 16700 + "can be updated only through the parent package."); 16701 return; 16702 } 16703 16704 if (replace) { 16705 // Prevent apps opting out from runtime permissions 16706 PackageParser.Package oldPackage = mPackages.get(pkgName); 16707 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16708 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16709 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16710 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16711 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16712 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16713 + " doesn't support runtime permissions but the old" 16714 + " target SDK " + oldTargetSdk + " does."); 16715 return; 16716 } 16717 16718 // Prevent installing of child packages 16719 if (oldPackage.parentPackage != null) { 16720 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16721 "Package " + pkg.packageName + " is child of package " 16722 + oldPackage.parentPackage + ". Child packages " 16723 + "can be updated only through the parent package."); 16724 return; 16725 } 16726 } 16727 } 16728 16729 PackageSetting ps = mSettings.mPackages.get(pkgName); 16730 if (ps != null) { 16731 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16732 16733 // Static shared libs have same package with different versions where 16734 // we internally use a synthetic package name to allow multiple versions 16735 // of the same package, therefore we need to compare signatures against 16736 // the package setting for the latest library version. 16737 PackageSetting signatureCheckPs = ps; 16738 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16739 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16740 if (libraryEntry != null) { 16741 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16742 } 16743 } 16744 16745 // Quick sanity check that we're signed correctly if updating; 16746 // we'll check this again later when scanning, but we want to 16747 // bail early here before tripping over redefined permissions. 16748 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16749 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16750 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16751 + pkg.packageName + " upgrade keys do not match the " 16752 + "previously installed version"); 16753 return; 16754 } 16755 } else { 16756 try { 16757 verifySignaturesLP(signatureCheckPs, pkg); 16758 } catch (PackageManagerException e) { 16759 res.setError(e.error, e.getMessage()); 16760 return; 16761 } 16762 } 16763 16764 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16765 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16766 systemApp = (ps.pkg.applicationInfo.flags & 16767 ApplicationInfo.FLAG_SYSTEM) != 0; 16768 } 16769 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16770 } 16771 16772 // Check whether the newly-scanned package wants to define an already-defined perm 16773 int N = pkg.permissions.size(); 16774 for (int i = N-1; i >= 0; i--) { 16775 PackageParser.Permission perm = pkg.permissions.get(i); 16776 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16777 if (bp != null) { 16778 // If the defining package is signed with our cert, it's okay. This 16779 // also includes the "updating the same package" case, of course. 16780 // "updating same package" could also involve key-rotation. 16781 final boolean sigsOk; 16782 if (bp.sourcePackage.equals(pkg.packageName) 16783 && (bp.packageSetting instanceof PackageSetting) 16784 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16785 scanFlags))) { 16786 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16787 } else { 16788 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16789 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16790 } 16791 if (!sigsOk) { 16792 // If the owning package is the system itself, we log but allow 16793 // install to proceed; we fail the install on all other permission 16794 // redefinitions. 16795 if (!bp.sourcePackage.equals("android")) { 16796 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16797 + pkg.packageName + " attempting to redeclare permission " 16798 + perm.info.name + " already owned by " + bp.sourcePackage); 16799 res.origPermission = perm.info.name; 16800 res.origPackage = bp.sourcePackage; 16801 return; 16802 } else { 16803 Slog.w(TAG, "Package " + pkg.packageName 16804 + " attempting to redeclare system permission " 16805 + perm.info.name + "; ignoring new declaration"); 16806 pkg.permissions.remove(i); 16807 } 16808 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16809 // Prevent apps to change protection level to dangerous from any other 16810 // type as this would allow a privilege escalation where an app adds a 16811 // normal/signature permission in other app's group and later redefines 16812 // it as dangerous leading to the group auto-grant. 16813 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16814 == PermissionInfo.PROTECTION_DANGEROUS) { 16815 if (bp != null && !bp.isRuntime()) { 16816 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16817 + "non-runtime permission " + perm.info.name 16818 + " to runtime; keeping old protection level"); 16819 perm.info.protectionLevel = bp.protectionLevel; 16820 } 16821 } 16822 } 16823 } 16824 } 16825 } 16826 16827 if (systemApp) { 16828 if (onExternal) { 16829 // Abort update; system app can't be replaced with app on sdcard 16830 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16831 "Cannot install updates to system apps on sdcard"); 16832 return; 16833 } else if (instantApp) { 16834 // Abort update; system app can't be replaced with an instant app 16835 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16836 "Cannot update a system app with an instant app"); 16837 return; 16838 } 16839 } 16840 16841 if (args.move != null) { 16842 // We did an in-place move, so dex is ready to roll 16843 scanFlags |= SCAN_NO_DEX; 16844 scanFlags |= SCAN_MOVE; 16845 16846 synchronized (mPackages) { 16847 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16848 if (ps == null) { 16849 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16850 "Missing settings for moved package " + pkgName); 16851 } 16852 16853 // We moved the entire application as-is, so bring over the 16854 // previously derived ABI information. 16855 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16856 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16857 } 16858 16859 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16860 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16861 scanFlags |= SCAN_NO_DEX; 16862 16863 try { 16864 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16865 args.abiOverride : pkg.cpuAbiOverride); 16866 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16867 true /*extractLibs*/, mAppLib32InstallDir); 16868 } catch (PackageManagerException pme) { 16869 Slog.e(TAG, "Error deriving application ABI", pme); 16870 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16871 return; 16872 } 16873 16874 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16875 // Do not run PackageDexOptimizer through the local performDexOpt 16876 // method because `pkg` may not be in `mPackages` yet. 16877 // 16878 // Also, don't fail application installs if the dexopt step fails. 16879 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16880 null /* instructionSets */, false /* checkProfiles */, 16881 getCompilerFilterForReason(REASON_INSTALL), 16882 getOrCreateCompilerPackageStats(pkg)); 16883 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16884 16885 // Notify BackgroundDexOptJobService that the package has been changed. 16886 // If this is an update of a package which used to fail to compile, 16887 // BDOS will remove it from its blacklist. 16888 // TODO: Layering violation 16889 BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName); 16890 } 16891 16892 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16893 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16894 return; 16895 } 16896 16897 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16898 16899 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16900 "installPackageLI")) { 16901 if (replace) { 16902 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16903 // Static libs have a synthetic package name containing the version 16904 // and cannot be updated as an update would get a new package name, 16905 // unless this is the exact same version code which is useful for 16906 // development. 16907 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16908 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16909 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16910 + "static-shared libs cannot be updated"); 16911 return; 16912 } 16913 } 16914 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16915 installerPackageName, res, args.installReason); 16916 } else { 16917 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16918 args.user, installerPackageName, volumeUuid, res, args.installReason); 16919 } 16920 } 16921 synchronized (mPackages) { 16922 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16923 if (ps != null) { 16924 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16925 } 16926 16927 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16928 for (int i = 0; i < childCount; i++) { 16929 PackageParser.Package childPkg = pkg.childPackages.get(i); 16930 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16931 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16932 if (childPs != null) { 16933 childRes.newUsers = childPs.queryInstalledUsers( 16934 sUserManager.getUserIds(), true); 16935 } 16936 } 16937 16938 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16939 updateSequenceNumberLP(pkgName, res.newUsers); 16940 } 16941 } 16942 } 16943 16944 private void startIntentFilterVerifications(int userId, boolean replacing, 16945 PackageParser.Package pkg) { 16946 if (mIntentFilterVerifierComponent == null) { 16947 Slog.w(TAG, "No IntentFilter verification will not be done as " 16948 + "there is no IntentFilterVerifier available!"); 16949 return; 16950 } 16951 16952 final int verifierUid = getPackageUid( 16953 mIntentFilterVerifierComponent.getPackageName(), 16954 MATCH_DEBUG_TRIAGED_MISSING, 16955 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16956 16957 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16958 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16959 mHandler.sendMessage(msg); 16960 16961 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16962 for (int i = 0; i < childCount; i++) { 16963 PackageParser.Package childPkg = pkg.childPackages.get(i); 16964 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16965 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16966 mHandler.sendMessage(msg); 16967 } 16968 } 16969 16970 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16971 PackageParser.Package pkg) { 16972 int size = pkg.activities.size(); 16973 if (size == 0) { 16974 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16975 "No activity, so no need to verify any IntentFilter!"); 16976 return; 16977 } 16978 16979 final boolean hasDomainURLs = hasDomainURLs(pkg); 16980 if (!hasDomainURLs) { 16981 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16982 "No domain URLs, so no need to verify any IntentFilter!"); 16983 return; 16984 } 16985 16986 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16987 + " if any IntentFilter from the " + size 16988 + " Activities needs verification ..."); 16989 16990 int count = 0; 16991 final String packageName = pkg.packageName; 16992 16993 synchronized (mPackages) { 16994 // If this is a new install and we see that we've already run verification for this 16995 // package, we have nothing to do: it means the state was restored from backup. 16996 if (!replacing) { 16997 IntentFilterVerificationInfo ivi = 16998 mSettings.getIntentFilterVerificationLPr(packageName); 16999 if (ivi != null) { 17000 if (DEBUG_DOMAIN_VERIFICATION) { 17001 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17002 + ivi.getStatusString()); 17003 } 17004 return; 17005 } 17006 } 17007 17008 // If any filters need to be verified, then all need to be. 17009 boolean needToVerify = false; 17010 for (PackageParser.Activity a : pkg.activities) { 17011 for (ActivityIntentInfo filter : a.intents) { 17012 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17013 if (DEBUG_DOMAIN_VERIFICATION) { 17014 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17015 } 17016 needToVerify = true; 17017 break; 17018 } 17019 } 17020 } 17021 17022 if (needToVerify) { 17023 final int verificationId = mIntentFilterVerificationToken++; 17024 for (PackageParser.Activity a : pkg.activities) { 17025 for (ActivityIntentInfo filter : a.intents) { 17026 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17027 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17028 "Verification needed for IntentFilter:" + filter.toString()); 17029 mIntentFilterVerifier.addOneIntentFilterVerification( 17030 verifierUid, userId, verificationId, filter, packageName); 17031 count++; 17032 } 17033 } 17034 } 17035 } 17036 } 17037 17038 if (count > 0) { 17039 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17040 + " IntentFilter verification" + (count > 1 ? "s" : "") 17041 + " for userId:" + userId); 17042 mIntentFilterVerifier.startVerifications(userId); 17043 } else { 17044 if (DEBUG_DOMAIN_VERIFICATION) { 17045 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17046 } 17047 } 17048 } 17049 17050 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17051 final ComponentName cn = filter.activity.getComponentName(); 17052 final String packageName = cn.getPackageName(); 17053 17054 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17055 packageName); 17056 if (ivi == null) { 17057 return true; 17058 } 17059 int status = ivi.getStatus(); 17060 switch (status) { 17061 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17062 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17063 return true; 17064 17065 default: 17066 // Nothing to do 17067 return false; 17068 } 17069 } 17070 17071 private static boolean isMultiArch(ApplicationInfo info) { 17072 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17073 } 17074 17075 private static boolean isExternal(PackageParser.Package pkg) { 17076 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17077 } 17078 17079 private static boolean isExternal(PackageSetting ps) { 17080 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17081 } 17082 17083 private static boolean isSystemApp(PackageParser.Package pkg) { 17084 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17085 } 17086 17087 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17088 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17089 } 17090 17091 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17092 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17093 } 17094 17095 private static boolean isSystemApp(PackageSetting ps) { 17096 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17097 } 17098 17099 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17100 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17101 } 17102 17103 private int packageFlagsToInstallFlags(PackageSetting ps) { 17104 int installFlags = 0; 17105 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17106 // This existing package was an external ASEC install when we have 17107 // the external flag without a UUID 17108 installFlags |= PackageManager.INSTALL_EXTERNAL; 17109 } 17110 if (ps.isForwardLocked()) { 17111 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17112 } 17113 return installFlags; 17114 } 17115 17116 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17117 if (isExternal(pkg)) { 17118 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17119 return StorageManager.UUID_PRIMARY_PHYSICAL; 17120 } else { 17121 return pkg.volumeUuid; 17122 } 17123 } else { 17124 return StorageManager.UUID_PRIVATE_INTERNAL; 17125 } 17126 } 17127 17128 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17129 if (isExternal(pkg)) { 17130 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17131 return mSettings.getExternalVersion(); 17132 } else { 17133 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17134 } 17135 } else { 17136 return mSettings.getInternalVersion(); 17137 } 17138 } 17139 17140 private void deleteTempPackageFiles() { 17141 final FilenameFilter filter = new FilenameFilter() { 17142 public boolean accept(File dir, String name) { 17143 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17144 } 17145 }; 17146 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17147 file.delete(); 17148 } 17149 } 17150 17151 @Override 17152 public void deletePackageAsUser(String packageName, int versionCode, 17153 IPackageDeleteObserver observer, int userId, int flags) { 17154 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17155 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17156 } 17157 17158 @Override 17159 public void deletePackageVersioned(VersionedPackage versionedPackage, 17160 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17161 mContext.enforceCallingOrSelfPermission( 17162 android.Manifest.permission.DELETE_PACKAGES, null); 17163 Preconditions.checkNotNull(versionedPackage); 17164 Preconditions.checkNotNull(observer); 17165 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17166 PackageManager.VERSION_CODE_HIGHEST, 17167 Integer.MAX_VALUE, "versionCode must be >= -1"); 17168 17169 final String packageName = versionedPackage.getPackageName(); 17170 // TODO: We will change version code to long, so in the new API it is long 17171 final int versionCode = (int) versionedPackage.getVersionCode(); 17172 final String internalPackageName; 17173 synchronized (mPackages) { 17174 // Normalize package name to handle renamed packages and static libs 17175 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17176 // TODO: We will change version code to long, so in the new API it is long 17177 (int) versionedPackage.getVersionCode()); 17178 } 17179 17180 final int uid = Binder.getCallingUid(); 17181 if (!isOrphaned(internalPackageName) 17182 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17183 try { 17184 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17185 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17186 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17187 observer.onUserActionRequired(intent); 17188 } catch (RemoteException re) { 17189 } 17190 return; 17191 } 17192 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17193 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17194 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17195 mContext.enforceCallingOrSelfPermission( 17196 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17197 "deletePackage for user " + userId); 17198 } 17199 17200 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17201 try { 17202 observer.onPackageDeleted(packageName, 17203 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17204 } catch (RemoteException re) { 17205 } 17206 return; 17207 } 17208 17209 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17210 try { 17211 observer.onPackageDeleted(packageName, 17212 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17213 } catch (RemoteException re) { 17214 } 17215 return; 17216 } 17217 17218 if (DEBUG_REMOVE) { 17219 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17220 + " deleteAllUsers: " + deleteAllUsers + " version=" 17221 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17222 ? "VERSION_CODE_HIGHEST" : versionCode)); 17223 } 17224 // Queue up an async operation since the package deletion may take a little while. 17225 mHandler.post(new Runnable() { 17226 public void run() { 17227 mHandler.removeCallbacks(this); 17228 int returnCode; 17229 if (!deleteAllUsers) { 17230 returnCode = deletePackageX(internalPackageName, versionCode, 17231 userId, deleteFlags); 17232 } else { 17233 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17234 internalPackageName, users); 17235 // If nobody is blocking uninstall, proceed with delete for all users 17236 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17237 returnCode = deletePackageX(internalPackageName, versionCode, 17238 userId, deleteFlags); 17239 } else { 17240 // Otherwise uninstall individually for users with blockUninstalls=false 17241 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17242 for (int userId : users) { 17243 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17244 returnCode = deletePackageX(internalPackageName, versionCode, 17245 userId, userFlags); 17246 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17247 Slog.w(TAG, "Package delete failed for user " + userId 17248 + ", returnCode " + returnCode); 17249 } 17250 } 17251 } 17252 // The app has only been marked uninstalled for certain users. 17253 // We still need to report that delete was blocked 17254 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17255 } 17256 } 17257 try { 17258 observer.onPackageDeleted(packageName, returnCode, null); 17259 } catch (RemoteException e) { 17260 Log.i(TAG, "Observer no longer exists."); 17261 } //end catch 17262 } //end run 17263 }); 17264 } 17265 17266 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17267 if (pkg.staticSharedLibName != null) { 17268 return pkg.manifestPackageName; 17269 } 17270 return pkg.packageName; 17271 } 17272 17273 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17274 // Handle renamed packages 17275 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17276 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17277 17278 // Is this a static library? 17279 SparseArray<SharedLibraryEntry> versionedLib = 17280 mStaticLibsByDeclaringPackage.get(packageName); 17281 if (versionedLib == null || versionedLib.size() <= 0) { 17282 return packageName; 17283 } 17284 17285 // Figure out which lib versions the caller can see 17286 SparseIntArray versionsCallerCanSee = null; 17287 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17288 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17289 && callingAppId != Process.ROOT_UID) { 17290 versionsCallerCanSee = new SparseIntArray(); 17291 String libName = versionedLib.valueAt(0).info.getName(); 17292 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17293 if (uidPackages != null) { 17294 for (String uidPackage : uidPackages) { 17295 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17296 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17297 if (libIdx >= 0) { 17298 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17299 versionsCallerCanSee.append(libVersion, libVersion); 17300 } 17301 } 17302 } 17303 } 17304 17305 // Caller can see nothing - done 17306 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17307 return packageName; 17308 } 17309 17310 // Find the version the caller can see and the app version code 17311 SharedLibraryEntry highestVersion = null; 17312 final int versionCount = versionedLib.size(); 17313 for (int i = 0; i < versionCount; i++) { 17314 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17315 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17316 libEntry.info.getVersion()) < 0) { 17317 continue; 17318 } 17319 // TODO: We will change version code to long, so in the new API it is long 17320 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17321 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17322 if (libVersionCode == versionCode) { 17323 return libEntry.apk; 17324 } 17325 } else if (highestVersion == null) { 17326 highestVersion = libEntry; 17327 } else if (libVersionCode > highestVersion.info 17328 .getDeclaringPackage().getVersionCode()) { 17329 highestVersion = libEntry; 17330 } 17331 } 17332 17333 if (highestVersion != null) { 17334 return highestVersion.apk; 17335 } 17336 17337 return packageName; 17338 } 17339 17340 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17341 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17342 || callingUid == Process.SYSTEM_UID) { 17343 return true; 17344 } 17345 final int callingUserId = UserHandle.getUserId(callingUid); 17346 // If the caller installed the pkgName, then allow it to silently uninstall. 17347 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17348 return true; 17349 } 17350 17351 // Allow package verifier to silently uninstall. 17352 if (mRequiredVerifierPackage != null && 17353 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17354 return true; 17355 } 17356 17357 // Allow package uninstaller to silently uninstall. 17358 if (mRequiredUninstallerPackage != null && 17359 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17360 return true; 17361 } 17362 17363 // Allow storage manager to silently uninstall. 17364 if (mStorageManagerPackage != null && 17365 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17366 return true; 17367 } 17368 return false; 17369 } 17370 17371 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17372 int[] result = EMPTY_INT_ARRAY; 17373 for (int userId : userIds) { 17374 if (getBlockUninstallForUser(packageName, userId)) { 17375 result = ArrayUtils.appendInt(result, userId); 17376 } 17377 } 17378 return result; 17379 } 17380 17381 @Override 17382 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17383 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17384 } 17385 17386 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17387 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17388 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17389 try { 17390 if (dpm != null) { 17391 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17392 /* callingUserOnly =*/ false); 17393 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17394 : deviceOwnerComponentName.getPackageName(); 17395 // Does the package contains the device owner? 17396 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17397 // this check is probably not needed, since DO should be registered as a device 17398 // admin on some user too. (Original bug for this: b/17657954) 17399 if (packageName.equals(deviceOwnerPackageName)) { 17400 return true; 17401 } 17402 // Does it contain a device admin for any user? 17403 int[] users; 17404 if (userId == UserHandle.USER_ALL) { 17405 users = sUserManager.getUserIds(); 17406 } else { 17407 users = new int[]{userId}; 17408 } 17409 for (int i = 0; i < users.length; ++i) { 17410 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17411 return true; 17412 } 17413 } 17414 } 17415 } catch (RemoteException e) { 17416 } 17417 return false; 17418 } 17419 17420 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17421 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17422 } 17423 17424 /** 17425 * This method is an internal method that could be get invoked either 17426 * to delete an installed package or to clean up a failed installation. 17427 * After deleting an installed package, a broadcast is sent to notify any 17428 * listeners that the package has been removed. For cleaning up a failed 17429 * installation, the broadcast is not necessary since the package's 17430 * installation wouldn't have sent the initial broadcast either 17431 * The key steps in deleting a package are 17432 * deleting the package information in internal structures like mPackages, 17433 * deleting the packages base directories through installd 17434 * updating mSettings to reflect current status 17435 * persisting settings for later use 17436 * sending a broadcast if necessary 17437 */ 17438 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17439 final PackageRemovedInfo info = new PackageRemovedInfo(); 17440 final boolean res; 17441 17442 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17443 ? UserHandle.USER_ALL : userId; 17444 17445 if (isPackageDeviceAdmin(packageName, removeUser)) { 17446 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17447 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17448 } 17449 17450 PackageSetting uninstalledPs = null; 17451 17452 // for the uninstall-updates case and restricted profiles, remember the per- 17453 // user handle installed state 17454 int[] allUsers; 17455 synchronized (mPackages) { 17456 uninstalledPs = mSettings.mPackages.get(packageName); 17457 if (uninstalledPs == null) { 17458 Slog.w(TAG, "Not removing non-existent package " + packageName); 17459 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17460 } 17461 17462 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17463 && uninstalledPs.versionCode != versionCode) { 17464 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17465 + uninstalledPs.versionCode + " != " + versionCode); 17466 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17467 } 17468 17469 // Static shared libs can be declared by any package, so let us not 17470 // allow removing a package if it provides a lib others depend on. 17471 PackageParser.Package pkg = mPackages.get(packageName); 17472 if (pkg != null && pkg.staticSharedLibName != null) { 17473 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17474 pkg.staticSharedLibVersion); 17475 if (libEntry != null) { 17476 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17477 libEntry.info, 0, userId); 17478 if (!ArrayUtils.isEmpty(libClientPackages)) { 17479 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17480 + " hosting lib " + libEntry.info.getName() + " version " 17481 + libEntry.info.getVersion() + " used by " + libClientPackages); 17482 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17483 } 17484 } 17485 } 17486 17487 allUsers = sUserManager.getUserIds(); 17488 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17489 } 17490 17491 final int freezeUser; 17492 if (isUpdatedSystemApp(uninstalledPs) 17493 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17494 // We're downgrading a system app, which will apply to all users, so 17495 // freeze them all during the downgrade 17496 freezeUser = UserHandle.USER_ALL; 17497 } else { 17498 freezeUser = removeUser; 17499 } 17500 17501 synchronized (mInstallLock) { 17502 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17503 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17504 deleteFlags, "deletePackageX")) { 17505 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17506 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17507 } 17508 synchronized (mPackages) { 17509 if (res) { 17510 mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg, 17511 info.removedUsers); 17512 updateSequenceNumberLP(packageName, info.removedUsers); 17513 } 17514 } 17515 } 17516 17517 if (res) { 17518 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17519 info.sendPackageRemovedBroadcasts(killApp); 17520 info.sendSystemPackageUpdatedBroadcasts(); 17521 info.sendSystemPackageAppearedBroadcasts(); 17522 } 17523 // Force a gc here. 17524 Runtime.getRuntime().gc(); 17525 // Delete the resources here after sending the broadcast to let 17526 // other processes clean up before deleting resources. 17527 if (info.args != null) { 17528 synchronized (mInstallLock) { 17529 info.args.doPostDeleteLI(true); 17530 } 17531 } 17532 17533 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17534 } 17535 17536 class PackageRemovedInfo { 17537 String removedPackage; 17538 int uid = -1; 17539 int removedAppId = -1; 17540 int[] origUsers; 17541 int[] removedUsers = null; 17542 SparseArray<Integer> installReasons; 17543 boolean isRemovedPackageSystemUpdate = false; 17544 boolean isUpdate; 17545 boolean dataRemoved; 17546 boolean removedForAllUsers; 17547 boolean isStaticSharedLib; 17548 // Clean up resources deleted packages. 17549 InstallArgs args = null; 17550 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17551 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17552 17553 void sendPackageRemovedBroadcasts(boolean killApp) { 17554 sendPackageRemovedBroadcastInternal(killApp); 17555 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17556 for (int i = 0; i < childCount; i++) { 17557 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17558 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17559 } 17560 } 17561 17562 void sendSystemPackageUpdatedBroadcasts() { 17563 if (isRemovedPackageSystemUpdate) { 17564 sendSystemPackageUpdatedBroadcastsInternal(); 17565 final int childCount = (removedChildPackages != null) 17566 ? removedChildPackages.size() : 0; 17567 for (int i = 0; i < childCount; i++) { 17568 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17569 if (childInfo.isRemovedPackageSystemUpdate) { 17570 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17571 } 17572 } 17573 } 17574 } 17575 17576 void sendSystemPackageAppearedBroadcasts() { 17577 final int packageCount = (appearedChildPackages != null) 17578 ? appearedChildPackages.size() : 0; 17579 for (int i = 0; i < packageCount; i++) { 17580 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17581 sendPackageAddedForNewUsers(installedInfo.name, true, 17582 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17583 } 17584 } 17585 17586 private void sendSystemPackageUpdatedBroadcastsInternal() { 17587 Bundle extras = new Bundle(2); 17588 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17589 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17590 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17591 extras, 0, null, null, null); 17592 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17593 extras, 0, null, null, null); 17594 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17595 null, 0, removedPackage, null, null); 17596 } 17597 17598 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17599 // Don't send static shared library removal broadcasts as these 17600 // libs are visible only the the apps that depend on them an one 17601 // cannot remove the library if it has a dependency. 17602 if (isStaticSharedLib) { 17603 return; 17604 } 17605 Bundle extras = new Bundle(2); 17606 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17607 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17608 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17609 if (isUpdate || isRemovedPackageSystemUpdate) { 17610 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17611 } 17612 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17613 if (removedPackage != null) { 17614 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17615 extras, 0, null, null, removedUsers); 17616 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17617 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17618 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17619 null, null, removedUsers); 17620 } 17621 } 17622 if (removedAppId >= 0) { 17623 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17624 removedUsers); 17625 } 17626 } 17627 } 17628 17629 /* 17630 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17631 * flag is not set, the data directory is removed as well. 17632 * make sure this flag is set for partially installed apps. If not its meaningless to 17633 * delete a partially installed application. 17634 */ 17635 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17636 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17637 String packageName = ps.name; 17638 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17639 // Retrieve object to delete permissions for shared user later on 17640 final PackageParser.Package deletedPkg; 17641 final PackageSetting deletedPs; 17642 // reader 17643 synchronized (mPackages) { 17644 deletedPkg = mPackages.get(packageName); 17645 deletedPs = mSettings.mPackages.get(packageName); 17646 if (outInfo != null) { 17647 outInfo.removedPackage = packageName; 17648 outInfo.isStaticSharedLib = deletedPkg != null 17649 && deletedPkg.staticSharedLibName != null; 17650 outInfo.removedUsers = deletedPs != null 17651 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17652 : null; 17653 } 17654 } 17655 17656 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17657 17658 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17659 final PackageParser.Package resolvedPkg; 17660 if (deletedPkg != null) { 17661 resolvedPkg = deletedPkg; 17662 } else { 17663 // We don't have a parsed package when it lives on an ejected 17664 // adopted storage device, so fake something together 17665 resolvedPkg = new PackageParser.Package(ps.name); 17666 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17667 } 17668 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17669 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17670 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17671 if (outInfo != null) { 17672 outInfo.dataRemoved = true; 17673 } 17674 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17675 } 17676 17677 int removedAppId = -1; 17678 17679 // writer 17680 synchronized (mPackages) { 17681 boolean installedStateChanged = false; 17682 if (deletedPs != null) { 17683 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17684 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17685 clearDefaultBrowserIfNeeded(packageName); 17686 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17687 removedAppId = mSettings.removePackageLPw(packageName); 17688 if (outInfo != null) { 17689 outInfo.removedAppId = removedAppId; 17690 } 17691 updatePermissionsLPw(deletedPs.name, null, 0); 17692 if (deletedPs.sharedUser != null) { 17693 // Remove permissions associated with package. Since runtime 17694 // permissions are per user we have to kill the removed package 17695 // or packages running under the shared user of the removed 17696 // package if revoking the permissions requested only by the removed 17697 // package is successful and this causes a change in gids. 17698 for (int userId : UserManagerService.getInstance().getUserIds()) { 17699 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17700 userId); 17701 if (userIdToKill == UserHandle.USER_ALL 17702 || userIdToKill >= UserHandle.USER_SYSTEM) { 17703 // If gids changed for this user, kill all affected packages. 17704 mHandler.post(new Runnable() { 17705 @Override 17706 public void run() { 17707 // This has to happen with no lock held. 17708 killApplication(deletedPs.name, deletedPs.appId, 17709 KILL_APP_REASON_GIDS_CHANGED); 17710 } 17711 }); 17712 break; 17713 } 17714 } 17715 } 17716 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17717 } 17718 // make sure to preserve per-user disabled state if this removal was just 17719 // a downgrade of a system app to the factory package 17720 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17721 if (DEBUG_REMOVE) { 17722 Slog.d(TAG, "Propagating install state across downgrade"); 17723 } 17724 for (int userId : allUserHandles) { 17725 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17726 if (DEBUG_REMOVE) { 17727 Slog.d(TAG, " user " + userId + " => " + installed); 17728 } 17729 if (installed != ps.getInstalled(userId)) { 17730 installedStateChanged = true; 17731 } 17732 ps.setInstalled(installed, userId); 17733 } 17734 } 17735 } 17736 // can downgrade to reader 17737 if (writeSettings) { 17738 // Save settings now 17739 mSettings.writeLPr(); 17740 } 17741 if (installedStateChanged) { 17742 mSettings.writeKernelMappingLPr(ps); 17743 } 17744 } 17745 if (removedAppId != -1) { 17746 // A user ID was deleted here. Go through all users and remove it 17747 // from KeyStore. 17748 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17749 } 17750 } 17751 17752 static boolean locationIsPrivileged(File path) { 17753 try { 17754 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17755 .getCanonicalPath(); 17756 return path.getCanonicalPath().startsWith(privilegedAppDir); 17757 } catch (IOException e) { 17758 Slog.e(TAG, "Unable to access code path " + path); 17759 } 17760 return false; 17761 } 17762 17763 /* 17764 * Tries to delete system package. 17765 */ 17766 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17767 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17768 boolean writeSettings) { 17769 if (deletedPs.parentPackageName != null) { 17770 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17771 return false; 17772 } 17773 17774 final boolean applyUserRestrictions 17775 = (allUserHandles != null) && (outInfo.origUsers != null); 17776 final PackageSetting disabledPs; 17777 // Confirm if the system package has been updated 17778 // An updated system app can be deleted. This will also have to restore 17779 // the system pkg from system partition 17780 // reader 17781 synchronized (mPackages) { 17782 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17783 } 17784 17785 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17786 + " disabledPs=" + disabledPs); 17787 17788 if (disabledPs == null) { 17789 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17790 return false; 17791 } else if (DEBUG_REMOVE) { 17792 Slog.d(TAG, "Deleting system pkg from data partition"); 17793 } 17794 17795 if (DEBUG_REMOVE) { 17796 if (applyUserRestrictions) { 17797 Slog.d(TAG, "Remembering install states:"); 17798 for (int userId : allUserHandles) { 17799 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17800 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17801 } 17802 } 17803 } 17804 17805 // Delete the updated package 17806 outInfo.isRemovedPackageSystemUpdate = true; 17807 if (outInfo.removedChildPackages != null) { 17808 final int childCount = (deletedPs.childPackageNames != null) 17809 ? deletedPs.childPackageNames.size() : 0; 17810 for (int i = 0; i < childCount; i++) { 17811 String childPackageName = deletedPs.childPackageNames.get(i); 17812 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17813 .contains(childPackageName)) { 17814 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17815 childPackageName); 17816 if (childInfo != null) { 17817 childInfo.isRemovedPackageSystemUpdate = true; 17818 } 17819 } 17820 } 17821 } 17822 17823 if (disabledPs.versionCode < deletedPs.versionCode) { 17824 // Delete data for downgrades 17825 flags &= ~PackageManager.DELETE_KEEP_DATA; 17826 } else { 17827 // Preserve data by setting flag 17828 flags |= PackageManager.DELETE_KEEP_DATA; 17829 } 17830 17831 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17832 outInfo, writeSettings, disabledPs.pkg); 17833 if (!ret) { 17834 return false; 17835 } 17836 17837 // writer 17838 synchronized (mPackages) { 17839 // Reinstate the old system package 17840 enableSystemPackageLPw(disabledPs.pkg); 17841 // Remove any native libraries from the upgraded package. 17842 removeNativeBinariesLI(deletedPs); 17843 } 17844 17845 // Install the system package 17846 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17847 int parseFlags = mDefParseFlags 17848 | PackageParser.PARSE_MUST_BE_APK 17849 | PackageParser.PARSE_IS_SYSTEM 17850 | PackageParser.PARSE_IS_SYSTEM_DIR; 17851 if (locationIsPrivileged(disabledPs.codePath)) { 17852 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17853 } 17854 17855 final PackageParser.Package newPkg; 17856 try { 17857 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17858 0 /* currentTime */, null); 17859 } catch (PackageManagerException e) { 17860 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17861 + e.getMessage()); 17862 return false; 17863 } 17864 17865 try { 17866 // update shared libraries for the newly re-installed system package 17867 updateSharedLibrariesLPr(newPkg, null); 17868 } catch (PackageManagerException e) { 17869 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17870 } 17871 17872 prepareAppDataAfterInstallLIF(newPkg); 17873 17874 // writer 17875 synchronized (mPackages) { 17876 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17877 17878 // Propagate the permissions state as we do not want to drop on the floor 17879 // runtime permissions. The update permissions method below will take 17880 // care of removing obsolete permissions and grant install permissions. 17881 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17882 updatePermissionsLPw(newPkg.packageName, newPkg, 17883 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17884 17885 if (applyUserRestrictions) { 17886 boolean installedStateChanged = false; 17887 if (DEBUG_REMOVE) { 17888 Slog.d(TAG, "Propagating install state across reinstall"); 17889 } 17890 for (int userId : allUserHandles) { 17891 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17892 if (DEBUG_REMOVE) { 17893 Slog.d(TAG, " user " + userId + " => " + installed); 17894 } 17895 if (installed != ps.getInstalled(userId)) { 17896 installedStateChanged = true; 17897 } 17898 ps.setInstalled(installed, userId); 17899 17900 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17901 } 17902 // Regardless of writeSettings we need to ensure that this restriction 17903 // state propagation is persisted 17904 mSettings.writeAllUsersPackageRestrictionsLPr(); 17905 if (installedStateChanged) { 17906 mSettings.writeKernelMappingLPr(ps); 17907 } 17908 } 17909 // can downgrade to reader here 17910 if (writeSettings) { 17911 mSettings.writeLPr(); 17912 } 17913 } 17914 return true; 17915 } 17916 17917 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17918 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17919 PackageRemovedInfo outInfo, boolean writeSettings, 17920 PackageParser.Package replacingPackage) { 17921 synchronized (mPackages) { 17922 if (outInfo != null) { 17923 outInfo.uid = ps.appId; 17924 } 17925 17926 if (outInfo != null && outInfo.removedChildPackages != null) { 17927 final int childCount = (ps.childPackageNames != null) 17928 ? ps.childPackageNames.size() : 0; 17929 for (int i = 0; i < childCount; i++) { 17930 String childPackageName = ps.childPackageNames.get(i); 17931 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17932 if (childPs == null) { 17933 return false; 17934 } 17935 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17936 childPackageName); 17937 if (childInfo != null) { 17938 childInfo.uid = childPs.appId; 17939 } 17940 } 17941 } 17942 } 17943 17944 // Delete package data from internal structures and also remove data if flag is set 17945 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17946 17947 // Delete the child packages data 17948 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17949 for (int i = 0; i < childCount; i++) { 17950 PackageSetting childPs; 17951 synchronized (mPackages) { 17952 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17953 } 17954 if (childPs != null) { 17955 PackageRemovedInfo childOutInfo = (outInfo != null 17956 && outInfo.removedChildPackages != null) 17957 ? outInfo.removedChildPackages.get(childPs.name) : null; 17958 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17959 && (replacingPackage != null 17960 && !replacingPackage.hasChildPackage(childPs.name)) 17961 ? flags & ~DELETE_KEEP_DATA : flags; 17962 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17963 deleteFlags, writeSettings); 17964 } 17965 } 17966 17967 // Delete application code and resources only for parent packages 17968 if (ps.parentPackageName == null) { 17969 if (deleteCodeAndResources && (outInfo != null)) { 17970 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17971 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17972 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17973 } 17974 } 17975 17976 return true; 17977 } 17978 17979 @Override 17980 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 17981 int userId) { 17982 mContext.enforceCallingOrSelfPermission( 17983 android.Manifest.permission.DELETE_PACKAGES, null); 17984 synchronized (mPackages) { 17985 PackageSetting ps = mSettings.mPackages.get(packageName); 17986 if (ps == null) { 17987 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 17988 return false; 17989 } 17990 // Cannot block uninstall of static shared libs as they are 17991 // considered a part of the using app (emulating static linking). 17992 // Also static libs are installed always on internal storage. 17993 PackageParser.Package pkg = mPackages.get(packageName); 17994 if (pkg != null && pkg.staticSharedLibName != null) { 17995 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 17996 + " providing static shared library: " + pkg.staticSharedLibName); 17997 return false; 17998 } 17999 if (!ps.getInstalled(userId)) { 18000 // Can't block uninstall for an app that is not installed or enabled. 18001 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18002 return false; 18003 } 18004 ps.setBlockUninstall(blockUninstall, userId); 18005 mSettings.writePackageRestrictionsLPr(userId); 18006 } 18007 return true; 18008 } 18009 18010 @Override 18011 public boolean getBlockUninstallForUser(String packageName, int userId) { 18012 synchronized (mPackages) { 18013 PackageSetting ps = mSettings.mPackages.get(packageName); 18014 if (ps == null) { 18015 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18016 return false; 18017 } 18018 return ps.getBlockUninstall(userId); 18019 } 18020 } 18021 18022 @Override 18023 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18024 int callingUid = Binder.getCallingUid(); 18025 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18026 throw new SecurityException( 18027 "setRequiredForSystemUser can only be run by the system or root"); 18028 } 18029 synchronized (mPackages) { 18030 PackageSetting ps = mSettings.mPackages.get(packageName); 18031 if (ps == null) { 18032 Log.w(TAG, "Package doesn't exist: " + packageName); 18033 return false; 18034 } 18035 if (systemUserApp) { 18036 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18037 } else { 18038 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18039 } 18040 mSettings.writeLPr(); 18041 } 18042 return true; 18043 } 18044 18045 /* 18046 * This method handles package deletion in general 18047 */ 18048 private boolean deletePackageLIF(String packageName, UserHandle user, 18049 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18050 PackageRemovedInfo outInfo, boolean writeSettings, 18051 PackageParser.Package replacingPackage) { 18052 if (packageName == null) { 18053 Slog.w(TAG, "Attempt to delete null packageName."); 18054 return false; 18055 } 18056 18057 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18058 18059 PackageSetting ps; 18060 synchronized (mPackages) { 18061 ps = mSettings.mPackages.get(packageName); 18062 if (ps == null) { 18063 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18064 return false; 18065 } 18066 18067 if (ps.parentPackageName != null && (!isSystemApp(ps) 18068 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18069 if (DEBUG_REMOVE) { 18070 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18071 + ((user == null) ? UserHandle.USER_ALL : user)); 18072 } 18073 final int removedUserId = (user != null) ? user.getIdentifier() 18074 : UserHandle.USER_ALL; 18075 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18076 return false; 18077 } 18078 markPackageUninstalledForUserLPw(ps, user); 18079 scheduleWritePackageRestrictionsLocked(user); 18080 return true; 18081 } 18082 } 18083 18084 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18085 && user.getIdentifier() != UserHandle.USER_ALL)) { 18086 // The caller is asking that the package only be deleted for a single 18087 // user. To do this, we just mark its uninstalled state and delete 18088 // its data. If this is a system app, we only allow this to happen if 18089 // they have set the special DELETE_SYSTEM_APP which requests different 18090 // semantics than normal for uninstalling system apps. 18091 markPackageUninstalledForUserLPw(ps, user); 18092 18093 if (!isSystemApp(ps)) { 18094 // Do not uninstall the APK if an app should be cached 18095 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18096 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18097 // Other user still have this package installed, so all 18098 // we need to do is clear this user's data and save that 18099 // it is uninstalled. 18100 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18101 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18102 return false; 18103 } 18104 scheduleWritePackageRestrictionsLocked(user); 18105 return true; 18106 } else { 18107 // We need to set it back to 'installed' so the uninstall 18108 // broadcasts will be sent correctly. 18109 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18110 ps.setInstalled(true, user.getIdentifier()); 18111 mSettings.writeKernelMappingLPr(ps); 18112 } 18113 } else { 18114 // This is a system app, so we assume that the 18115 // other users still have this package installed, so all 18116 // we need to do is clear this user's data and save that 18117 // it is uninstalled. 18118 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18119 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18120 return false; 18121 } 18122 scheduleWritePackageRestrictionsLocked(user); 18123 return true; 18124 } 18125 } 18126 18127 // If we are deleting a composite package for all users, keep track 18128 // of result for each child. 18129 if (ps.childPackageNames != null && outInfo != null) { 18130 synchronized (mPackages) { 18131 final int childCount = ps.childPackageNames.size(); 18132 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18133 for (int i = 0; i < childCount; i++) { 18134 String childPackageName = ps.childPackageNames.get(i); 18135 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18136 childInfo.removedPackage = childPackageName; 18137 outInfo.removedChildPackages.put(childPackageName, childInfo); 18138 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18139 if (childPs != null) { 18140 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18141 } 18142 } 18143 } 18144 } 18145 18146 boolean ret = false; 18147 if (isSystemApp(ps)) { 18148 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18149 // When an updated system application is deleted we delete the existing resources 18150 // as well and fall back to existing code in system partition 18151 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18152 } else { 18153 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18154 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18155 outInfo, writeSettings, replacingPackage); 18156 } 18157 18158 // Take a note whether we deleted the package for all users 18159 if (outInfo != null) { 18160 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18161 if (outInfo.removedChildPackages != null) { 18162 synchronized (mPackages) { 18163 final int childCount = outInfo.removedChildPackages.size(); 18164 for (int i = 0; i < childCount; i++) { 18165 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18166 if (childInfo != null) { 18167 childInfo.removedForAllUsers = mPackages.get( 18168 childInfo.removedPackage) == null; 18169 } 18170 } 18171 } 18172 } 18173 // If we uninstalled an update to a system app there may be some 18174 // child packages that appeared as they are declared in the system 18175 // app but were not declared in the update. 18176 if (isSystemApp(ps)) { 18177 synchronized (mPackages) { 18178 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18179 final int childCount = (updatedPs.childPackageNames != null) 18180 ? updatedPs.childPackageNames.size() : 0; 18181 for (int i = 0; i < childCount; i++) { 18182 String childPackageName = updatedPs.childPackageNames.get(i); 18183 if (outInfo.removedChildPackages == null 18184 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18185 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18186 if (childPs == null) { 18187 continue; 18188 } 18189 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18190 installRes.name = childPackageName; 18191 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18192 installRes.pkg = mPackages.get(childPackageName); 18193 installRes.uid = childPs.pkg.applicationInfo.uid; 18194 if (outInfo.appearedChildPackages == null) { 18195 outInfo.appearedChildPackages = new ArrayMap<>(); 18196 } 18197 outInfo.appearedChildPackages.put(childPackageName, installRes); 18198 } 18199 } 18200 } 18201 } 18202 } 18203 18204 return ret; 18205 } 18206 18207 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18208 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18209 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18210 for (int nextUserId : userIds) { 18211 if (DEBUG_REMOVE) { 18212 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18213 } 18214 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18215 false /*installed*/, 18216 true /*stopped*/, 18217 true /*notLaunched*/, 18218 false /*hidden*/, 18219 false /*suspended*/, 18220 false /*instantApp*/, 18221 null /*lastDisableAppCaller*/, 18222 null /*enabledComponents*/, 18223 null /*disabledComponents*/, 18224 false /*blockUninstall*/, 18225 ps.readUserState(nextUserId).domainVerificationStatus, 18226 0, PackageManager.INSTALL_REASON_UNKNOWN); 18227 } 18228 mSettings.writeKernelMappingLPr(ps); 18229 } 18230 18231 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18232 PackageRemovedInfo outInfo) { 18233 final PackageParser.Package pkg; 18234 synchronized (mPackages) { 18235 pkg = mPackages.get(ps.name); 18236 } 18237 18238 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18239 : new int[] {userId}; 18240 for (int nextUserId : userIds) { 18241 if (DEBUG_REMOVE) { 18242 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18243 + nextUserId); 18244 } 18245 18246 destroyAppDataLIF(pkg, userId, 18247 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18248 destroyAppProfilesLIF(pkg, userId); 18249 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18250 schedulePackageCleaning(ps.name, nextUserId, false); 18251 synchronized (mPackages) { 18252 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18253 scheduleWritePackageRestrictionsLocked(nextUserId); 18254 } 18255 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18256 } 18257 } 18258 18259 if (outInfo != null) { 18260 outInfo.removedPackage = ps.name; 18261 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18262 outInfo.removedAppId = ps.appId; 18263 outInfo.removedUsers = userIds; 18264 } 18265 18266 return true; 18267 } 18268 18269 private final class ClearStorageConnection implements ServiceConnection { 18270 IMediaContainerService mContainerService; 18271 18272 @Override 18273 public void onServiceConnected(ComponentName name, IBinder service) { 18274 synchronized (this) { 18275 mContainerService = IMediaContainerService.Stub 18276 .asInterface(Binder.allowBlocking(service)); 18277 notifyAll(); 18278 } 18279 } 18280 18281 @Override 18282 public void onServiceDisconnected(ComponentName name) { 18283 } 18284 } 18285 18286 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18287 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18288 18289 final boolean mounted; 18290 if (Environment.isExternalStorageEmulated()) { 18291 mounted = true; 18292 } else { 18293 final String status = Environment.getExternalStorageState(); 18294 18295 mounted = status.equals(Environment.MEDIA_MOUNTED) 18296 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18297 } 18298 18299 if (!mounted) { 18300 return; 18301 } 18302 18303 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18304 int[] users; 18305 if (userId == UserHandle.USER_ALL) { 18306 users = sUserManager.getUserIds(); 18307 } else { 18308 users = new int[] { userId }; 18309 } 18310 final ClearStorageConnection conn = new ClearStorageConnection(); 18311 if (mContext.bindServiceAsUser( 18312 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18313 try { 18314 for (int curUser : users) { 18315 long timeout = SystemClock.uptimeMillis() + 5000; 18316 synchronized (conn) { 18317 long now; 18318 while (conn.mContainerService == null && 18319 (now = SystemClock.uptimeMillis()) < timeout) { 18320 try { 18321 conn.wait(timeout - now); 18322 } catch (InterruptedException e) { 18323 } 18324 } 18325 } 18326 if (conn.mContainerService == null) { 18327 return; 18328 } 18329 18330 final UserEnvironment userEnv = new UserEnvironment(curUser); 18331 clearDirectory(conn.mContainerService, 18332 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18333 if (allData) { 18334 clearDirectory(conn.mContainerService, 18335 userEnv.buildExternalStorageAppDataDirs(packageName)); 18336 clearDirectory(conn.mContainerService, 18337 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18338 } 18339 } 18340 } finally { 18341 mContext.unbindService(conn); 18342 } 18343 } 18344 } 18345 18346 @Override 18347 public void clearApplicationProfileData(String packageName) { 18348 enforceSystemOrRoot("Only the system can clear all profile data"); 18349 18350 final PackageParser.Package pkg; 18351 synchronized (mPackages) { 18352 pkg = mPackages.get(packageName); 18353 } 18354 18355 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18356 synchronized (mInstallLock) { 18357 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18358 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18359 true /* removeBaseMarker */); 18360 } 18361 } 18362 } 18363 18364 @Override 18365 public void clearApplicationUserData(final String packageName, 18366 final IPackageDataObserver observer, final int userId) { 18367 mContext.enforceCallingOrSelfPermission( 18368 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18369 18370 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18371 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18372 18373 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18374 throw new SecurityException("Cannot clear data for a protected package: " 18375 + packageName); 18376 } 18377 // Queue up an async operation since the package deletion may take a little while. 18378 mHandler.post(new Runnable() { 18379 public void run() { 18380 mHandler.removeCallbacks(this); 18381 final boolean succeeded; 18382 try (PackageFreezer freezer = freezePackage(packageName, 18383 "clearApplicationUserData")) { 18384 synchronized (mInstallLock) { 18385 succeeded = clearApplicationUserDataLIF(packageName, userId); 18386 } 18387 clearExternalStorageDataSync(packageName, userId, true); 18388 synchronized (mPackages) { 18389 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18390 packageName, userId); 18391 } 18392 } 18393 if (succeeded) { 18394 // invoke DeviceStorageMonitor's update method to clear any notifications 18395 DeviceStorageMonitorInternal dsm = LocalServices 18396 .getService(DeviceStorageMonitorInternal.class); 18397 if (dsm != null) { 18398 dsm.checkMemory(); 18399 } 18400 } 18401 if(observer != null) { 18402 try { 18403 observer.onRemoveCompleted(packageName, succeeded); 18404 } catch (RemoteException e) { 18405 Log.i(TAG, "Observer no longer exists."); 18406 } 18407 } //end if observer 18408 } //end run 18409 }); 18410 } 18411 18412 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18413 if (packageName == null) { 18414 Slog.w(TAG, "Attempt to delete null packageName."); 18415 return false; 18416 } 18417 18418 // Try finding details about the requested package 18419 PackageParser.Package pkg; 18420 synchronized (mPackages) { 18421 pkg = mPackages.get(packageName); 18422 if (pkg == null) { 18423 final PackageSetting ps = mSettings.mPackages.get(packageName); 18424 if (ps != null) { 18425 pkg = ps.pkg; 18426 } 18427 } 18428 18429 if (pkg == null) { 18430 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18431 return false; 18432 } 18433 18434 PackageSetting ps = (PackageSetting) pkg.mExtras; 18435 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18436 } 18437 18438 clearAppDataLIF(pkg, userId, 18439 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18440 18441 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18442 removeKeystoreDataIfNeeded(userId, appId); 18443 18444 UserManagerInternal umInternal = getUserManagerInternal(); 18445 final int flags; 18446 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18447 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18448 } else if (umInternal.isUserRunning(userId)) { 18449 flags = StorageManager.FLAG_STORAGE_DE; 18450 } else { 18451 flags = 0; 18452 } 18453 prepareAppDataContentsLIF(pkg, userId, flags); 18454 18455 return true; 18456 } 18457 18458 /** 18459 * Reverts user permission state changes (permissions and flags) in 18460 * all packages for a given user. 18461 * 18462 * @param userId The device user for which to do a reset. 18463 */ 18464 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18465 final int packageCount = mPackages.size(); 18466 for (int i = 0; i < packageCount; i++) { 18467 PackageParser.Package pkg = mPackages.valueAt(i); 18468 PackageSetting ps = (PackageSetting) pkg.mExtras; 18469 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18470 } 18471 } 18472 18473 private void resetNetworkPolicies(int userId) { 18474 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18475 } 18476 18477 /** 18478 * Reverts user permission state changes (permissions and flags). 18479 * 18480 * @param ps The package for which to reset. 18481 * @param userId The device user for which to do a reset. 18482 */ 18483 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18484 final PackageSetting ps, final int userId) { 18485 if (ps.pkg == null) { 18486 return; 18487 } 18488 18489 // These are flags that can change base on user actions. 18490 final int userSettableMask = FLAG_PERMISSION_USER_SET 18491 | FLAG_PERMISSION_USER_FIXED 18492 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18493 | FLAG_PERMISSION_REVIEW_REQUIRED; 18494 18495 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18496 | FLAG_PERMISSION_POLICY_FIXED; 18497 18498 boolean writeInstallPermissions = false; 18499 boolean writeRuntimePermissions = false; 18500 18501 final int permissionCount = ps.pkg.requestedPermissions.size(); 18502 for (int i = 0; i < permissionCount; i++) { 18503 String permission = ps.pkg.requestedPermissions.get(i); 18504 18505 BasePermission bp = mSettings.mPermissions.get(permission); 18506 if (bp == null) { 18507 continue; 18508 } 18509 18510 // If shared user we just reset the state to which only this app contributed. 18511 if (ps.sharedUser != null) { 18512 boolean used = false; 18513 final int packageCount = ps.sharedUser.packages.size(); 18514 for (int j = 0; j < packageCount; j++) { 18515 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18516 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18517 && pkg.pkg.requestedPermissions.contains(permission)) { 18518 used = true; 18519 break; 18520 } 18521 } 18522 if (used) { 18523 continue; 18524 } 18525 } 18526 18527 PermissionsState permissionsState = ps.getPermissionsState(); 18528 18529 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18530 18531 // Always clear the user settable flags. 18532 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18533 bp.name) != null; 18534 // If permission review is enabled and this is a legacy app, mark the 18535 // permission as requiring a review as this is the initial state. 18536 int flags = 0; 18537 if (mPermissionReviewRequired 18538 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18539 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18540 } 18541 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18542 if (hasInstallState) { 18543 writeInstallPermissions = true; 18544 } else { 18545 writeRuntimePermissions = true; 18546 } 18547 } 18548 18549 // Below is only runtime permission handling. 18550 if (!bp.isRuntime()) { 18551 continue; 18552 } 18553 18554 // Never clobber system or policy. 18555 if ((oldFlags & policyOrSystemFlags) != 0) { 18556 continue; 18557 } 18558 18559 // If this permission was granted by default, make sure it is. 18560 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18561 if (permissionsState.grantRuntimePermission(bp, userId) 18562 != PERMISSION_OPERATION_FAILURE) { 18563 writeRuntimePermissions = true; 18564 } 18565 // If permission review is enabled the permissions for a legacy apps 18566 // are represented as constantly granted runtime ones, so don't revoke. 18567 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18568 // Otherwise, reset the permission. 18569 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18570 switch (revokeResult) { 18571 case PERMISSION_OPERATION_SUCCESS: 18572 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18573 writeRuntimePermissions = true; 18574 final int appId = ps.appId; 18575 mHandler.post(new Runnable() { 18576 @Override 18577 public void run() { 18578 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18579 } 18580 }); 18581 } break; 18582 } 18583 } 18584 } 18585 18586 // Synchronously write as we are taking permissions away. 18587 if (writeRuntimePermissions) { 18588 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18589 } 18590 18591 // Synchronously write as we are taking permissions away. 18592 if (writeInstallPermissions) { 18593 mSettings.writeLPr(); 18594 } 18595 } 18596 18597 /** 18598 * Remove entries from the keystore daemon. Will only remove it if the 18599 * {@code appId} is valid. 18600 */ 18601 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18602 if (appId < 0) { 18603 return; 18604 } 18605 18606 final KeyStore keyStore = KeyStore.getInstance(); 18607 if (keyStore != null) { 18608 if (userId == UserHandle.USER_ALL) { 18609 for (final int individual : sUserManager.getUserIds()) { 18610 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18611 } 18612 } else { 18613 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18614 } 18615 } else { 18616 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18617 } 18618 } 18619 18620 @Override 18621 public void deleteApplicationCacheFiles(final String packageName, 18622 final IPackageDataObserver observer) { 18623 final int userId = UserHandle.getCallingUserId(); 18624 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18625 } 18626 18627 @Override 18628 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18629 final IPackageDataObserver observer) { 18630 mContext.enforceCallingOrSelfPermission( 18631 android.Manifest.permission.DELETE_CACHE_FILES, null); 18632 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18633 /* requireFullPermission= */ true, /* checkShell= */ false, 18634 "delete application cache files"); 18635 18636 final PackageParser.Package pkg; 18637 synchronized (mPackages) { 18638 pkg = mPackages.get(packageName); 18639 } 18640 18641 // Queue up an async operation since the package deletion may take a little while. 18642 mHandler.post(new Runnable() { 18643 public void run() { 18644 synchronized (mInstallLock) { 18645 final int flags = StorageManager.FLAG_STORAGE_DE 18646 | StorageManager.FLAG_STORAGE_CE; 18647 // We're only clearing cache files, so we don't care if the 18648 // app is unfrozen and still able to run 18649 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18650 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18651 } 18652 clearExternalStorageDataSync(packageName, userId, false); 18653 if (observer != null) { 18654 try { 18655 observer.onRemoveCompleted(packageName, true); 18656 } catch (RemoteException e) { 18657 Log.i(TAG, "Observer no longer exists."); 18658 } 18659 } 18660 } 18661 }); 18662 } 18663 18664 @Override 18665 public void getPackageSizeInfo(final String packageName, int userHandle, 18666 final IPackageStatsObserver observer) { 18667 Slog.w(TAG, "Shame on you for calling a hidden API. Shame!"); 18668 try { 18669 observer.onGetStatsCompleted(null, false); 18670 } catch (RemoteException ignored) { 18671 } 18672 } 18673 18674 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18675 final PackageSetting ps; 18676 synchronized (mPackages) { 18677 ps = mSettings.mPackages.get(packageName); 18678 if (ps == null) { 18679 Slog.w(TAG, "Failed to find settings for " + packageName); 18680 return false; 18681 } 18682 } 18683 18684 final String[] packageNames = { packageName }; 18685 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18686 final String[] codePaths = { ps.codePathString }; 18687 18688 try { 18689 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18690 ps.appId, ceDataInodes, codePaths, stats); 18691 18692 // For now, ignore code size of packages on system partition 18693 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18694 stats.codeSize = 0; 18695 } 18696 18697 // External clients expect these to be tracked separately 18698 stats.dataSize -= stats.cacheSize; 18699 18700 } catch (InstallerException e) { 18701 Slog.w(TAG, String.valueOf(e)); 18702 return false; 18703 } 18704 18705 return true; 18706 } 18707 18708 private int getUidTargetSdkVersionLockedLPr(int uid) { 18709 Object obj = mSettings.getUserIdLPr(uid); 18710 if (obj instanceof SharedUserSetting) { 18711 final SharedUserSetting sus = (SharedUserSetting) obj; 18712 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18713 final Iterator<PackageSetting> it = sus.packages.iterator(); 18714 while (it.hasNext()) { 18715 final PackageSetting ps = it.next(); 18716 if (ps.pkg != null) { 18717 int v = ps.pkg.applicationInfo.targetSdkVersion; 18718 if (v < vers) vers = v; 18719 } 18720 } 18721 return vers; 18722 } else if (obj instanceof PackageSetting) { 18723 final PackageSetting ps = (PackageSetting) obj; 18724 if (ps.pkg != null) { 18725 return ps.pkg.applicationInfo.targetSdkVersion; 18726 } 18727 } 18728 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18729 } 18730 18731 @Override 18732 public void addPreferredActivity(IntentFilter filter, int match, 18733 ComponentName[] set, ComponentName activity, int userId) { 18734 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18735 "Adding preferred"); 18736 } 18737 18738 private void addPreferredActivityInternal(IntentFilter filter, int match, 18739 ComponentName[] set, ComponentName activity, boolean always, int userId, 18740 String opname) { 18741 // writer 18742 int callingUid = Binder.getCallingUid(); 18743 enforceCrossUserPermission(callingUid, userId, 18744 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18745 if (filter.countActions() == 0) { 18746 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18747 return; 18748 } 18749 synchronized (mPackages) { 18750 if (mContext.checkCallingOrSelfPermission( 18751 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18752 != PackageManager.PERMISSION_GRANTED) { 18753 if (getUidTargetSdkVersionLockedLPr(callingUid) 18754 < Build.VERSION_CODES.FROYO) { 18755 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18756 + callingUid); 18757 return; 18758 } 18759 mContext.enforceCallingOrSelfPermission( 18760 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18761 } 18762 18763 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18764 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18765 + userId + ":"); 18766 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18767 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18768 scheduleWritePackageRestrictionsLocked(userId); 18769 postPreferredActivityChangedBroadcast(userId); 18770 } 18771 } 18772 18773 private void postPreferredActivityChangedBroadcast(int userId) { 18774 mHandler.post(() -> { 18775 final IActivityManager am = ActivityManager.getService(); 18776 if (am == null) { 18777 return; 18778 } 18779 18780 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18781 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18782 try { 18783 am.broadcastIntent(null, intent, null, null, 18784 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18785 null, false, false, userId); 18786 } catch (RemoteException e) { 18787 } 18788 }); 18789 } 18790 18791 @Override 18792 public void replacePreferredActivity(IntentFilter filter, int match, 18793 ComponentName[] set, ComponentName activity, int userId) { 18794 if (filter.countActions() != 1) { 18795 throw new IllegalArgumentException( 18796 "replacePreferredActivity expects filter to have only 1 action."); 18797 } 18798 if (filter.countDataAuthorities() != 0 18799 || filter.countDataPaths() != 0 18800 || filter.countDataSchemes() > 1 18801 || filter.countDataTypes() != 0) { 18802 throw new IllegalArgumentException( 18803 "replacePreferredActivity expects filter to have no data authorities, " + 18804 "paths, or types; and at most one scheme."); 18805 } 18806 18807 final int callingUid = Binder.getCallingUid(); 18808 enforceCrossUserPermission(callingUid, userId, 18809 true /* requireFullPermission */, false /* checkShell */, 18810 "replace preferred activity"); 18811 synchronized (mPackages) { 18812 if (mContext.checkCallingOrSelfPermission( 18813 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18814 != PackageManager.PERMISSION_GRANTED) { 18815 if (getUidTargetSdkVersionLockedLPr(callingUid) 18816 < Build.VERSION_CODES.FROYO) { 18817 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18818 + Binder.getCallingUid()); 18819 return; 18820 } 18821 mContext.enforceCallingOrSelfPermission( 18822 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18823 } 18824 18825 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18826 if (pir != null) { 18827 // Get all of the existing entries that exactly match this filter. 18828 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18829 if (existing != null && existing.size() == 1) { 18830 PreferredActivity cur = existing.get(0); 18831 if (DEBUG_PREFERRED) { 18832 Slog.i(TAG, "Checking replace of preferred:"); 18833 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18834 if (!cur.mPref.mAlways) { 18835 Slog.i(TAG, " -- CUR; not mAlways!"); 18836 } else { 18837 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18838 Slog.i(TAG, " -- CUR: mSet=" 18839 + Arrays.toString(cur.mPref.mSetComponents)); 18840 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18841 Slog.i(TAG, " -- NEW: mMatch=" 18842 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18843 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18844 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18845 } 18846 } 18847 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18848 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18849 && cur.mPref.sameSet(set)) { 18850 // Setting the preferred activity to what it happens to be already 18851 if (DEBUG_PREFERRED) { 18852 Slog.i(TAG, "Replacing with same preferred activity " 18853 + cur.mPref.mShortComponent + " for user " 18854 + userId + ":"); 18855 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18856 } 18857 return; 18858 } 18859 } 18860 18861 if (existing != null) { 18862 if (DEBUG_PREFERRED) { 18863 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18864 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18865 } 18866 for (int i = 0; i < existing.size(); i++) { 18867 PreferredActivity pa = existing.get(i); 18868 if (DEBUG_PREFERRED) { 18869 Slog.i(TAG, "Removing existing preferred activity " 18870 + pa.mPref.mComponent + ":"); 18871 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18872 } 18873 pir.removeFilter(pa); 18874 } 18875 } 18876 } 18877 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18878 "Replacing preferred"); 18879 } 18880 } 18881 18882 @Override 18883 public void clearPackagePreferredActivities(String packageName) { 18884 final int uid = Binder.getCallingUid(); 18885 // writer 18886 synchronized (mPackages) { 18887 PackageParser.Package pkg = mPackages.get(packageName); 18888 if (pkg == null || pkg.applicationInfo.uid != uid) { 18889 if (mContext.checkCallingOrSelfPermission( 18890 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18891 != PackageManager.PERMISSION_GRANTED) { 18892 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18893 < Build.VERSION_CODES.FROYO) { 18894 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18895 + Binder.getCallingUid()); 18896 return; 18897 } 18898 mContext.enforceCallingOrSelfPermission( 18899 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18900 } 18901 } 18902 18903 int user = UserHandle.getCallingUserId(); 18904 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18905 scheduleWritePackageRestrictionsLocked(user); 18906 } 18907 } 18908 } 18909 18910 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18911 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18912 ArrayList<PreferredActivity> removed = null; 18913 boolean changed = false; 18914 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18915 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18916 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18917 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18918 continue; 18919 } 18920 Iterator<PreferredActivity> it = pir.filterIterator(); 18921 while (it.hasNext()) { 18922 PreferredActivity pa = it.next(); 18923 // Mark entry for removal only if it matches the package name 18924 // and the entry is of type "always". 18925 if (packageName == null || 18926 (pa.mPref.mComponent.getPackageName().equals(packageName) 18927 && pa.mPref.mAlways)) { 18928 if (removed == null) { 18929 removed = new ArrayList<PreferredActivity>(); 18930 } 18931 removed.add(pa); 18932 } 18933 } 18934 if (removed != null) { 18935 for (int j=0; j<removed.size(); j++) { 18936 PreferredActivity pa = removed.get(j); 18937 pir.removeFilter(pa); 18938 } 18939 changed = true; 18940 } 18941 } 18942 if (changed) { 18943 postPreferredActivityChangedBroadcast(userId); 18944 } 18945 return changed; 18946 } 18947 18948 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18949 private void clearIntentFilterVerificationsLPw(int userId) { 18950 final int packageCount = mPackages.size(); 18951 for (int i = 0; i < packageCount; i++) { 18952 PackageParser.Package pkg = mPackages.valueAt(i); 18953 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18954 } 18955 } 18956 18957 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18958 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18959 if (userId == UserHandle.USER_ALL) { 18960 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18961 sUserManager.getUserIds())) { 18962 for (int oneUserId : sUserManager.getUserIds()) { 18963 scheduleWritePackageRestrictionsLocked(oneUserId); 18964 } 18965 } 18966 } else { 18967 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18968 scheduleWritePackageRestrictionsLocked(userId); 18969 } 18970 } 18971 } 18972 18973 void clearDefaultBrowserIfNeeded(String packageName) { 18974 for (int oneUserId : sUserManager.getUserIds()) { 18975 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18976 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18977 if (packageName.equals(defaultBrowserPackageName)) { 18978 setDefaultBrowserPackageName(null, oneUserId); 18979 } 18980 } 18981 } 18982 18983 @Override 18984 public void resetApplicationPreferences(int userId) { 18985 mContext.enforceCallingOrSelfPermission( 18986 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18987 final long identity = Binder.clearCallingIdentity(); 18988 // writer 18989 try { 18990 synchronized (mPackages) { 18991 clearPackagePreferredActivitiesLPw(null, userId); 18992 mSettings.applyDefaultPreferredAppsLPw(this, userId); 18993 // TODO: We have to reset the default SMS and Phone. This requires 18994 // significant refactoring to keep all default apps in the package 18995 // manager (cleaner but more work) or have the services provide 18996 // callbacks to the package manager to request a default app reset. 18997 applyFactoryDefaultBrowserLPw(userId); 18998 clearIntentFilterVerificationsLPw(userId); 18999 primeDomainVerificationsLPw(userId); 19000 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19001 scheduleWritePackageRestrictionsLocked(userId); 19002 } 19003 resetNetworkPolicies(userId); 19004 } finally { 19005 Binder.restoreCallingIdentity(identity); 19006 } 19007 } 19008 19009 @Override 19010 public int getPreferredActivities(List<IntentFilter> outFilters, 19011 List<ComponentName> outActivities, String packageName) { 19012 19013 int num = 0; 19014 final int userId = UserHandle.getCallingUserId(); 19015 // reader 19016 synchronized (mPackages) { 19017 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19018 if (pir != null) { 19019 final Iterator<PreferredActivity> it = pir.filterIterator(); 19020 while (it.hasNext()) { 19021 final PreferredActivity pa = it.next(); 19022 if (packageName == null 19023 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19024 && pa.mPref.mAlways)) { 19025 if (outFilters != null) { 19026 outFilters.add(new IntentFilter(pa)); 19027 } 19028 if (outActivities != null) { 19029 outActivities.add(pa.mPref.mComponent); 19030 } 19031 } 19032 } 19033 } 19034 } 19035 19036 return num; 19037 } 19038 19039 @Override 19040 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19041 int userId) { 19042 int callingUid = Binder.getCallingUid(); 19043 if (callingUid != Process.SYSTEM_UID) { 19044 throw new SecurityException( 19045 "addPersistentPreferredActivity can only be run by the system"); 19046 } 19047 if (filter.countActions() == 0) { 19048 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19049 return; 19050 } 19051 synchronized (mPackages) { 19052 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19053 ":"); 19054 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19055 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19056 new PersistentPreferredActivity(filter, activity)); 19057 scheduleWritePackageRestrictionsLocked(userId); 19058 postPreferredActivityChangedBroadcast(userId); 19059 } 19060 } 19061 19062 @Override 19063 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19064 int callingUid = Binder.getCallingUid(); 19065 if (callingUid != Process.SYSTEM_UID) { 19066 throw new SecurityException( 19067 "clearPackagePersistentPreferredActivities can only be run by the system"); 19068 } 19069 ArrayList<PersistentPreferredActivity> removed = null; 19070 boolean changed = false; 19071 synchronized (mPackages) { 19072 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19073 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19074 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19075 .valueAt(i); 19076 if (userId != thisUserId) { 19077 continue; 19078 } 19079 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19080 while (it.hasNext()) { 19081 PersistentPreferredActivity ppa = it.next(); 19082 // Mark entry for removal only if it matches the package name. 19083 if (ppa.mComponent.getPackageName().equals(packageName)) { 19084 if (removed == null) { 19085 removed = new ArrayList<PersistentPreferredActivity>(); 19086 } 19087 removed.add(ppa); 19088 } 19089 } 19090 if (removed != null) { 19091 for (int j=0; j<removed.size(); j++) { 19092 PersistentPreferredActivity ppa = removed.get(j); 19093 ppir.removeFilter(ppa); 19094 } 19095 changed = true; 19096 } 19097 } 19098 19099 if (changed) { 19100 scheduleWritePackageRestrictionsLocked(userId); 19101 postPreferredActivityChangedBroadcast(userId); 19102 } 19103 } 19104 } 19105 19106 /** 19107 * Common machinery for picking apart a restored XML blob and passing 19108 * it to a caller-supplied functor to be applied to the running system. 19109 */ 19110 private void restoreFromXml(XmlPullParser parser, int userId, 19111 String expectedStartTag, BlobXmlRestorer functor) 19112 throws IOException, XmlPullParserException { 19113 int type; 19114 while ((type = parser.next()) != XmlPullParser.START_TAG 19115 && type != XmlPullParser.END_DOCUMENT) { 19116 } 19117 if (type != XmlPullParser.START_TAG) { 19118 // oops didn't find a start tag?! 19119 if (DEBUG_BACKUP) { 19120 Slog.e(TAG, "Didn't find start tag during restore"); 19121 } 19122 return; 19123 } 19124Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19125 // this is supposed to be TAG_PREFERRED_BACKUP 19126 if (!expectedStartTag.equals(parser.getName())) { 19127 if (DEBUG_BACKUP) { 19128 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19129 } 19130 return; 19131 } 19132 19133 // skip interfering stuff, then we're aligned with the backing implementation 19134 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19135Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19136 functor.apply(parser, userId); 19137 } 19138 19139 private interface BlobXmlRestorer { 19140 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19141 } 19142 19143 /** 19144 * Non-Binder method, support for the backup/restore mechanism: write the 19145 * full set of preferred activities in its canonical XML format. Returns the 19146 * XML output as a byte array, or null if there is none. 19147 */ 19148 @Override 19149 public byte[] getPreferredActivityBackup(int userId) { 19150 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19151 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19152 } 19153 19154 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19155 try { 19156 final XmlSerializer serializer = new FastXmlSerializer(); 19157 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19158 serializer.startDocument(null, true); 19159 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19160 19161 synchronized (mPackages) { 19162 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19163 } 19164 19165 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19166 serializer.endDocument(); 19167 serializer.flush(); 19168 } catch (Exception e) { 19169 if (DEBUG_BACKUP) { 19170 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19171 } 19172 return null; 19173 } 19174 19175 return dataStream.toByteArray(); 19176 } 19177 19178 @Override 19179 public void restorePreferredActivities(byte[] backup, int userId) { 19180 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19181 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19182 } 19183 19184 try { 19185 final XmlPullParser parser = Xml.newPullParser(); 19186 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19187 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19188 new BlobXmlRestorer() { 19189 @Override 19190 public void apply(XmlPullParser parser, int userId) 19191 throws XmlPullParserException, IOException { 19192 synchronized (mPackages) { 19193 mSettings.readPreferredActivitiesLPw(parser, userId); 19194 } 19195 } 19196 } ); 19197 } catch (Exception e) { 19198 if (DEBUG_BACKUP) { 19199 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19200 } 19201 } 19202 } 19203 19204 /** 19205 * Non-Binder method, support for the backup/restore mechanism: write the 19206 * default browser (etc) settings in its canonical XML format. Returns the default 19207 * browser XML representation as a byte array, or null if there is none. 19208 */ 19209 @Override 19210 public byte[] getDefaultAppsBackup(int userId) { 19211 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19212 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19213 } 19214 19215 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19216 try { 19217 final XmlSerializer serializer = new FastXmlSerializer(); 19218 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19219 serializer.startDocument(null, true); 19220 serializer.startTag(null, TAG_DEFAULT_APPS); 19221 19222 synchronized (mPackages) { 19223 mSettings.writeDefaultAppsLPr(serializer, userId); 19224 } 19225 19226 serializer.endTag(null, TAG_DEFAULT_APPS); 19227 serializer.endDocument(); 19228 serializer.flush(); 19229 } catch (Exception e) { 19230 if (DEBUG_BACKUP) { 19231 Slog.e(TAG, "Unable to write default apps for backup", e); 19232 } 19233 return null; 19234 } 19235 19236 return dataStream.toByteArray(); 19237 } 19238 19239 @Override 19240 public void restoreDefaultApps(byte[] backup, int userId) { 19241 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19242 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19243 } 19244 19245 try { 19246 final XmlPullParser parser = Xml.newPullParser(); 19247 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19248 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19249 new BlobXmlRestorer() { 19250 @Override 19251 public void apply(XmlPullParser parser, int userId) 19252 throws XmlPullParserException, IOException { 19253 synchronized (mPackages) { 19254 mSettings.readDefaultAppsLPw(parser, userId); 19255 } 19256 } 19257 } ); 19258 } catch (Exception e) { 19259 if (DEBUG_BACKUP) { 19260 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19261 } 19262 } 19263 } 19264 19265 @Override 19266 public byte[] getIntentFilterVerificationBackup(int userId) { 19267 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19268 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19269 } 19270 19271 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19272 try { 19273 final XmlSerializer serializer = new FastXmlSerializer(); 19274 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19275 serializer.startDocument(null, true); 19276 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19277 19278 synchronized (mPackages) { 19279 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19280 } 19281 19282 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19283 serializer.endDocument(); 19284 serializer.flush(); 19285 } catch (Exception e) { 19286 if (DEBUG_BACKUP) { 19287 Slog.e(TAG, "Unable to write default apps for backup", e); 19288 } 19289 return null; 19290 } 19291 19292 return dataStream.toByteArray(); 19293 } 19294 19295 @Override 19296 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19297 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19298 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19299 } 19300 19301 try { 19302 final XmlPullParser parser = Xml.newPullParser(); 19303 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19304 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19305 new BlobXmlRestorer() { 19306 @Override 19307 public void apply(XmlPullParser parser, int userId) 19308 throws XmlPullParserException, IOException { 19309 synchronized (mPackages) { 19310 mSettings.readAllDomainVerificationsLPr(parser, userId); 19311 mSettings.writeLPr(); 19312 } 19313 } 19314 } ); 19315 } catch (Exception e) { 19316 if (DEBUG_BACKUP) { 19317 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19318 } 19319 } 19320 } 19321 19322 @Override 19323 public byte[] getPermissionGrantBackup(int userId) { 19324 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19325 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19326 } 19327 19328 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19329 try { 19330 final XmlSerializer serializer = new FastXmlSerializer(); 19331 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19332 serializer.startDocument(null, true); 19333 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19334 19335 synchronized (mPackages) { 19336 serializeRuntimePermissionGrantsLPr(serializer, userId); 19337 } 19338 19339 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19340 serializer.endDocument(); 19341 serializer.flush(); 19342 } catch (Exception e) { 19343 if (DEBUG_BACKUP) { 19344 Slog.e(TAG, "Unable to write default apps for backup", e); 19345 } 19346 return null; 19347 } 19348 19349 return dataStream.toByteArray(); 19350 } 19351 19352 @Override 19353 public void restorePermissionGrants(byte[] backup, int userId) { 19354 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19355 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19356 } 19357 19358 try { 19359 final XmlPullParser parser = Xml.newPullParser(); 19360 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19361 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19362 new BlobXmlRestorer() { 19363 @Override 19364 public void apply(XmlPullParser parser, int userId) 19365 throws XmlPullParserException, IOException { 19366 synchronized (mPackages) { 19367 processRestoredPermissionGrantsLPr(parser, userId); 19368 } 19369 } 19370 } ); 19371 } catch (Exception e) { 19372 if (DEBUG_BACKUP) { 19373 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19374 } 19375 } 19376 } 19377 19378 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19379 throws IOException { 19380 serializer.startTag(null, TAG_ALL_GRANTS); 19381 19382 final int N = mSettings.mPackages.size(); 19383 for (int i = 0; i < N; i++) { 19384 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19385 boolean pkgGrantsKnown = false; 19386 19387 PermissionsState packagePerms = ps.getPermissionsState(); 19388 19389 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19390 final int grantFlags = state.getFlags(); 19391 // only look at grants that are not system/policy fixed 19392 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19393 final boolean isGranted = state.isGranted(); 19394 // And only back up the user-twiddled state bits 19395 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19396 final String packageName = mSettings.mPackages.keyAt(i); 19397 if (!pkgGrantsKnown) { 19398 serializer.startTag(null, TAG_GRANT); 19399 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19400 pkgGrantsKnown = true; 19401 } 19402 19403 final boolean userSet = 19404 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19405 final boolean userFixed = 19406 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19407 final boolean revoke = 19408 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19409 19410 serializer.startTag(null, TAG_PERMISSION); 19411 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19412 if (isGranted) { 19413 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19414 } 19415 if (userSet) { 19416 serializer.attribute(null, ATTR_USER_SET, "true"); 19417 } 19418 if (userFixed) { 19419 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19420 } 19421 if (revoke) { 19422 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19423 } 19424 serializer.endTag(null, TAG_PERMISSION); 19425 } 19426 } 19427 } 19428 19429 if (pkgGrantsKnown) { 19430 serializer.endTag(null, TAG_GRANT); 19431 } 19432 } 19433 19434 serializer.endTag(null, TAG_ALL_GRANTS); 19435 } 19436 19437 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19438 throws XmlPullParserException, IOException { 19439 String pkgName = null; 19440 int outerDepth = parser.getDepth(); 19441 int type; 19442 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19443 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19444 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19445 continue; 19446 } 19447 19448 final String tagName = parser.getName(); 19449 if (tagName.equals(TAG_GRANT)) { 19450 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19451 if (DEBUG_BACKUP) { 19452 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19453 } 19454 } else if (tagName.equals(TAG_PERMISSION)) { 19455 19456 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19457 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19458 19459 int newFlagSet = 0; 19460 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19461 newFlagSet |= FLAG_PERMISSION_USER_SET; 19462 } 19463 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19464 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19465 } 19466 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19467 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19468 } 19469 if (DEBUG_BACKUP) { 19470 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19471 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19472 } 19473 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19474 if (ps != null) { 19475 // Already installed so we apply the grant immediately 19476 if (DEBUG_BACKUP) { 19477 Slog.v(TAG, " + already installed; applying"); 19478 } 19479 PermissionsState perms = ps.getPermissionsState(); 19480 BasePermission bp = mSettings.mPermissions.get(permName); 19481 if (bp != null) { 19482 if (isGranted) { 19483 perms.grantRuntimePermission(bp, userId); 19484 } 19485 if (newFlagSet != 0) { 19486 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19487 } 19488 } 19489 } else { 19490 // Need to wait for post-restore install to apply the grant 19491 if (DEBUG_BACKUP) { 19492 Slog.v(TAG, " - not yet installed; saving for later"); 19493 } 19494 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19495 isGranted, newFlagSet, userId); 19496 } 19497 } else { 19498 PackageManagerService.reportSettingsProblem(Log.WARN, 19499 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19500 XmlUtils.skipCurrentTag(parser); 19501 } 19502 } 19503 19504 scheduleWriteSettingsLocked(); 19505 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19506 } 19507 19508 @Override 19509 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19510 int sourceUserId, int targetUserId, int flags) { 19511 mContext.enforceCallingOrSelfPermission( 19512 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19513 int callingUid = Binder.getCallingUid(); 19514 enforceOwnerRights(ownerPackage, callingUid); 19515 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19516 if (intentFilter.countActions() == 0) { 19517 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19518 return; 19519 } 19520 synchronized (mPackages) { 19521 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19522 ownerPackage, targetUserId, flags); 19523 CrossProfileIntentResolver resolver = 19524 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19525 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19526 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19527 if (existing != null) { 19528 int size = existing.size(); 19529 for (int i = 0; i < size; i++) { 19530 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19531 return; 19532 } 19533 } 19534 } 19535 resolver.addFilter(newFilter); 19536 scheduleWritePackageRestrictionsLocked(sourceUserId); 19537 } 19538 } 19539 19540 @Override 19541 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19542 mContext.enforceCallingOrSelfPermission( 19543 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19544 int callingUid = Binder.getCallingUid(); 19545 enforceOwnerRights(ownerPackage, callingUid); 19546 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19547 synchronized (mPackages) { 19548 CrossProfileIntentResolver resolver = 19549 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19550 ArraySet<CrossProfileIntentFilter> set = 19551 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19552 for (CrossProfileIntentFilter filter : set) { 19553 if (filter.getOwnerPackage().equals(ownerPackage)) { 19554 resolver.removeFilter(filter); 19555 } 19556 } 19557 scheduleWritePackageRestrictionsLocked(sourceUserId); 19558 } 19559 } 19560 19561 // Enforcing that callingUid is owning pkg on userId 19562 private void enforceOwnerRights(String pkg, int callingUid) { 19563 // The system owns everything. 19564 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19565 return; 19566 } 19567 int callingUserId = UserHandle.getUserId(callingUid); 19568 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19569 if (pi == null) { 19570 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19571 + callingUserId); 19572 } 19573 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19574 throw new SecurityException("Calling uid " + callingUid 19575 + " does not own package " + pkg); 19576 } 19577 } 19578 19579 @Override 19580 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19581 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19582 } 19583 19584 private Intent getHomeIntent() { 19585 Intent intent = new Intent(Intent.ACTION_MAIN); 19586 intent.addCategory(Intent.CATEGORY_HOME); 19587 intent.addCategory(Intent.CATEGORY_DEFAULT); 19588 return intent; 19589 } 19590 19591 private IntentFilter getHomeFilter() { 19592 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19593 filter.addCategory(Intent.CATEGORY_HOME); 19594 filter.addCategory(Intent.CATEGORY_DEFAULT); 19595 return filter; 19596 } 19597 19598 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19599 int userId) { 19600 Intent intent = getHomeIntent(); 19601 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19602 PackageManager.GET_META_DATA, userId); 19603 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19604 true, false, false, userId); 19605 19606 allHomeCandidates.clear(); 19607 if (list != null) { 19608 for (ResolveInfo ri : list) { 19609 allHomeCandidates.add(ri); 19610 } 19611 } 19612 return (preferred == null || preferred.activityInfo == null) 19613 ? null 19614 : new ComponentName(preferred.activityInfo.packageName, 19615 preferred.activityInfo.name); 19616 } 19617 19618 @Override 19619 public void setHomeActivity(ComponentName comp, int userId) { 19620 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19621 getHomeActivitiesAsUser(homeActivities, userId); 19622 19623 boolean found = false; 19624 19625 final int size = homeActivities.size(); 19626 final ComponentName[] set = new ComponentName[size]; 19627 for (int i = 0; i < size; i++) { 19628 final ResolveInfo candidate = homeActivities.get(i); 19629 final ActivityInfo info = candidate.activityInfo; 19630 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19631 set[i] = activityName; 19632 if (!found && activityName.equals(comp)) { 19633 found = true; 19634 } 19635 } 19636 if (!found) { 19637 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19638 + userId); 19639 } 19640 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19641 set, comp, userId); 19642 } 19643 19644 private @Nullable String getSetupWizardPackageName() { 19645 final Intent intent = new Intent(Intent.ACTION_MAIN); 19646 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19647 19648 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19649 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19650 | MATCH_DISABLED_COMPONENTS, 19651 UserHandle.myUserId()); 19652 if (matches.size() == 1) { 19653 return matches.get(0).getComponentInfo().packageName; 19654 } else { 19655 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19656 + ": matches=" + matches); 19657 return null; 19658 } 19659 } 19660 19661 private @Nullable String getStorageManagerPackageName() { 19662 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19663 19664 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19665 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19666 | MATCH_DISABLED_COMPONENTS, 19667 UserHandle.myUserId()); 19668 if (matches.size() == 1) { 19669 return matches.get(0).getComponentInfo().packageName; 19670 } else { 19671 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19672 + matches.size() + ": matches=" + matches); 19673 return null; 19674 } 19675 } 19676 19677 @Override 19678 public void setApplicationEnabledSetting(String appPackageName, 19679 int newState, int flags, int userId, String callingPackage) { 19680 if (!sUserManager.exists(userId)) return; 19681 if (callingPackage == null) { 19682 callingPackage = Integer.toString(Binder.getCallingUid()); 19683 } 19684 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19685 } 19686 19687 @Override 19688 public void setComponentEnabledSetting(ComponentName componentName, 19689 int newState, int flags, int userId) { 19690 if (!sUserManager.exists(userId)) return; 19691 setEnabledSetting(componentName.getPackageName(), 19692 componentName.getClassName(), newState, flags, userId, null); 19693 } 19694 19695 private void setEnabledSetting(final String packageName, String className, int newState, 19696 final int flags, int userId, String callingPackage) { 19697 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19698 || newState == COMPONENT_ENABLED_STATE_ENABLED 19699 || newState == COMPONENT_ENABLED_STATE_DISABLED 19700 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19701 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19702 throw new IllegalArgumentException("Invalid new component state: " 19703 + newState); 19704 } 19705 PackageSetting pkgSetting; 19706 final int uid = Binder.getCallingUid(); 19707 final int permission; 19708 if (uid == Process.SYSTEM_UID) { 19709 permission = PackageManager.PERMISSION_GRANTED; 19710 } else { 19711 permission = mContext.checkCallingOrSelfPermission( 19712 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19713 } 19714 enforceCrossUserPermission(uid, userId, 19715 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19716 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19717 boolean sendNow = false; 19718 boolean isApp = (className == null); 19719 String componentName = isApp ? packageName : className; 19720 int packageUid = -1; 19721 ArrayList<String> components; 19722 19723 // writer 19724 synchronized (mPackages) { 19725 pkgSetting = mSettings.mPackages.get(packageName); 19726 if (pkgSetting == null) { 19727 if (className == null) { 19728 throw new IllegalArgumentException("Unknown package: " + packageName); 19729 } 19730 throw new IllegalArgumentException( 19731 "Unknown component: " + packageName + "/" + className); 19732 } 19733 } 19734 19735 // Limit who can change which apps 19736 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19737 // Don't allow apps that don't have permission to modify other apps 19738 if (!allowedByPermission) { 19739 throw new SecurityException( 19740 "Permission Denial: attempt to change component state from pid=" 19741 + Binder.getCallingPid() 19742 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19743 } 19744 // Don't allow changing protected packages. 19745 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19746 throw new SecurityException("Cannot disable a protected package: " + packageName); 19747 } 19748 } 19749 19750 synchronized (mPackages) { 19751 if (uid == Process.SHELL_UID 19752 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19753 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19754 // unless it is a test package. 19755 int oldState = pkgSetting.getEnabled(userId); 19756 if (className == null 19757 && 19758 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19759 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19760 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19761 && 19762 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19763 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19764 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19765 // ok 19766 } else { 19767 throw new SecurityException( 19768 "Shell cannot change component state for " + packageName + "/" 19769 + className + " to " + newState); 19770 } 19771 } 19772 if (className == null) { 19773 // We're dealing with an application/package level state change 19774 if (pkgSetting.getEnabled(userId) == newState) { 19775 // Nothing to do 19776 return; 19777 } 19778 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19779 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19780 // Don't care about who enables an app. 19781 callingPackage = null; 19782 } 19783 pkgSetting.setEnabled(newState, userId, callingPackage); 19784 // pkgSetting.pkg.mSetEnabled = newState; 19785 } else { 19786 // We're dealing with a component level state change 19787 // First, verify that this is a valid class name. 19788 PackageParser.Package pkg = pkgSetting.pkg; 19789 if (pkg == null || !pkg.hasComponentClassName(className)) { 19790 if (pkg != null && 19791 pkg.applicationInfo.targetSdkVersion >= 19792 Build.VERSION_CODES.JELLY_BEAN) { 19793 throw new IllegalArgumentException("Component class " + className 19794 + " does not exist in " + packageName); 19795 } else { 19796 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19797 + className + " does not exist in " + packageName); 19798 } 19799 } 19800 switch (newState) { 19801 case COMPONENT_ENABLED_STATE_ENABLED: 19802 if (!pkgSetting.enableComponentLPw(className, userId)) { 19803 return; 19804 } 19805 break; 19806 case COMPONENT_ENABLED_STATE_DISABLED: 19807 if (!pkgSetting.disableComponentLPw(className, userId)) { 19808 return; 19809 } 19810 break; 19811 case COMPONENT_ENABLED_STATE_DEFAULT: 19812 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19813 return; 19814 } 19815 break; 19816 default: 19817 Slog.e(TAG, "Invalid new component state: " + newState); 19818 return; 19819 } 19820 } 19821 scheduleWritePackageRestrictionsLocked(userId); 19822 updateSequenceNumberLP(packageName, new int[] { userId }); 19823 components = mPendingBroadcasts.get(userId, packageName); 19824 final boolean newPackage = components == null; 19825 if (newPackage) { 19826 components = new ArrayList<String>(); 19827 } 19828 if (!components.contains(componentName)) { 19829 components.add(componentName); 19830 } 19831 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19832 sendNow = true; 19833 // Purge entry from pending broadcast list if another one exists already 19834 // since we are sending one right away. 19835 mPendingBroadcasts.remove(userId, packageName); 19836 } else { 19837 if (newPackage) { 19838 mPendingBroadcasts.put(userId, packageName, components); 19839 } 19840 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19841 // Schedule a message 19842 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19843 } 19844 } 19845 } 19846 19847 long callingId = Binder.clearCallingIdentity(); 19848 try { 19849 if (sendNow) { 19850 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19851 sendPackageChangedBroadcast(packageName, 19852 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19853 } 19854 } finally { 19855 Binder.restoreCallingIdentity(callingId); 19856 } 19857 } 19858 19859 @Override 19860 public void flushPackageRestrictionsAsUser(int userId) { 19861 if (!sUserManager.exists(userId)) { 19862 return; 19863 } 19864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19865 false /* checkShell */, "flushPackageRestrictions"); 19866 synchronized (mPackages) { 19867 mSettings.writePackageRestrictionsLPr(userId); 19868 mDirtyUsers.remove(userId); 19869 if (mDirtyUsers.isEmpty()) { 19870 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19871 } 19872 } 19873 } 19874 19875 private void sendPackageChangedBroadcast(String packageName, 19876 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19877 if (DEBUG_INSTALL) 19878 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19879 + componentNames); 19880 Bundle extras = new Bundle(4); 19881 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19882 String nameList[] = new String[componentNames.size()]; 19883 componentNames.toArray(nameList); 19884 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19885 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19886 extras.putInt(Intent.EXTRA_UID, packageUid); 19887 // If this is not reporting a change of the overall package, then only send it 19888 // to registered receivers. We don't want to launch a swath of apps for every 19889 // little component state change. 19890 final int flags = !componentNames.contains(packageName) 19891 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19892 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19893 new int[] {UserHandle.getUserId(packageUid)}); 19894 } 19895 19896 @Override 19897 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19898 if (!sUserManager.exists(userId)) return; 19899 final int uid = Binder.getCallingUid(); 19900 final int permission = mContext.checkCallingOrSelfPermission( 19901 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19902 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19903 enforceCrossUserPermission(uid, userId, 19904 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19905 // writer 19906 synchronized (mPackages) { 19907 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19908 allowedByPermission, uid, userId)) { 19909 scheduleWritePackageRestrictionsLocked(userId); 19910 } 19911 } 19912 } 19913 19914 @Override 19915 public String getInstallerPackageName(String packageName) { 19916 // reader 19917 synchronized (mPackages) { 19918 return mSettings.getInstallerPackageNameLPr(packageName); 19919 } 19920 } 19921 19922 public boolean isOrphaned(String packageName) { 19923 // reader 19924 synchronized (mPackages) { 19925 return mSettings.isOrphaned(packageName); 19926 } 19927 } 19928 19929 @Override 19930 public int getApplicationEnabledSetting(String packageName, int userId) { 19931 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19932 int uid = Binder.getCallingUid(); 19933 enforceCrossUserPermission(uid, userId, 19934 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19935 // reader 19936 synchronized (mPackages) { 19937 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19938 } 19939 } 19940 19941 @Override 19942 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 19943 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19944 int uid = Binder.getCallingUid(); 19945 enforceCrossUserPermission(uid, userId, 19946 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 19947 // reader 19948 synchronized (mPackages) { 19949 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 19950 } 19951 } 19952 19953 @Override 19954 public void enterSafeMode() { 19955 enforceSystemOrRoot("Only the system can request entering safe mode"); 19956 19957 if (!mSystemReady) { 19958 mSafeMode = true; 19959 } 19960 } 19961 19962 @Override 19963 public void systemReady() { 19964 mSystemReady = true; 19965 19966 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 19967 // disabled after already being started. 19968 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 19969 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 19970 19971 // Read the compatibilty setting when the system is ready. 19972 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 19973 mContext.getContentResolver(), 19974 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 19975 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 19976 if (DEBUG_SETTINGS) { 19977 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 19978 } 19979 19980 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 19981 19982 synchronized (mPackages) { 19983 // Verify that all of the preferred activity components actually 19984 // exist. It is possible for applications to be updated and at 19985 // that point remove a previously declared activity component that 19986 // had been set as a preferred activity. We try to clean this up 19987 // the next time we encounter that preferred activity, but it is 19988 // possible for the user flow to never be able to return to that 19989 // situation so here we do a sanity check to make sure we haven't 19990 // left any junk around. 19991 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 19992 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19993 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19994 removed.clear(); 19995 for (PreferredActivity pa : pir.filterSet()) { 19996 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 19997 removed.add(pa); 19998 } 19999 } 20000 if (removed.size() > 0) { 20001 for (int r=0; r<removed.size(); r++) { 20002 PreferredActivity pa = removed.get(r); 20003 Slog.w(TAG, "Removing dangling preferred activity: " 20004 + pa.mPref.mComponent); 20005 pir.removeFilter(pa); 20006 } 20007 mSettings.writePackageRestrictionsLPr( 20008 mSettings.mPreferredActivities.keyAt(i)); 20009 } 20010 } 20011 20012 for (int userId : UserManagerService.getInstance().getUserIds()) { 20013 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20014 grantPermissionsUserIds = ArrayUtils.appendInt( 20015 grantPermissionsUserIds, userId); 20016 } 20017 } 20018 } 20019 sUserManager.systemReady(); 20020 20021 // If we upgraded grant all default permissions before kicking off. 20022 for (int userId : grantPermissionsUserIds) { 20023 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20024 } 20025 20026 // If we did not grant default permissions, we preload from this the 20027 // default permission exceptions lazily to ensure we don't hit the 20028 // disk on a new user creation. 20029 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20030 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20031 } 20032 20033 // Kick off any messages waiting for system ready 20034 if (mPostSystemReadyMessages != null) { 20035 for (Message msg : mPostSystemReadyMessages) { 20036 msg.sendToTarget(); 20037 } 20038 mPostSystemReadyMessages = null; 20039 } 20040 20041 // Watch for external volumes that come and go over time 20042 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20043 storage.registerListener(mStorageListener); 20044 20045 mInstallerService.systemReady(); 20046 mPackageDexOptimizer.systemReady(); 20047 20048 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20049 StorageManagerInternal.class); 20050 StorageManagerInternal.addExternalStoragePolicy( 20051 new StorageManagerInternal.ExternalStorageMountPolicy() { 20052 @Override 20053 public int getMountMode(int uid, String packageName) { 20054 if (Process.isIsolated(uid)) { 20055 return Zygote.MOUNT_EXTERNAL_NONE; 20056 } 20057 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20058 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20059 } 20060 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20061 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20062 } 20063 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20064 return Zygote.MOUNT_EXTERNAL_READ; 20065 } 20066 return Zygote.MOUNT_EXTERNAL_WRITE; 20067 } 20068 20069 @Override 20070 public boolean hasExternalStorage(int uid, String packageName) { 20071 return true; 20072 } 20073 }); 20074 20075 // Now that we're mostly running, clean up stale users and apps 20076 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20077 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20078 20079 if (mPrivappPermissionsViolations != null) { 20080 Slog.wtf(TAG,"Signature|privileged permissions not in " 20081 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20082 mPrivappPermissionsViolations = null; 20083 } 20084 } 20085 20086 public void waitForAppDataPrepared() { 20087 if (mPrepareAppDataFuture == null) { 20088 return; 20089 } 20090 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20091 mPrepareAppDataFuture = null; 20092 } 20093 20094 @Override 20095 public boolean isSafeMode() { 20096 return mSafeMode; 20097 } 20098 20099 @Override 20100 public boolean hasSystemUidErrors() { 20101 return mHasSystemUidErrors; 20102 } 20103 20104 static String arrayToString(int[] array) { 20105 StringBuffer buf = new StringBuffer(128); 20106 buf.append('['); 20107 if (array != null) { 20108 for (int i=0; i<array.length; i++) { 20109 if (i > 0) buf.append(", "); 20110 buf.append(array[i]); 20111 } 20112 } 20113 buf.append(']'); 20114 return buf.toString(); 20115 } 20116 20117 static class DumpState { 20118 public static final int DUMP_LIBS = 1 << 0; 20119 public static final int DUMP_FEATURES = 1 << 1; 20120 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20121 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20122 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20123 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20124 public static final int DUMP_PERMISSIONS = 1 << 6; 20125 public static final int DUMP_PACKAGES = 1 << 7; 20126 public static final int DUMP_SHARED_USERS = 1 << 8; 20127 public static final int DUMP_MESSAGES = 1 << 9; 20128 public static final int DUMP_PROVIDERS = 1 << 10; 20129 public static final int DUMP_VERIFIERS = 1 << 11; 20130 public static final int DUMP_PREFERRED = 1 << 12; 20131 public static final int DUMP_PREFERRED_XML = 1 << 13; 20132 public static final int DUMP_KEYSETS = 1 << 14; 20133 public static final int DUMP_VERSION = 1 << 15; 20134 public static final int DUMP_INSTALLS = 1 << 16; 20135 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20136 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20137 public static final int DUMP_FROZEN = 1 << 19; 20138 public static final int DUMP_DEXOPT = 1 << 20; 20139 public static final int DUMP_COMPILER_STATS = 1 << 21; 20140 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20141 20142 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20143 20144 private int mTypes; 20145 20146 private int mOptions; 20147 20148 private boolean mTitlePrinted; 20149 20150 private SharedUserSetting mSharedUser; 20151 20152 public boolean isDumping(int type) { 20153 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20154 return true; 20155 } 20156 20157 return (mTypes & type) != 0; 20158 } 20159 20160 public void setDump(int type) { 20161 mTypes |= type; 20162 } 20163 20164 public boolean isOptionEnabled(int option) { 20165 return (mOptions & option) != 0; 20166 } 20167 20168 public void setOptionEnabled(int option) { 20169 mOptions |= option; 20170 } 20171 20172 public boolean onTitlePrinted() { 20173 final boolean printed = mTitlePrinted; 20174 mTitlePrinted = true; 20175 return printed; 20176 } 20177 20178 public boolean getTitlePrinted() { 20179 return mTitlePrinted; 20180 } 20181 20182 public void setTitlePrinted(boolean enabled) { 20183 mTitlePrinted = enabled; 20184 } 20185 20186 public SharedUserSetting getSharedUser() { 20187 return mSharedUser; 20188 } 20189 20190 public void setSharedUser(SharedUserSetting user) { 20191 mSharedUser = user; 20192 } 20193 } 20194 20195 @Override 20196 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20197 FileDescriptor err, String[] args, ShellCallback callback, 20198 ResultReceiver resultReceiver) { 20199 (new PackageManagerShellCommand(this)).exec( 20200 this, in, out, err, args, callback, resultReceiver); 20201 } 20202 20203 @Override 20204 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20205 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20206 != PackageManager.PERMISSION_GRANTED) { 20207 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20208 + Binder.getCallingPid() 20209 + ", uid=" + Binder.getCallingUid() 20210 + " without permission " 20211 + android.Manifest.permission.DUMP); 20212 return; 20213 } 20214 20215 DumpState dumpState = new DumpState(); 20216 boolean fullPreferred = false; 20217 boolean checkin = false; 20218 20219 String packageName = null; 20220 ArraySet<String> permissionNames = null; 20221 20222 int opti = 0; 20223 while (opti < args.length) { 20224 String opt = args[opti]; 20225 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20226 break; 20227 } 20228 opti++; 20229 20230 if ("-a".equals(opt)) { 20231 // Right now we only know how to print all. 20232 } else if ("-h".equals(opt)) { 20233 pw.println("Package manager dump options:"); 20234 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20235 pw.println(" --checkin: dump for a checkin"); 20236 pw.println(" -f: print details of intent filters"); 20237 pw.println(" -h: print this help"); 20238 pw.println(" cmd may be one of:"); 20239 pw.println(" l[ibraries]: list known shared libraries"); 20240 pw.println(" f[eatures]: list device features"); 20241 pw.println(" k[eysets]: print known keysets"); 20242 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20243 pw.println(" perm[issions]: dump permissions"); 20244 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20245 pw.println(" pref[erred]: print preferred package settings"); 20246 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20247 pw.println(" prov[iders]: dump content providers"); 20248 pw.println(" p[ackages]: dump installed packages"); 20249 pw.println(" s[hared-users]: dump shared user IDs"); 20250 pw.println(" m[essages]: print collected runtime messages"); 20251 pw.println(" v[erifiers]: print package verifier info"); 20252 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20253 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20254 pw.println(" version: print database version info"); 20255 pw.println(" write: write current settings now"); 20256 pw.println(" installs: details about install sessions"); 20257 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20258 pw.println(" dexopt: dump dexopt state"); 20259 pw.println(" compiler-stats: dump compiler statistics"); 20260 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20261 pw.println(" <package.name>: info about given package"); 20262 return; 20263 } else if ("--checkin".equals(opt)) { 20264 checkin = true; 20265 } else if ("-f".equals(opt)) { 20266 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20267 } else { 20268 pw.println("Unknown argument: " + opt + "; use -h for help"); 20269 } 20270 } 20271 20272 // Is the caller requesting to dump a particular piece of data? 20273 if (opti < args.length) { 20274 String cmd = args[opti]; 20275 opti++; 20276 // Is this a package name? 20277 if ("android".equals(cmd) || cmd.contains(".")) { 20278 packageName = cmd; 20279 // When dumping a single package, we always dump all of its 20280 // filter information since the amount of data will be reasonable. 20281 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20282 } else if ("check-permission".equals(cmd)) { 20283 if (opti >= args.length) { 20284 pw.println("Error: check-permission missing permission argument"); 20285 return; 20286 } 20287 String perm = args[opti]; 20288 opti++; 20289 if (opti >= args.length) { 20290 pw.println("Error: check-permission missing package argument"); 20291 return; 20292 } 20293 20294 String pkg = args[opti]; 20295 opti++; 20296 int user = UserHandle.getUserId(Binder.getCallingUid()); 20297 if (opti < args.length) { 20298 try { 20299 user = Integer.parseInt(args[opti]); 20300 } catch (NumberFormatException e) { 20301 pw.println("Error: check-permission user argument is not a number: " 20302 + args[opti]); 20303 return; 20304 } 20305 } 20306 20307 // Normalize package name to handle renamed packages and static libs 20308 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20309 20310 pw.println(checkPermission(perm, pkg, user)); 20311 return; 20312 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20313 dumpState.setDump(DumpState.DUMP_LIBS); 20314 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20315 dumpState.setDump(DumpState.DUMP_FEATURES); 20316 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20317 if (opti >= args.length) { 20318 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20319 | DumpState.DUMP_SERVICE_RESOLVERS 20320 | DumpState.DUMP_RECEIVER_RESOLVERS 20321 | DumpState.DUMP_CONTENT_RESOLVERS); 20322 } else { 20323 while (opti < args.length) { 20324 String name = args[opti]; 20325 if ("a".equals(name) || "activity".equals(name)) { 20326 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20327 } else if ("s".equals(name) || "service".equals(name)) { 20328 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20329 } else if ("r".equals(name) || "receiver".equals(name)) { 20330 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20331 } else if ("c".equals(name) || "content".equals(name)) { 20332 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20333 } else { 20334 pw.println("Error: unknown resolver table type: " + name); 20335 return; 20336 } 20337 opti++; 20338 } 20339 } 20340 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20341 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20342 } else if ("permission".equals(cmd)) { 20343 if (opti >= args.length) { 20344 pw.println("Error: permission requires permission name"); 20345 return; 20346 } 20347 permissionNames = new ArraySet<>(); 20348 while (opti < args.length) { 20349 permissionNames.add(args[opti]); 20350 opti++; 20351 } 20352 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20353 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20354 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20355 dumpState.setDump(DumpState.DUMP_PREFERRED); 20356 } else if ("preferred-xml".equals(cmd)) { 20357 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20358 if (opti < args.length && "--full".equals(args[opti])) { 20359 fullPreferred = true; 20360 opti++; 20361 } 20362 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20363 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20364 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20365 dumpState.setDump(DumpState.DUMP_PACKAGES); 20366 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20367 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20368 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20369 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20370 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20371 dumpState.setDump(DumpState.DUMP_MESSAGES); 20372 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20373 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20374 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20375 || "intent-filter-verifiers".equals(cmd)) { 20376 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20377 } else if ("version".equals(cmd)) { 20378 dumpState.setDump(DumpState.DUMP_VERSION); 20379 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20380 dumpState.setDump(DumpState.DUMP_KEYSETS); 20381 } else if ("installs".equals(cmd)) { 20382 dumpState.setDump(DumpState.DUMP_INSTALLS); 20383 } else if ("frozen".equals(cmd)) { 20384 dumpState.setDump(DumpState.DUMP_FROZEN); 20385 } else if ("dexopt".equals(cmd)) { 20386 dumpState.setDump(DumpState.DUMP_DEXOPT); 20387 } else if ("compiler-stats".equals(cmd)) { 20388 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20389 } else if ("enabled-overlays".equals(cmd)) { 20390 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20391 } else if ("write".equals(cmd)) { 20392 synchronized (mPackages) { 20393 mSettings.writeLPr(); 20394 pw.println("Settings written."); 20395 return; 20396 } 20397 } 20398 } 20399 20400 if (checkin) { 20401 pw.println("vers,1"); 20402 } 20403 20404 // reader 20405 synchronized (mPackages) { 20406 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20407 if (!checkin) { 20408 if (dumpState.onTitlePrinted()) 20409 pw.println(); 20410 pw.println("Database versions:"); 20411 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20412 } 20413 } 20414 20415 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20416 if (!checkin) { 20417 if (dumpState.onTitlePrinted()) 20418 pw.println(); 20419 pw.println("Verifiers:"); 20420 pw.print(" Required: "); 20421 pw.print(mRequiredVerifierPackage); 20422 pw.print(" (uid="); 20423 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20424 UserHandle.USER_SYSTEM)); 20425 pw.println(")"); 20426 } else if (mRequiredVerifierPackage != null) { 20427 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20428 pw.print(","); 20429 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20430 UserHandle.USER_SYSTEM)); 20431 } 20432 } 20433 20434 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20435 packageName == null) { 20436 if (mIntentFilterVerifierComponent != null) { 20437 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20438 if (!checkin) { 20439 if (dumpState.onTitlePrinted()) 20440 pw.println(); 20441 pw.println("Intent Filter Verifier:"); 20442 pw.print(" Using: "); 20443 pw.print(verifierPackageName); 20444 pw.print(" (uid="); 20445 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20446 UserHandle.USER_SYSTEM)); 20447 pw.println(")"); 20448 } else if (verifierPackageName != null) { 20449 pw.print("ifv,"); pw.print(verifierPackageName); 20450 pw.print(","); 20451 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20452 UserHandle.USER_SYSTEM)); 20453 } 20454 } else { 20455 pw.println(); 20456 pw.println("No Intent Filter Verifier available!"); 20457 } 20458 } 20459 20460 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20461 boolean printedHeader = false; 20462 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20463 while (it.hasNext()) { 20464 String libName = it.next(); 20465 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20466 if (versionedLib == null) { 20467 continue; 20468 } 20469 final int versionCount = versionedLib.size(); 20470 for (int i = 0; i < versionCount; i++) { 20471 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20472 if (!checkin) { 20473 if (!printedHeader) { 20474 if (dumpState.onTitlePrinted()) 20475 pw.println(); 20476 pw.println("Libraries:"); 20477 printedHeader = true; 20478 } 20479 pw.print(" "); 20480 } else { 20481 pw.print("lib,"); 20482 } 20483 pw.print(libEntry.info.getName()); 20484 if (libEntry.info.isStatic()) { 20485 pw.print(" version=" + libEntry.info.getVersion()); 20486 } 20487 if (!checkin) { 20488 pw.print(" -> "); 20489 } 20490 if (libEntry.path != null) { 20491 pw.print(" (jar) "); 20492 pw.print(libEntry.path); 20493 } else { 20494 pw.print(" (apk) "); 20495 pw.print(libEntry.apk); 20496 } 20497 pw.println(); 20498 } 20499 } 20500 } 20501 20502 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20503 if (dumpState.onTitlePrinted()) 20504 pw.println(); 20505 if (!checkin) { 20506 pw.println("Features:"); 20507 } 20508 20509 synchronized (mAvailableFeatures) { 20510 for (FeatureInfo feat : mAvailableFeatures.values()) { 20511 if (checkin) { 20512 pw.print("feat,"); 20513 pw.print(feat.name); 20514 pw.print(","); 20515 pw.println(feat.version); 20516 } else { 20517 pw.print(" "); 20518 pw.print(feat.name); 20519 if (feat.version > 0) { 20520 pw.print(" version="); 20521 pw.print(feat.version); 20522 } 20523 pw.println(); 20524 } 20525 } 20526 } 20527 } 20528 20529 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20530 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20531 : "Activity Resolver Table:", " ", packageName, 20532 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20533 dumpState.setTitlePrinted(true); 20534 } 20535 } 20536 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20537 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20538 : "Receiver Resolver Table:", " ", packageName, 20539 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20540 dumpState.setTitlePrinted(true); 20541 } 20542 } 20543 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20544 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20545 : "Service Resolver Table:", " ", packageName, 20546 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20547 dumpState.setTitlePrinted(true); 20548 } 20549 } 20550 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20551 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20552 : "Provider Resolver Table:", " ", packageName, 20553 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20554 dumpState.setTitlePrinted(true); 20555 } 20556 } 20557 20558 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20559 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20560 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20561 int user = mSettings.mPreferredActivities.keyAt(i); 20562 if (pir.dump(pw, 20563 dumpState.getTitlePrinted() 20564 ? "\nPreferred Activities User " + user + ":" 20565 : "Preferred Activities User " + user + ":", " ", 20566 packageName, true, false)) { 20567 dumpState.setTitlePrinted(true); 20568 } 20569 } 20570 } 20571 20572 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20573 pw.flush(); 20574 FileOutputStream fout = new FileOutputStream(fd); 20575 BufferedOutputStream str = new BufferedOutputStream(fout); 20576 XmlSerializer serializer = new FastXmlSerializer(); 20577 try { 20578 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20579 serializer.startDocument(null, true); 20580 serializer.setFeature( 20581 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20582 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20583 serializer.endDocument(); 20584 serializer.flush(); 20585 } catch (IllegalArgumentException e) { 20586 pw.println("Failed writing: " + e); 20587 } catch (IllegalStateException e) { 20588 pw.println("Failed writing: " + e); 20589 } catch (IOException e) { 20590 pw.println("Failed writing: " + e); 20591 } 20592 } 20593 20594 if (!checkin 20595 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20596 && packageName == null) { 20597 pw.println(); 20598 int count = mSettings.mPackages.size(); 20599 if (count == 0) { 20600 pw.println("No applications!"); 20601 pw.println(); 20602 } else { 20603 final String prefix = " "; 20604 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20605 if (allPackageSettings.size() == 0) { 20606 pw.println("No domain preferred apps!"); 20607 pw.println(); 20608 } else { 20609 pw.println("App verification status:"); 20610 pw.println(); 20611 count = 0; 20612 for (PackageSetting ps : allPackageSettings) { 20613 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20614 if (ivi == null || ivi.getPackageName() == null) continue; 20615 pw.println(prefix + "Package: " + ivi.getPackageName()); 20616 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20617 pw.println(prefix + "Status: " + ivi.getStatusString()); 20618 pw.println(); 20619 count++; 20620 } 20621 if (count == 0) { 20622 pw.println(prefix + "No app verification established."); 20623 pw.println(); 20624 } 20625 for (int userId : sUserManager.getUserIds()) { 20626 pw.println("App linkages for user " + userId + ":"); 20627 pw.println(); 20628 count = 0; 20629 for (PackageSetting ps : allPackageSettings) { 20630 final long status = ps.getDomainVerificationStatusForUser(userId); 20631 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20632 && !DEBUG_DOMAIN_VERIFICATION) { 20633 continue; 20634 } 20635 pw.println(prefix + "Package: " + ps.name); 20636 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20637 String statusStr = IntentFilterVerificationInfo. 20638 getStatusStringFromValue(status); 20639 pw.println(prefix + "Status: " + statusStr); 20640 pw.println(); 20641 count++; 20642 } 20643 if (count == 0) { 20644 pw.println(prefix + "No configured app linkages."); 20645 pw.println(); 20646 } 20647 } 20648 } 20649 } 20650 } 20651 20652 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20653 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20654 if (packageName == null && permissionNames == null) { 20655 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20656 if (iperm == 0) { 20657 if (dumpState.onTitlePrinted()) 20658 pw.println(); 20659 pw.println("AppOp Permissions:"); 20660 } 20661 pw.print(" AppOp Permission "); 20662 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20663 pw.println(":"); 20664 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20665 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20666 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20667 } 20668 } 20669 } 20670 } 20671 20672 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20673 boolean printedSomething = false; 20674 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20675 if (packageName != null && !packageName.equals(p.info.packageName)) { 20676 continue; 20677 } 20678 if (!printedSomething) { 20679 if (dumpState.onTitlePrinted()) 20680 pw.println(); 20681 pw.println("Registered ContentProviders:"); 20682 printedSomething = true; 20683 } 20684 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20685 pw.print(" "); pw.println(p.toString()); 20686 } 20687 printedSomething = false; 20688 for (Map.Entry<String, PackageParser.Provider> entry : 20689 mProvidersByAuthority.entrySet()) { 20690 PackageParser.Provider p = entry.getValue(); 20691 if (packageName != null && !packageName.equals(p.info.packageName)) { 20692 continue; 20693 } 20694 if (!printedSomething) { 20695 if (dumpState.onTitlePrinted()) 20696 pw.println(); 20697 pw.println("ContentProvider Authorities:"); 20698 printedSomething = true; 20699 } 20700 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20701 pw.print(" "); pw.println(p.toString()); 20702 if (p.info != null && p.info.applicationInfo != null) { 20703 final String appInfo = p.info.applicationInfo.toString(); 20704 pw.print(" applicationInfo="); pw.println(appInfo); 20705 } 20706 } 20707 } 20708 20709 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20710 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20711 } 20712 20713 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20714 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20715 } 20716 20717 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20718 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20719 } 20720 20721 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20722 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20723 } 20724 20725 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20726 // XXX should handle packageName != null by dumping only install data that 20727 // the given package is involved with. 20728 if (dumpState.onTitlePrinted()) pw.println(); 20729 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20730 } 20731 20732 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20733 // XXX should handle packageName != null by dumping only install data that 20734 // the given package is involved with. 20735 if (dumpState.onTitlePrinted()) pw.println(); 20736 20737 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20738 ipw.println(); 20739 ipw.println("Frozen packages:"); 20740 ipw.increaseIndent(); 20741 if (mFrozenPackages.size() == 0) { 20742 ipw.println("(none)"); 20743 } else { 20744 for (int i = 0; i < mFrozenPackages.size(); i++) { 20745 ipw.println(mFrozenPackages.valueAt(i)); 20746 } 20747 } 20748 ipw.decreaseIndent(); 20749 } 20750 20751 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20752 if (dumpState.onTitlePrinted()) pw.println(); 20753 dumpDexoptStateLPr(pw, packageName); 20754 } 20755 20756 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20757 if (dumpState.onTitlePrinted()) pw.println(); 20758 dumpCompilerStatsLPr(pw, packageName); 20759 } 20760 20761 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20762 if (dumpState.onTitlePrinted()) pw.println(); 20763 dumpEnabledOverlaysLPr(pw); 20764 } 20765 20766 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20767 if (dumpState.onTitlePrinted()) pw.println(); 20768 mSettings.dumpReadMessagesLPr(pw, dumpState); 20769 20770 pw.println(); 20771 pw.println("Package warning messages:"); 20772 BufferedReader in = null; 20773 String line = null; 20774 try { 20775 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20776 while ((line = in.readLine()) != null) { 20777 if (line.contains("ignored: updated version")) continue; 20778 pw.println(line); 20779 } 20780 } catch (IOException ignored) { 20781 } finally { 20782 IoUtils.closeQuietly(in); 20783 } 20784 } 20785 20786 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20787 BufferedReader in = null; 20788 String line = null; 20789 try { 20790 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20791 while ((line = in.readLine()) != null) { 20792 if (line.contains("ignored: updated version")) continue; 20793 pw.print("msg,"); 20794 pw.println(line); 20795 } 20796 } catch (IOException ignored) { 20797 } finally { 20798 IoUtils.closeQuietly(in); 20799 } 20800 } 20801 } 20802 } 20803 20804 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20805 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20806 ipw.println(); 20807 ipw.println("Dexopt state:"); 20808 ipw.increaseIndent(); 20809 Collection<PackageParser.Package> packages = null; 20810 if (packageName != null) { 20811 PackageParser.Package targetPackage = mPackages.get(packageName); 20812 if (targetPackage != null) { 20813 packages = Collections.singletonList(targetPackage); 20814 } else { 20815 ipw.println("Unable to find package: " + packageName); 20816 return; 20817 } 20818 } else { 20819 packages = mPackages.values(); 20820 } 20821 20822 for (PackageParser.Package pkg : packages) { 20823 ipw.println("[" + pkg.packageName + "]"); 20824 ipw.increaseIndent(); 20825 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20826 ipw.decreaseIndent(); 20827 } 20828 } 20829 20830 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20831 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20832 ipw.println(); 20833 ipw.println("Compiler stats:"); 20834 ipw.increaseIndent(); 20835 Collection<PackageParser.Package> packages = null; 20836 if (packageName != null) { 20837 PackageParser.Package targetPackage = mPackages.get(packageName); 20838 if (targetPackage != null) { 20839 packages = Collections.singletonList(targetPackage); 20840 } else { 20841 ipw.println("Unable to find package: " + packageName); 20842 return; 20843 } 20844 } else { 20845 packages = mPackages.values(); 20846 } 20847 20848 for (PackageParser.Package pkg : packages) { 20849 ipw.println("[" + pkg.packageName + "]"); 20850 ipw.increaseIndent(); 20851 20852 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20853 if (stats == null) { 20854 ipw.println("(No recorded stats)"); 20855 } else { 20856 stats.dump(ipw); 20857 } 20858 ipw.decreaseIndent(); 20859 } 20860 } 20861 20862 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 20863 pw.println("Enabled overlay paths:"); 20864 final int N = mEnabledOverlayPaths.size(); 20865 for (int i = 0; i < N; i++) { 20866 final int userId = mEnabledOverlayPaths.keyAt(i); 20867 pw.println(String.format(" User %d:", userId)); 20868 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 20869 mEnabledOverlayPaths.valueAt(i); 20870 final int M = userSpecificOverlays.size(); 20871 for (int j = 0; j < M; j++) { 20872 final String targetPackageName = userSpecificOverlays.keyAt(j); 20873 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 20874 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 20875 } 20876 } 20877 } 20878 20879 private String dumpDomainString(String packageName) { 20880 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20881 .getList(); 20882 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20883 20884 ArraySet<String> result = new ArraySet<>(); 20885 if (iviList.size() > 0) { 20886 for (IntentFilterVerificationInfo ivi : iviList) { 20887 for (String host : ivi.getDomains()) { 20888 result.add(host); 20889 } 20890 } 20891 } 20892 if (filters != null && filters.size() > 0) { 20893 for (IntentFilter filter : filters) { 20894 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20895 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20896 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20897 result.addAll(filter.getHostsList()); 20898 } 20899 } 20900 } 20901 20902 StringBuilder sb = new StringBuilder(result.size() * 16); 20903 for (String domain : result) { 20904 if (sb.length() > 0) sb.append(" "); 20905 sb.append(domain); 20906 } 20907 return sb.toString(); 20908 } 20909 20910 // ------- apps on sdcard specific code ------- 20911 static final boolean DEBUG_SD_INSTALL = false; 20912 20913 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20914 20915 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20916 20917 private boolean mMediaMounted = false; 20918 20919 static String getEncryptKey() { 20920 try { 20921 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20922 SD_ENCRYPTION_KEYSTORE_NAME); 20923 if (sdEncKey == null) { 20924 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20925 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20926 if (sdEncKey == null) { 20927 Slog.e(TAG, "Failed to create encryption keys"); 20928 return null; 20929 } 20930 } 20931 return sdEncKey; 20932 } catch (NoSuchAlgorithmException nsae) { 20933 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20934 return null; 20935 } catch (IOException ioe) { 20936 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 20937 return null; 20938 } 20939 } 20940 20941 /* 20942 * Update media status on PackageManager. 20943 */ 20944 @Override 20945 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 20946 int callingUid = Binder.getCallingUid(); 20947 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 20948 throw new SecurityException("Media status can only be updated by the system"); 20949 } 20950 // reader; this apparently protects mMediaMounted, but should probably 20951 // be a different lock in that case. 20952 synchronized (mPackages) { 20953 Log.i(TAG, "Updating external media status from " 20954 + (mMediaMounted ? "mounted" : "unmounted") + " to " 20955 + (mediaStatus ? "mounted" : "unmounted")); 20956 if (DEBUG_SD_INSTALL) 20957 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 20958 + ", mMediaMounted=" + mMediaMounted); 20959 if (mediaStatus == mMediaMounted) { 20960 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 20961 : 0, -1); 20962 mHandler.sendMessage(msg); 20963 return; 20964 } 20965 mMediaMounted = mediaStatus; 20966 } 20967 // Queue up an async operation since the package installation may take a 20968 // little while. 20969 mHandler.post(new Runnable() { 20970 public void run() { 20971 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 20972 } 20973 }); 20974 } 20975 20976 /** 20977 * Called by StorageManagerService when the initial ASECs to scan are available. 20978 * Should block until all the ASEC containers are finished being scanned. 20979 */ 20980 public void scanAvailableAsecs() { 20981 updateExternalMediaStatusInner(true, false, false); 20982 } 20983 20984 /* 20985 * Collect information of applications on external media, map them against 20986 * existing containers and update information based on current mount status. 20987 * Please note that we always have to report status if reportStatus has been 20988 * set to true especially when unloading packages. 20989 */ 20990 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 20991 boolean externalStorage) { 20992 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 20993 int[] uidArr = EmptyArray.INT; 20994 20995 final String[] list = PackageHelper.getSecureContainerList(); 20996 if (ArrayUtils.isEmpty(list)) { 20997 Log.i(TAG, "No secure containers found"); 20998 } else { 20999 // Process list of secure containers and categorize them 21000 // as active or stale based on their package internal state. 21001 21002 // reader 21003 synchronized (mPackages) { 21004 for (String cid : list) { 21005 // Leave stages untouched for now; installer service owns them 21006 if (PackageInstallerService.isStageName(cid)) continue; 21007 21008 if (DEBUG_SD_INSTALL) 21009 Log.i(TAG, "Processing container " + cid); 21010 String pkgName = getAsecPackageName(cid); 21011 if (pkgName == null) { 21012 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21013 continue; 21014 } 21015 if (DEBUG_SD_INSTALL) 21016 Log.i(TAG, "Looking for pkg : " + pkgName); 21017 21018 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21019 if (ps == null) { 21020 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21021 continue; 21022 } 21023 21024 /* 21025 * Skip packages that are not external if we're unmounting 21026 * external storage. 21027 */ 21028 if (externalStorage && !isMounted && !isExternal(ps)) { 21029 continue; 21030 } 21031 21032 final AsecInstallArgs args = new AsecInstallArgs(cid, 21033 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21034 // The package status is changed only if the code path 21035 // matches between settings and the container id. 21036 if (ps.codePathString != null 21037 && ps.codePathString.startsWith(args.getCodePath())) { 21038 if (DEBUG_SD_INSTALL) { 21039 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21040 + " at code path: " + ps.codePathString); 21041 } 21042 21043 // We do have a valid package installed on sdcard 21044 processCids.put(args, ps.codePathString); 21045 final int uid = ps.appId; 21046 if (uid != -1) { 21047 uidArr = ArrayUtils.appendInt(uidArr, uid); 21048 } 21049 } else { 21050 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21051 + ps.codePathString); 21052 } 21053 } 21054 } 21055 21056 Arrays.sort(uidArr); 21057 } 21058 21059 // Process packages with valid entries. 21060 if (isMounted) { 21061 if (DEBUG_SD_INSTALL) 21062 Log.i(TAG, "Loading packages"); 21063 loadMediaPackages(processCids, uidArr, externalStorage); 21064 startCleaningPackages(); 21065 mInstallerService.onSecureContainersAvailable(); 21066 } else { 21067 if (DEBUG_SD_INSTALL) 21068 Log.i(TAG, "Unloading packages"); 21069 unloadMediaPackages(processCids, uidArr, reportStatus); 21070 } 21071 } 21072 21073 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21074 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21075 final int size = infos.size(); 21076 final String[] packageNames = new String[size]; 21077 final int[] packageUids = new int[size]; 21078 for (int i = 0; i < size; i++) { 21079 final ApplicationInfo info = infos.get(i); 21080 packageNames[i] = info.packageName; 21081 packageUids[i] = info.uid; 21082 } 21083 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21084 finishedReceiver); 21085 } 21086 21087 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21088 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21089 sendResourcesChangedBroadcast(mediaStatus, replacing, 21090 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21091 } 21092 21093 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21094 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21095 int size = pkgList.length; 21096 if (size > 0) { 21097 // Send broadcasts here 21098 Bundle extras = new Bundle(); 21099 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21100 if (uidArr != null) { 21101 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21102 } 21103 if (replacing) { 21104 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21105 } 21106 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21107 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21108 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21109 } 21110 } 21111 21112 /* 21113 * Look at potentially valid container ids from processCids If package 21114 * information doesn't match the one on record or package scanning fails, 21115 * the cid is added to list of removeCids. We currently don't delete stale 21116 * containers. 21117 */ 21118 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21119 boolean externalStorage) { 21120 ArrayList<String> pkgList = new ArrayList<String>(); 21121 Set<AsecInstallArgs> keys = processCids.keySet(); 21122 21123 for (AsecInstallArgs args : keys) { 21124 String codePath = processCids.get(args); 21125 if (DEBUG_SD_INSTALL) 21126 Log.i(TAG, "Loading container : " + args.cid); 21127 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21128 try { 21129 // Make sure there are no container errors first. 21130 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21131 Slog.e(TAG, "Failed to mount cid : " + args.cid 21132 + " when installing from sdcard"); 21133 continue; 21134 } 21135 // Check code path here. 21136 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21137 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21138 + " does not match one in settings " + codePath); 21139 continue; 21140 } 21141 // Parse package 21142 int parseFlags = mDefParseFlags; 21143 if (args.isExternalAsec()) { 21144 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21145 } 21146 if (args.isFwdLocked()) { 21147 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21148 } 21149 21150 synchronized (mInstallLock) { 21151 PackageParser.Package pkg = null; 21152 try { 21153 // Sadly we don't know the package name yet to freeze it 21154 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21155 SCAN_IGNORE_FROZEN, 0, null); 21156 } catch (PackageManagerException e) { 21157 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21158 } 21159 // Scan the package 21160 if (pkg != null) { 21161 /* 21162 * TODO why is the lock being held? doPostInstall is 21163 * called in other places without the lock. This needs 21164 * to be straightened out. 21165 */ 21166 // writer 21167 synchronized (mPackages) { 21168 retCode = PackageManager.INSTALL_SUCCEEDED; 21169 pkgList.add(pkg.packageName); 21170 // Post process args 21171 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21172 pkg.applicationInfo.uid); 21173 } 21174 } else { 21175 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21176 } 21177 } 21178 21179 } finally { 21180 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21181 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21182 } 21183 } 21184 } 21185 // writer 21186 synchronized (mPackages) { 21187 // If the platform SDK has changed since the last time we booted, 21188 // we need to re-grant app permission to catch any new ones that 21189 // appear. This is really a hack, and means that apps can in some 21190 // cases get permissions that the user didn't initially explicitly 21191 // allow... it would be nice to have some better way to handle 21192 // this situation. 21193 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21194 : mSettings.getInternalVersion(); 21195 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21196 : StorageManager.UUID_PRIVATE_INTERNAL; 21197 21198 int updateFlags = UPDATE_PERMISSIONS_ALL; 21199 if (ver.sdkVersion != mSdkVersion) { 21200 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21201 + mSdkVersion + "; regranting permissions for external"); 21202 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21203 } 21204 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21205 21206 // Yay, everything is now upgraded 21207 ver.forceCurrent(); 21208 21209 // can downgrade to reader 21210 // Persist settings 21211 mSettings.writeLPr(); 21212 } 21213 // Send a broadcast to let everyone know we are done processing 21214 if (pkgList.size() > 0) { 21215 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21216 } 21217 } 21218 21219 /* 21220 * Utility method to unload a list of specified containers 21221 */ 21222 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21223 // Just unmount all valid containers. 21224 for (AsecInstallArgs arg : cidArgs) { 21225 synchronized (mInstallLock) { 21226 arg.doPostDeleteLI(false); 21227 } 21228 } 21229 } 21230 21231 /* 21232 * Unload packages mounted on external media. This involves deleting package 21233 * data from internal structures, sending broadcasts about disabled packages, 21234 * gc'ing to free up references, unmounting all secure containers 21235 * corresponding to packages on external media, and posting a 21236 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21237 * that we always have to post this message if status has been requested no 21238 * matter what. 21239 */ 21240 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21241 final boolean reportStatus) { 21242 if (DEBUG_SD_INSTALL) 21243 Log.i(TAG, "unloading media packages"); 21244 ArrayList<String> pkgList = new ArrayList<String>(); 21245 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21246 final Set<AsecInstallArgs> keys = processCids.keySet(); 21247 for (AsecInstallArgs args : keys) { 21248 String pkgName = args.getPackageName(); 21249 if (DEBUG_SD_INSTALL) 21250 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21251 // Delete package internally 21252 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21253 synchronized (mInstallLock) { 21254 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21255 final boolean res; 21256 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21257 "unloadMediaPackages")) { 21258 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21259 null); 21260 } 21261 if (res) { 21262 pkgList.add(pkgName); 21263 } else { 21264 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21265 failedList.add(args); 21266 } 21267 } 21268 } 21269 21270 // reader 21271 synchronized (mPackages) { 21272 // We didn't update the settings after removing each package; 21273 // write them now for all packages. 21274 mSettings.writeLPr(); 21275 } 21276 21277 // We have to absolutely send UPDATED_MEDIA_STATUS only 21278 // after confirming that all the receivers processed the ordered 21279 // broadcast when packages get disabled, force a gc to clean things up. 21280 // and unload all the containers. 21281 if (pkgList.size() > 0) { 21282 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21283 new IIntentReceiver.Stub() { 21284 public void performReceive(Intent intent, int resultCode, String data, 21285 Bundle extras, boolean ordered, boolean sticky, 21286 int sendingUser) throws RemoteException { 21287 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21288 reportStatus ? 1 : 0, 1, keys); 21289 mHandler.sendMessage(msg); 21290 } 21291 }); 21292 } else { 21293 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21294 keys); 21295 mHandler.sendMessage(msg); 21296 } 21297 } 21298 21299 private void loadPrivatePackages(final VolumeInfo vol) { 21300 mHandler.post(new Runnable() { 21301 @Override 21302 public void run() { 21303 loadPrivatePackagesInner(vol); 21304 } 21305 }); 21306 } 21307 21308 private void loadPrivatePackagesInner(VolumeInfo vol) { 21309 final String volumeUuid = vol.fsUuid; 21310 if (TextUtils.isEmpty(volumeUuid)) { 21311 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21312 return; 21313 } 21314 21315 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21316 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21317 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21318 21319 final VersionInfo ver; 21320 final List<PackageSetting> packages; 21321 synchronized (mPackages) { 21322 ver = mSettings.findOrCreateVersion(volumeUuid); 21323 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21324 } 21325 21326 for (PackageSetting ps : packages) { 21327 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21328 synchronized (mInstallLock) { 21329 final PackageParser.Package pkg; 21330 try { 21331 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21332 loaded.add(pkg.applicationInfo); 21333 21334 } catch (PackageManagerException e) { 21335 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21336 } 21337 21338 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21339 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21340 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21341 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21342 } 21343 } 21344 } 21345 21346 // Reconcile app data for all started/unlocked users 21347 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21348 final UserManager um = mContext.getSystemService(UserManager.class); 21349 UserManagerInternal umInternal = getUserManagerInternal(); 21350 for (UserInfo user : um.getUsers()) { 21351 final int flags; 21352 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21353 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21354 } else if (umInternal.isUserRunning(user.id)) { 21355 flags = StorageManager.FLAG_STORAGE_DE; 21356 } else { 21357 continue; 21358 } 21359 21360 try { 21361 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21362 synchronized (mInstallLock) { 21363 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21364 } 21365 } catch (IllegalStateException e) { 21366 // Device was probably ejected, and we'll process that event momentarily 21367 Slog.w(TAG, "Failed to prepare storage: " + e); 21368 } 21369 } 21370 21371 synchronized (mPackages) { 21372 int updateFlags = UPDATE_PERMISSIONS_ALL; 21373 if (ver.sdkVersion != mSdkVersion) { 21374 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21375 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21376 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21377 } 21378 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21379 21380 // Yay, everything is now upgraded 21381 ver.forceCurrent(); 21382 21383 mSettings.writeLPr(); 21384 } 21385 21386 for (PackageFreezer freezer : freezers) { 21387 freezer.close(); 21388 } 21389 21390 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21391 sendResourcesChangedBroadcast(true, false, loaded, null); 21392 } 21393 21394 private void unloadPrivatePackages(final VolumeInfo vol) { 21395 mHandler.post(new Runnable() { 21396 @Override 21397 public void run() { 21398 unloadPrivatePackagesInner(vol); 21399 } 21400 }); 21401 } 21402 21403 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21404 final String volumeUuid = vol.fsUuid; 21405 if (TextUtils.isEmpty(volumeUuid)) { 21406 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21407 return; 21408 } 21409 21410 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21411 synchronized (mInstallLock) { 21412 synchronized (mPackages) { 21413 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21414 for (PackageSetting ps : packages) { 21415 if (ps.pkg == null) continue; 21416 21417 final ApplicationInfo info = ps.pkg.applicationInfo; 21418 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21419 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21420 21421 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21422 "unloadPrivatePackagesInner")) { 21423 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21424 false, null)) { 21425 unloaded.add(info); 21426 } else { 21427 Slog.w(TAG, "Failed to unload " + ps.codePath); 21428 } 21429 } 21430 21431 // Try very hard to release any references to this package 21432 // so we don't risk the system server being killed due to 21433 // open FDs 21434 AttributeCache.instance().removePackage(ps.name); 21435 } 21436 21437 mSettings.writeLPr(); 21438 } 21439 } 21440 21441 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21442 sendResourcesChangedBroadcast(false, false, unloaded, null); 21443 21444 // Try very hard to release any references to this path so we don't risk 21445 // the system server being killed due to open FDs 21446 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21447 21448 for (int i = 0; i < 3; i++) { 21449 System.gc(); 21450 System.runFinalization(); 21451 } 21452 } 21453 21454 private void assertPackageKnown(String volumeUuid, String packageName) 21455 throws PackageManagerException { 21456 synchronized (mPackages) { 21457 // Normalize package name to handle renamed packages 21458 packageName = normalizePackageNameLPr(packageName); 21459 21460 final PackageSetting ps = mSettings.mPackages.get(packageName); 21461 if (ps == null) { 21462 throw new PackageManagerException("Package " + packageName + " is unknown"); 21463 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21464 throw new PackageManagerException( 21465 "Package " + packageName + " found on unknown volume " + volumeUuid 21466 + "; expected volume " + ps.volumeUuid); 21467 } 21468 } 21469 } 21470 21471 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21472 throws PackageManagerException { 21473 synchronized (mPackages) { 21474 // Normalize package name to handle renamed packages 21475 packageName = normalizePackageNameLPr(packageName); 21476 21477 final PackageSetting ps = mSettings.mPackages.get(packageName); 21478 if (ps == null) { 21479 throw new PackageManagerException("Package " + packageName + " is unknown"); 21480 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21481 throw new PackageManagerException( 21482 "Package " + packageName + " found on unknown volume " + volumeUuid 21483 + "; expected volume " + ps.volumeUuid); 21484 } else if (!ps.getInstalled(userId)) { 21485 throw new PackageManagerException( 21486 "Package " + packageName + " not installed for user " + userId); 21487 } 21488 } 21489 } 21490 21491 private List<String> collectAbsoluteCodePaths() { 21492 synchronized (mPackages) { 21493 List<String> codePaths = new ArrayList<>(); 21494 final int packageCount = mSettings.mPackages.size(); 21495 for (int i = 0; i < packageCount; i++) { 21496 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21497 codePaths.add(ps.codePath.getAbsolutePath()); 21498 } 21499 return codePaths; 21500 } 21501 } 21502 21503 /** 21504 * Examine all apps present on given mounted volume, and destroy apps that 21505 * aren't expected, either due to uninstallation or reinstallation on 21506 * another volume. 21507 */ 21508 private void reconcileApps(String volumeUuid) { 21509 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21510 List<File> filesToDelete = null; 21511 21512 final File[] files = FileUtils.listFilesOrEmpty( 21513 Environment.getDataAppDirectory(volumeUuid)); 21514 for (File file : files) { 21515 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21516 && !PackageInstallerService.isStageName(file.getName()); 21517 if (!isPackage) { 21518 // Ignore entries which are not packages 21519 continue; 21520 } 21521 21522 String absolutePath = file.getAbsolutePath(); 21523 21524 boolean pathValid = false; 21525 final int absoluteCodePathCount = absoluteCodePaths.size(); 21526 for (int i = 0; i < absoluteCodePathCount; i++) { 21527 String absoluteCodePath = absoluteCodePaths.get(i); 21528 if (absolutePath.startsWith(absoluteCodePath)) { 21529 pathValid = true; 21530 break; 21531 } 21532 } 21533 21534 if (!pathValid) { 21535 if (filesToDelete == null) { 21536 filesToDelete = new ArrayList<>(); 21537 } 21538 filesToDelete.add(file); 21539 } 21540 } 21541 21542 if (filesToDelete != null) { 21543 final int fileToDeleteCount = filesToDelete.size(); 21544 for (int i = 0; i < fileToDeleteCount; i++) { 21545 File fileToDelete = filesToDelete.get(i); 21546 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21547 synchronized (mInstallLock) { 21548 removeCodePathLI(fileToDelete); 21549 } 21550 } 21551 } 21552 } 21553 21554 /** 21555 * Reconcile all app data for the given user. 21556 * <p> 21557 * Verifies that directories exist and that ownership and labeling is 21558 * correct for all installed apps on all mounted volumes. 21559 */ 21560 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21561 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21562 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21563 final String volumeUuid = vol.getFsUuid(); 21564 synchronized (mInstallLock) { 21565 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21566 } 21567 } 21568 } 21569 21570 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21571 boolean migrateAppData) { 21572 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21573 } 21574 21575 /** 21576 * Reconcile all app data on given mounted volume. 21577 * <p> 21578 * Destroys app data that isn't expected, either due to uninstallation or 21579 * reinstallation on another volume. 21580 * <p> 21581 * Verifies that directories exist and that ownership and labeling is 21582 * correct for all installed apps. 21583 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21584 */ 21585 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21586 boolean migrateAppData, boolean onlyCoreApps) { 21587 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21588 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21589 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21590 21591 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21592 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21593 21594 // First look for stale data that doesn't belong, and check if things 21595 // have changed since we did our last restorecon 21596 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21597 if (StorageManager.isFileEncryptedNativeOrEmulated() 21598 && !StorageManager.isUserKeyUnlocked(userId)) { 21599 throw new RuntimeException( 21600 "Yikes, someone asked us to reconcile CE storage while " + userId 21601 + " was still locked; this would have caused massive data loss!"); 21602 } 21603 21604 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21605 for (File file : files) { 21606 final String packageName = file.getName(); 21607 try { 21608 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21609 } catch (PackageManagerException e) { 21610 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21611 try { 21612 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21613 StorageManager.FLAG_STORAGE_CE, 0); 21614 } catch (InstallerException e2) { 21615 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21616 } 21617 } 21618 } 21619 } 21620 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21621 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21622 for (File file : files) { 21623 final String packageName = file.getName(); 21624 try { 21625 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21626 } catch (PackageManagerException e) { 21627 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21628 try { 21629 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21630 StorageManager.FLAG_STORAGE_DE, 0); 21631 } catch (InstallerException e2) { 21632 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21633 } 21634 } 21635 } 21636 } 21637 21638 // Ensure that data directories are ready to roll for all packages 21639 // installed for this volume and user 21640 final List<PackageSetting> packages; 21641 synchronized (mPackages) { 21642 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21643 } 21644 int preparedCount = 0; 21645 for (PackageSetting ps : packages) { 21646 final String packageName = ps.name; 21647 if (ps.pkg == null) { 21648 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21649 // TODO: might be due to legacy ASEC apps; we should circle back 21650 // and reconcile again once they're scanned 21651 continue; 21652 } 21653 // Skip non-core apps if requested 21654 if (onlyCoreApps && !ps.pkg.coreApp) { 21655 result.add(packageName); 21656 continue; 21657 } 21658 21659 if (ps.getInstalled(userId)) { 21660 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21661 preparedCount++; 21662 } 21663 } 21664 21665 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21666 return result; 21667 } 21668 21669 /** 21670 * Prepare app data for the given app just after it was installed or 21671 * upgraded. This method carefully only touches users that it's installed 21672 * for, and it forces a restorecon to handle any seinfo changes. 21673 * <p> 21674 * Verifies that directories exist and that ownership and labeling is 21675 * correct for all installed apps. If there is an ownership mismatch, it 21676 * will try recovering system apps by wiping data; third-party app data is 21677 * left intact. 21678 * <p> 21679 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21680 */ 21681 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21682 final PackageSetting ps; 21683 synchronized (mPackages) { 21684 ps = mSettings.mPackages.get(pkg.packageName); 21685 mSettings.writeKernelMappingLPr(ps); 21686 } 21687 21688 final UserManager um = mContext.getSystemService(UserManager.class); 21689 UserManagerInternal umInternal = getUserManagerInternal(); 21690 for (UserInfo user : um.getUsers()) { 21691 final int flags; 21692 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21693 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21694 } else if (umInternal.isUserRunning(user.id)) { 21695 flags = StorageManager.FLAG_STORAGE_DE; 21696 } else { 21697 continue; 21698 } 21699 21700 if (ps.getInstalled(user.id)) { 21701 // TODO: when user data is locked, mark that we're still dirty 21702 prepareAppDataLIF(pkg, user.id, flags); 21703 } 21704 } 21705 } 21706 21707 /** 21708 * Prepare app data for the given app. 21709 * <p> 21710 * Verifies that directories exist and that ownership and labeling is 21711 * correct for all installed apps. If there is an ownership mismatch, this 21712 * will try recovering system apps by wiping data; third-party app data is 21713 * left intact. 21714 */ 21715 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21716 if (pkg == null) { 21717 Slog.wtf(TAG, "Package was null!", new Throwable()); 21718 return; 21719 } 21720 prepareAppDataLeafLIF(pkg, userId, flags); 21721 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21722 for (int i = 0; i < childCount; i++) { 21723 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21724 } 21725 } 21726 21727 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21728 boolean maybeMigrateAppData) { 21729 prepareAppDataLIF(pkg, userId, flags); 21730 21731 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21732 // We may have just shuffled around app data directories, so 21733 // prepare them one more time 21734 prepareAppDataLIF(pkg, userId, flags); 21735 } 21736 } 21737 21738 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21739 if (DEBUG_APP_DATA) { 21740 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21741 + Integer.toHexString(flags)); 21742 } 21743 21744 final String volumeUuid = pkg.volumeUuid; 21745 final String packageName = pkg.packageName; 21746 final ApplicationInfo app = pkg.applicationInfo; 21747 final int appId = UserHandle.getAppId(app.uid); 21748 21749 Preconditions.checkNotNull(app.seInfo); 21750 21751 long ceDataInode = -1; 21752 try { 21753 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21754 appId, app.seInfo, app.targetSdkVersion); 21755 } catch (InstallerException e) { 21756 if (app.isSystemApp()) { 21757 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21758 + ", but trying to recover: " + e); 21759 destroyAppDataLeafLIF(pkg, userId, flags); 21760 try { 21761 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21762 appId, app.seInfo, app.targetSdkVersion); 21763 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21764 } catch (InstallerException e2) { 21765 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21766 } 21767 } else { 21768 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21769 } 21770 } 21771 21772 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21773 // TODO: mark this structure as dirty so we persist it! 21774 synchronized (mPackages) { 21775 final PackageSetting ps = mSettings.mPackages.get(packageName); 21776 if (ps != null) { 21777 ps.setCeDataInode(ceDataInode, userId); 21778 } 21779 } 21780 } 21781 21782 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21783 } 21784 21785 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21786 if (pkg == null) { 21787 Slog.wtf(TAG, "Package was null!", new Throwable()); 21788 return; 21789 } 21790 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21791 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21792 for (int i = 0; i < childCount; i++) { 21793 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21794 } 21795 } 21796 21797 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21798 final String volumeUuid = pkg.volumeUuid; 21799 final String packageName = pkg.packageName; 21800 final ApplicationInfo app = pkg.applicationInfo; 21801 21802 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21803 // Create a native library symlink only if we have native libraries 21804 // and if the native libraries are 32 bit libraries. We do not provide 21805 // this symlink for 64 bit libraries. 21806 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21807 final String nativeLibPath = app.nativeLibraryDir; 21808 try { 21809 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21810 nativeLibPath, userId); 21811 } catch (InstallerException e) { 21812 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21813 } 21814 } 21815 } 21816 } 21817 21818 /** 21819 * For system apps on non-FBE devices, this method migrates any existing 21820 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21821 * requested by the app. 21822 */ 21823 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21824 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21825 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21826 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21827 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21828 try { 21829 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21830 storageTarget); 21831 } catch (InstallerException e) { 21832 logCriticalInfo(Log.WARN, 21833 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21834 } 21835 return true; 21836 } else { 21837 return false; 21838 } 21839 } 21840 21841 public PackageFreezer freezePackage(String packageName, String killReason) { 21842 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21843 } 21844 21845 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21846 return new PackageFreezer(packageName, userId, killReason); 21847 } 21848 21849 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21850 String killReason) { 21851 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21852 } 21853 21854 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21855 String killReason) { 21856 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21857 return new PackageFreezer(); 21858 } else { 21859 return freezePackage(packageName, userId, killReason); 21860 } 21861 } 21862 21863 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21864 String killReason) { 21865 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21866 } 21867 21868 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21869 String killReason) { 21870 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21871 return new PackageFreezer(); 21872 } else { 21873 return freezePackage(packageName, userId, killReason); 21874 } 21875 } 21876 21877 /** 21878 * Class that freezes and kills the given package upon creation, and 21879 * unfreezes it upon closing. This is typically used when doing surgery on 21880 * app code/data to prevent the app from running while you're working. 21881 */ 21882 private class PackageFreezer implements AutoCloseable { 21883 private final String mPackageName; 21884 private final PackageFreezer[] mChildren; 21885 21886 private final boolean mWeFroze; 21887 21888 private final AtomicBoolean mClosed = new AtomicBoolean(); 21889 private final CloseGuard mCloseGuard = CloseGuard.get(); 21890 21891 /** 21892 * Create and return a stub freezer that doesn't actually do anything, 21893 * typically used when someone requested 21894 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21895 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21896 */ 21897 public PackageFreezer() { 21898 mPackageName = null; 21899 mChildren = null; 21900 mWeFroze = false; 21901 mCloseGuard.open("close"); 21902 } 21903 21904 public PackageFreezer(String packageName, int userId, String killReason) { 21905 synchronized (mPackages) { 21906 mPackageName = packageName; 21907 mWeFroze = mFrozenPackages.add(mPackageName); 21908 21909 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21910 if (ps != null) { 21911 killApplication(ps.name, ps.appId, userId, killReason); 21912 } 21913 21914 final PackageParser.Package p = mPackages.get(packageName); 21915 if (p != null && p.childPackages != null) { 21916 final int N = p.childPackages.size(); 21917 mChildren = new PackageFreezer[N]; 21918 for (int i = 0; i < N; i++) { 21919 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21920 userId, killReason); 21921 } 21922 } else { 21923 mChildren = null; 21924 } 21925 } 21926 mCloseGuard.open("close"); 21927 } 21928 21929 @Override 21930 protected void finalize() throws Throwable { 21931 try { 21932 mCloseGuard.warnIfOpen(); 21933 close(); 21934 } finally { 21935 super.finalize(); 21936 } 21937 } 21938 21939 @Override 21940 public void close() { 21941 mCloseGuard.close(); 21942 if (mClosed.compareAndSet(false, true)) { 21943 synchronized (mPackages) { 21944 if (mWeFroze) { 21945 mFrozenPackages.remove(mPackageName); 21946 } 21947 21948 if (mChildren != null) { 21949 for (PackageFreezer freezer : mChildren) { 21950 freezer.close(); 21951 } 21952 } 21953 } 21954 } 21955 } 21956 } 21957 21958 /** 21959 * Verify that given package is currently frozen. 21960 */ 21961 private void checkPackageFrozen(String packageName) { 21962 synchronized (mPackages) { 21963 if (!mFrozenPackages.contains(packageName)) { 21964 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21965 } 21966 } 21967 } 21968 21969 @Override 21970 public int movePackage(final String packageName, final String volumeUuid) { 21971 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21972 21973 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 21974 final int moveId = mNextMoveId.getAndIncrement(); 21975 mHandler.post(new Runnable() { 21976 @Override 21977 public void run() { 21978 try { 21979 movePackageInternal(packageName, volumeUuid, moveId, user); 21980 } catch (PackageManagerException e) { 21981 Slog.w(TAG, "Failed to move " + packageName, e); 21982 mMoveCallbacks.notifyStatusChanged(moveId, 21983 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21984 } 21985 } 21986 }); 21987 return moveId; 21988 } 21989 21990 private void movePackageInternal(final String packageName, final String volumeUuid, 21991 final int moveId, UserHandle user) throws PackageManagerException { 21992 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21993 final PackageManager pm = mContext.getPackageManager(); 21994 21995 final boolean currentAsec; 21996 final String currentVolumeUuid; 21997 final File codeFile; 21998 final String installerPackageName; 21999 final String packageAbiOverride; 22000 final int appId; 22001 final String seinfo; 22002 final String label; 22003 final int targetSdkVersion; 22004 final PackageFreezer freezer; 22005 final int[] installedUserIds; 22006 22007 // reader 22008 synchronized (mPackages) { 22009 final PackageParser.Package pkg = mPackages.get(packageName); 22010 final PackageSetting ps = mSettings.mPackages.get(packageName); 22011 if (pkg == null || ps == null) { 22012 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22013 } 22014 22015 if (pkg.applicationInfo.isSystemApp()) { 22016 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22017 "Cannot move system application"); 22018 } 22019 22020 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22021 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22022 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22023 if (isInternalStorage && !allow3rdPartyOnInternal) { 22024 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22025 "3rd party apps are not allowed on internal storage"); 22026 } 22027 22028 if (pkg.applicationInfo.isExternalAsec()) { 22029 currentAsec = true; 22030 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22031 } else if (pkg.applicationInfo.isForwardLocked()) { 22032 currentAsec = true; 22033 currentVolumeUuid = "forward_locked"; 22034 } else { 22035 currentAsec = false; 22036 currentVolumeUuid = ps.volumeUuid; 22037 22038 final File probe = new File(pkg.codePath); 22039 final File probeOat = new File(probe, "oat"); 22040 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22041 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22042 "Move only supported for modern cluster style installs"); 22043 } 22044 } 22045 22046 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22047 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22048 "Package already moved to " + volumeUuid); 22049 } 22050 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22051 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22052 "Device admin cannot be moved"); 22053 } 22054 22055 if (mFrozenPackages.contains(packageName)) { 22056 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22057 "Failed to move already frozen package"); 22058 } 22059 22060 codeFile = new File(pkg.codePath); 22061 installerPackageName = ps.installerPackageName; 22062 packageAbiOverride = ps.cpuAbiOverrideString; 22063 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22064 seinfo = pkg.applicationInfo.seInfo; 22065 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22066 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22067 freezer = freezePackage(packageName, "movePackageInternal"); 22068 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22069 } 22070 22071 final Bundle extras = new Bundle(); 22072 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22073 extras.putString(Intent.EXTRA_TITLE, label); 22074 mMoveCallbacks.notifyCreated(moveId, extras); 22075 22076 int installFlags; 22077 final boolean moveCompleteApp; 22078 final File measurePath; 22079 22080 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22081 installFlags = INSTALL_INTERNAL; 22082 moveCompleteApp = !currentAsec; 22083 measurePath = Environment.getDataAppDirectory(volumeUuid); 22084 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22085 installFlags = INSTALL_EXTERNAL; 22086 moveCompleteApp = false; 22087 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22088 } else { 22089 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22090 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22091 || !volume.isMountedWritable()) { 22092 freezer.close(); 22093 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22094 "Move location not mounted private volume"); 22095 } 22096 22097 Preconditions.checkState(!currentAsec); 22098 22099 installFlags = INSTALL_INTERNAL; 22100 moveCompleteApp = true; 22101 measurePath = Environment.getDataAppDirectory(volumeUuid); 22102 } 22103 22104 final PackageStats stats = new PackageStats(null, -1); 22105 synchronized (mInstaller) { 22106 for (int userId : installedUserIds) { 22107 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22108 freezer.close(); 22109 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22110 "Failed to measure package size"); 22111 } 22112 } 22113 } 22114 22115 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22116 + stats.dataSize); 22117 22118 final long startFreeBytes = measurePath.getFreeSpace(); 22119 final long sizeBytes; 22120 if (moveCompleteApp) { 22121 sizeBytes = stats.codeSize + stats.dataSize; 22122 } else { 22123 sizeBytes = stats.codeSize; 22124 } 22125 22126 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22127 freezer.close(); 22128 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22129 "Not enough free space to move"); 22130 } 22131 22132 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22133 22134 final CountDownLatch installedLatch = new CountDownLatch(1); 22135 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22136 @Override 22137 public void onUserActionRequired(Intent intent) throws RemoteException { 22138 throw new IllegalStateException(); 22139 } 22140 22141 @Override 22142 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22143 Bundle extras) throws RemoteException { 22144 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22145 + PackageManager.installStatusToString(returnCode, msg)); 22146 22147 installedLatch.countDown(); 22148 freezer.close(); 22149 22150 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22151 switch (status) { 22152 case PackageInstaller.STATUS_SUCCESS: 22153 mMoveCallbacks.notifyStatusChanged(moveId, 22154 PackageManager.MOVE_SUCCEEDED); 22155 break; 22156 case PackageInstaller.STATUS_FAILURE_STORAGE: 22157 mMoveCallbacks.notifyStatusChanged(moveId, 22158 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22159 break; 22160 default: 22161 mMoveCallbacks.notifyStatusChanged(moveId, 22162 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22163 break; 22164 } 22165 } 22166 }; 22167 22168 final MoveInfo move; 22169 if (moveCompleteApp) { 22170 // Kick off a thread to report progress estimates 22171 new Thread() { 22172 @Override 22173 public void run() { 22174 while (true) { 22175 try { 22176 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22177 break; 22178 } 22179 } catch (InterruptedException ignored) { 22180 } 22181 22182 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22183 final int progress = 10 + (int) MathUtils.constrain( 22184 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22185 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22186 } 22187 } 22188 }.start(); 22189 22190 final String dataAppName = codeFile.getName(); 22191 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22192 dataAppName, appId, seinfo, targetSdkVersion); 22193 } else { 22194 move = null; 22195 } 22196 22197 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22198 22199 final Message msg = mHandler.obtainMessage(INIT_COPY); 22200 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22201 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22202 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22203 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22204 PackageManager.INSTALL_REASON_UNKNOWN); 22205 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22206 msg.obj = params; 22207 22208 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22209 System.identityHashCode(msg.obj)); 22210 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22211 System.identityHashCode(msg.obj)); 22212 22213 mHandler.sendMessage(msg); 22214 } 22215 22216 @Override 22217 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22218 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22219 22220 final int realMoveId = mNextMoveId.getAndIncrement(); 22221 final Bundle extras = new Bundle(); 22222 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22223 mMoveCallbacks.notifyCreated(realMoveId, extras); 22224 22225 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22226 @Override 22227 public void onCreated(int moveId, Bundle extras) { 22228 // Ignored 22229 } 22230 22231 @Override 22232 public void onStatusChanged(int moveId, int status, long estMillis) { 22233 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22234 } 22235 }; 22236 22237 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22238 storage.setPrimaryStorageUuid(volumeUuid, callback); 22239 return realMoveId; 22240 } 22241 22242 @Override 22243 public int getMoveStatus(int moveId) { 22244 mContext.enforceCallingOrSelfPermission( 22245 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22246 return mMoveCallbacks.mLastStatus.get(moveId); 22247 } 22248 22249 @Override 22250 public void registerMoveCallback(IPackageMoveObserver callback) { 22251 mContext.enforceCallingOrSelfPermission( 22252 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22253 mMoveCallbacks.register(callback); 22254 } 22255 22256 @Override 22257 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22258 mContext.enforceCallingOrSelfPermission( 22259 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22260 mMoveCallbacks.unregister(callback); 22261 } 22262 22263 @Override 22264 public boolean setInstallLocation(int loc) { 22265 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22266 null); 22267 if (getInstallLocation() == loc) { 22268 return true; 22269 } 22270 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22271 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22272 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22273 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22274 return true; 22275 } 22276 return false; 22277 } 22278 22279 @Override 22280 public int getInstallLocation() { 22281 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22282 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22283 PackageHelper.APP_INSTALL_AUTO); 22284 } 22285 22286 /** Called by UserManagerService */ 22287 void cleanUpUser(UserManagerService userManager, int userHandle) { 22288 synchronized (mPackages) { 22289 mDirtyUsers.remove(userHandle); 22290 mUserNeedsBadging.delete(userHandle); 22291 mSettings.removeUserLPw(userHandle); 22292 mPendingBroadcasts.remove(userHandle); 22293 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22294 removeUnusedPackagesLPw(userManager, userHandle); 22295 } 22296 } 22297 22298 /** 22299 * We're removing userHandle and would like to remove any downloaded packages 22300 * that are no longer in use by any other user. 22301 * @param userHandle the user being removed 22302 */ 22303 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22304 final boolean DEBUG_CLEAN_APKS = false; 22305 int [] users = userManager.getUserIds(); 22306 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22307 while (psit.hasNext()) { 22308 PackageSetting ps = psit.next(); 22309 if (ps.pkg == null) { 22310 continue; 22311 } 22312 final String packageName = ps.pkg.packageName; 22313 // Skip over if system app 22314 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22315 continue; 22316 } 22317 if (DEBUG_CLEAN_APKS) { 22318 Slog.i(TAG, "Checking package " + packageName); 22319 } 22320 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22321 if (keep) { 22322 if (DEBUG_CLEAN_APKS) { 22323 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22324 } 22325 } else { 22326 for (int i = 0; i < users.length; i++) { 22327 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22328 keep = true; 22329 if (DEBUG_CLEAN_APKS) { 22330 Slog.i(TAG, " Keeping package " + packageName + " for user " 22331 + users[i]); 22332 } 22333 break; 22334 } 22335 } 22336 } 22337 if (!keep) { 22338 if (DEBUG_CLEAN_APKS) { 22339 Slog.i(TAG, " Removing package " + packageName); 22340 } 22341 mHandler.post(new Runnable() { 22342 public void run() { 22343 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22344 userHandle, 0); 22345 } //end run 22346 }); 22347 } 22348 } 22349 } 22350 22351 /** Called by UserManagerService */ 22352 void createNewUser(int userId, String[] disallowedPackages) { 22353 synchronized (mInstallLock) { 22354 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22355 } 22356 synchronized (mPackages) { 22357 scheduleWritePackageRestrictionsLocked(userId); 22358 scheduleWritePackageListLocked(userId); 22359 applyFactoryDefaultBrowserLPw(userId); 22360 primeDomainVerificationsLPw(userId); 22361 } 22362 } 22363 22364 void onNewUserCreated(final int userId) { 22365 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22366 // If permission review for legacy apps is required, we represent 22367 // dagerous permissions for such apps as always granted runtime 22368 // permissions to keep per user flag state whether review is needed. 22369 // Hence, if a new user is added we have to propagate dangerous 22370 // permission grants for these legacy apps. 22371 if (mPermissionReviewRequired) { 22372 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22373 | UPDATE_PERMISSIONS_REPLACE_ALL); 22374 } 22375 } 22376 22377 @Override 22378 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22379 mContext.enforceCallingOrSelfPermission( 22380 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22381 "Only package verification agents can read the verifier device identity"); 22382 22383 synchronized (mPackages) { 22384 return mSettings.getVerifierDeviceIdentityLPw(); 22385 } 22386 } 22387 22388 @Override 22389 public void setPermissionEnforced(String permission, boolean enforced) { 22390 // TODO: Now that we no longer change GID for storage, this should to away. 22391 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22392 "setPermissionEnforced"); 22393 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22394 synchronized (mPackages) { 22395 if (mSettings.mReadExternalStorageEnforced == null 22396 || mSettings.mReadExternalStorageEnforced != enforced) { 22397 mSettings.mReadExternalStorageEnforced = enforced; 22398 mSettings.writeLPr(); 22399 } 22400 } 22401 // kill any non-foreground processes so we restart them and 22402 // grant/revoke the GID. 22403 final IActivityManager am = ActivityManager.getService(); 22404 if (am != null) { 22405 final long token = Binder.clearCallingIdentity(); 22406 try { 22407 am.killProcessesBelowForeground("setPermissionEnforcement"); 22408 } catch (RemoteException e) { 22409 } finally { 22410 Binder.restoreCallingIdentity(token); 22411 } 22412 } 22413 } else { 22414 throw new IllegalArgumentException("No selective enforcement for " + permission); 22415 } 22416 } 22417 22418 @Override 22419 @Deprecated 22420 public boolean isPermissionEnforced(String permission) { 22421 return true; 22422 } 22423 22424 @Override 22425 public boolean isStorageLow() { 22426 final long token = Binder.clearCallingIdentity(); 22427 try { 22428 final DeviceStorageMonitorInternal 22429 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22430 if (dsm != null) { 22431 return dsm.isMemoryLow(); 22432 } else { 22433 return false; 22434 } 22435 } finally { 22436 Binder.restoreCallingIdentity(token); 22437 } 22438 } 22439 22440 @Override 22441 public IPackageInstaller getPackageInstaller() { 22442 return mInstallerService; 22443 } 22444 22445 private boolean userNeedsBadging(int userId) { 22446 int index = mUserNeedsBadging.indexOfKey(userId); 22447 if (index < 0) { 22448 final UserInfo userInfo; 22449 final long token = Binder.clearCallingIdentity(); 22450 try { 22451 userInfo = sUserManager.getUserInfo(userId); 22452 } finally { 22453 Binder.restoreCallingIdentity(token); 22454 } 22455 final boolean b; 22456 if (userInfo != null && userInfo.isManagedProfile()) { 22457 b = true; 22458 } else { 22459 b = false; 22460 } 22461 mUserNeedsBadging.put(userId, b); 22462 return b; 22463 } 22464 return mUserNeedsBadging.valueAt(index); 22465 } 22466 22467 @Override 22468 public KeySet getKeySetByAlias(String packageName, String alias) { 22469 if (packageName == null || alias == null) { 22470 return null; 22471 } 22472 synchronized(mPackages) { 22473 final PackageParser.Package pkg = mPackages.get(packageName); 22474 if (pkg == null) { 22475 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22476 throw new IllegalArgumentException("Unknown package: " + packageName); 22477 } 22478 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22479 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22480 } 22481 } 22482 22483 @Override 22484 public KeySet getSigningKeySet(String packageName) { 22485 if (packageName == null) { 22486 return null; 22487 } 22488 synchronized(mPackages) { 22489 final PackageParser.Package pkg = mPackages.get(packageName); 22490 if (pkg == null) { 22491 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22492 throw new IllegalArgumentException("Unknown package: " + packageName); 22493 } 22494 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22495 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22496 throw new SecurityException("May not access signing KeySet of other apps."); 22497 } 22498 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22499 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22500 } 22501 } 22502 22503 @Override 22504 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22505 if (packageName == null || ks == null) { 22506 return false; 22507 } 22508 synchronized(mPackages) { 22509 final PackageParser.Package pkg = mPackages.get(packageName); 22510 if (pkg == null) { 22511 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22512 throw new IllegalArgumentException("Unknown package: " + packageName); 22513 } 22514 IBinder ksh = ks.getToken(); 22515 if (ksh instanceof KeySetHandle) { 22516 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22517 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22518 } 22519 return false; 22520 } 22521 } 22522 22523 @Override 22524 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22525 if (packageName == null || ks == null) { 22526 return false; 22527 } 22528 synchronized(mPackages) { 22529 final PackageParser.Package pkg = mPackages.get(packageName); 22530 if (pkg == null) { 22531 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22532 throw new IllegalArgumentException("Unknown package: " + packageName); 22533 } 22534 IBinder ksh = ks.getToken(); 22535 if (ksh instanceof KeySetHandle) { 22536 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22537 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22538 } 22539 return false; 22540 } 22541 } 22542 22543 private void deletePackageIfUnusedLPr(final String packageName) { 22544 PackageSetting ps = mSettings.mPackages.get(packageName); 22545 if (ps == null) { 22546 return; 22547 } 22548 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22549 // TODO Implement atomic delete if package is unused 22550 // It is currently possible that the package will be deleted even if it is installed 22551 // after this method returns. 22552 mHandler.post(new Runnable() { 22553 public void run() { 22554 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22555 0, PackageManager.DELETE_ALL_USERS); 22556 } 22557 }); 22558 } 22559 } 22560 22561 /** 22562 * Check and throw if the given before/after packages would be considered a 22563 * downgrade. 22564 */ 22565 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22566 throws PackageManagerException { 22567 if (after.versionCode < before.mVersionCode) { 22568 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22569 "Update version code " + after.versionCode + " is older than current " 22570 + before.mVersionCode); 22571 } else if (after.versionCode == before.mVersionCode) { 22572 if (after.baseRevisionCode < before.baseRevisionCode) { 22573 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22574 "Update base revision code " + after.baseRevisionCode 22575 + " is older than current " + before.baseRevisionCode); 22576 } 22577 22578 if (!ArrayUtils.isEmpty(after.splitNames)) { 22579 for (int i = 0; i < after.splitNames.length; i++) { 22580 final String splitName = after.splitNames[i]; 22581 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22582 if (j != -1) { 22583 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22584 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22585 "Update split " + splitName + " revision code " 22586 + after.splitRevisionCodes[i] + " is older than current " 22587 + before.splitRevisionCodes[j]); 22588 } 22589 } 22590 } 22591 } 22592 } 22593 } 22594 22595 private static class MoveCallbacks extends Handler { 22596 private static final int MSG_CREATED = 1; 22597 private static final int MSG_STATUS_CHANGED = 2; 22598 22599 private final RemoteCallbackList<IPackageMoveObserver> 22600 mCallbacks = new RemoteCallbackList<>(); 22601 22602 private final SparseIntArray mLastStatus = new SparseIntArray(); 22603 22604 public MoveCallbacks(Looper looper) { 22605 super(looper); 22606 } 22607 22608 public void register(IPackageMoveObserver callback) { 22609 mCallbacks.register(callback); 22610 } 22611 22612 public void unregister(IPackageMoveObserver callback) { 22613 mCallbacks.unregister(callback); 22614 } 22615 22616 @Override 22617 public void handleMessage(Message msg) { 22618 final SomeArgs args = (SomeArgs) msg.obj; 22619 final int n = mCallbacks.beginBroadcast(); 22620 for (int i = 0; i < n; i++) { 22621 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22622 try { 22623 invokeCallback(callback, msg.what, args); 22624 } catch (RemoteException ignored) { 22625 } 22626 } 22627 mCallbacks.finishBroadcast(); 22628 args.recycle(); 22629 } 22630 22631 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22632 throws RemoteException { 22633 switch (what) { 22634 case MSG_CREATED: { 22635 callback.onCreated(args.argi1, (Bundle) args.arg2); 22636 break; 22637 } 22638 case MSG_STATUS_CHANGED: { 22639 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22640 break; 22641 } 22642 } 22643 } 22644 22645 private void notifyCreated(int moveId, Bundle extras) { 22646 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22647 22648 final SomeArgs args = SomeArgs.obtain(); 22649 args.argi1 = moveId; 22650 args.arg2 = extras; 22651 obtainMessage(MSG_CREATED, args).sendToTarget(); 22652 } 22653 22654 private void notifyStatusChanged(int moveId, int status) { 22655 notifyStatusChanged(moveId, status, -1); 22656 } 22657 22658 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22659 Slog.v(TAG, "Move " + moveId + " status " + status); 22660 22661 final SomeArgs args = SomeArgs.obtain(); 22662 args.argi1 = moveId; 22663 args.argi2 = status; 22664 args.arg3 = estMillis; 22665 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22666 22667 synchronized (mLastStatus) { 22668 mLastStatus.put(moveId, status); 22669 } 22670 } 22671 } 22672 22673 private final static class OnPermissionChangeListeners extends Handler { 22674 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22675 22676 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22677 new RemoteCallbackList<>(); 22678 22679 public OnPermissionChangeListeners(Looper looper) { 22680 super(looper); 22681 } 22682 22683 @Override 22684 public void handleMessage(Message msg) { 22685 switch (msg.what) { 22686 case MSG_ON_PERMISSIONS_CHANGED: { 22687 final int uid = msg.arg1; 22688 handleOnPermissionsChanged(uid); 22689 } break; 22690 } 22691 } 22692 22693 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22694 mPermissionListeners.register(listener); 22695 22696 } 22697 22698 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22699 mPermissionListeners.unregister(listener); 22700 } 22701 22702 public void onPermissionsChanged(int uid) { 22703 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22704 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22705 } 22706 } 22707 22708 private void handleOnPermissionsChanged(int uid) { 22709 final int count = mPermissionListeners.beginBroadcast(); 22710 try { 22711 for (int i = 0; i < count; i++) { 22712 IOnPermissionsChangeListener callback = mPermissionListeners 22713 .getBroadcastItem(i); 22714 try { 22715 callback.onPermissionsChanged(uid); 22716 } catch (RemoteException e) { 22717 Log.e(TAG, "Permission listener is dead", e); 22718 } 22719 } 22720 } finally { 22721 mPermissionListeners.finishBroadcast(); 22722 } 22723 } 22724 } 22725 22726 private class PackageManagerInternalImpl extends PackageManagerInternal { 22727 @Override 22728 public void setLocationPackagesProvider(PackagesProvider provider) { 22729 synchronized (mPackages) { 22730 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22731 } 22732 } 22733 22734 @Override 22735 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22736 synchronized (mPackages) { 22737 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22738 } 22739 } 22740 22741 @Override 22742 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22743 synchronized (mPackages) { 22744 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22745 } 22746 } 22747 22748 @Override 22749 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22750 synchronized (mPackages) { 22751 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22752 } 22753 } 22754 22755 @Override 22756 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22757 synchronized (mPackages) { 22758 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22759 } 22760 } 22761 22762 @Override 22763 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22764 synchronized (mPackages) { 22765 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22766 } 22767 } 22768 22769 @Override 22770 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22771 synchronized (mPackages) { 22772 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22773 packageName, userId); 22774 } 22775 } 22776 22777 @Override 22778 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22779 synchronized (mPackages) { 22780 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22781 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22782 packageName, userId); 22783 } 22784 } 22785 22786 @Override 22787 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22788 synchronized (mPackages) { 22789 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22790 packageName, userId); 22791 } 22792 } 22793 22794 @Override 22795 public void setKeepUninstalledPackages(final List<String> packageList) { 22796 Preconditions.checkNotNull(packageList); 22797 List<String> removedFromList = null; 22798 synchronized (mPackages) { 22799 if (mKeepUninstalledPackages != null) { 22800 final int packagesCount = mKeepUninstalledPackages.size(); 22801 for (int i = 0; i < packagesCount; i++) { 22802 String oldPackage = mKeepUninstalledPackages.get(i); 22803 if (packageList != null && packageList.contains(oldPackage)) { 22804 continue; 22805 } 22806 if (removedFromList == null) { 22807 removedFromList = new ArrayList<>(); 22808 } 22809 removedFromList.add(oldPackage); 22810 } 22811 } 22812 mKeepUninstalledPackages = new ArrayList<>(packageList); 22813 if (removedFromList != null) { 22814 final int removedCount = removedFromList.size(); 22815 for (int i = 0; i < removedCount; i++) { 22816 deletePackageIfUnusedLPr(removedFromList.get(i)); 22817 } 22818 } 22819 } 22820 } 22821 22822 @Override 22823 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22824 synchronized (mPackages) { 22825 // If we do not support permission review, done. 22826 if (!mPermissionReviewRequired) { 22827 return false; 22828 } 22829 22830 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22831 if (packageSetting == null) { 22832 return false; 22833 } 22834 22835 // Permission review applies only to apps not supporting the new permission model. 22836 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22837 return false; 22838 } 22839 22840 // Legacy apps have the permission and get user consent on launch. 22841 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22842 return permissionsState.isPermissionReviewRequired(userId); 22843 } 22844 } 22845 22846 @Override 22847 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22848 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22849 } 22850 22851 @Override 22852 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22853 int userId) { 22854 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22855 } 22856 22857 @Override 22858 public void setDeviceAndProfileOwnerPackages( 22859 int deviceOwnerUserId, String deviceOwnerPackage, 22860 SparseArray<String> profileOwnerPackages) { 22861 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22862 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22863 } 22864 22865 @Override 22866 public boolean isPackageDataProtected(int userId, String packageName) { 22867 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22868 } 22869 22870 @Override 22871 public boolean isPackageEphemeral(int userId, String packageName) { 22872 synchronized (mPackages) { 22873 final PackageSetting ps = mSettings.mPackages.get(packageName); 22874 return ps != null ? ps.getInstantApp(userId) : false; 22875 } 22876 } 22877 22878 @Override 22879 public boolean wasPackageEverLaunched(String packageName, int userId) { 22880 synchronized (mPackages) { 22881 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22882 } 22883 } 22884 22885 @Override 22886 public void grantRuntimePermission(String packageName, String name, int userId, 22887 boolean overridePolicy) { 22888 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22889 overridePolicy); 22890 } 22891 22892 @Override 22893 public void revokeRuntimePermission(String packageName, String name, int userId, 22894 boolean overridePolicy) { 22895 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22896 overridePolicy); 22897 } 22898 22899 @Override 22900 public String getNameForUid(int uid) { 22901 return PackageManagerService.this.getNameForUid(uid); 22902 } 22903 22904 @Override 22905 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 22906 Intent origIntent, String resolvedType, String callingPackage, int userId) { 22907 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 22908 responseObj, origIntent, resolvedType, callingPackage, userId); 22909 } 22910 22911 @Override 22912 public void grantEphemeralAccess(int userId, Intent intent, 22913 int targetAppId, int ephemeralAppId) { 22914 synchronized (mPackages) { 22915 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 22916 targetAppId, ephemeralAppId); 22917 } 22918 } 22919 22920 @Override 22921 public void pruneInstantApps() { 22922 synchronized (mPackages) { 22923 mInstantAppRegistry.pruneInstantAppsLPw(); 22924 } 22925 } 22926 22927 @Override 22928 public String getSetupWizardPackageName() { 22929 return mSetupWizardPackage; 22930 } 22931 22932 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22933 if (policy != null) { 22934 mExternalSourcesPolicy = policy; 22935 } 22936 } 22937 22938 @Override 22939 public boolean isPackagePersistent(String packageName) { 22940 synchronized (mPackages) { 22941 PackageParser.Package pkg = mPackages.get(packageName); 22942 return pkg != null 22943 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 22944 | ApplicationInfo.FLAG_PERSISTENT)) == 22945 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 22946 : false; 22947 } 22948 } 22949 22950 @Override 22951 public List<PackageInfo> getOverlayPackages(int userId) { 22952 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 22953 synchronized (mPackages) { 22954 for (PackageParser.Package p : mPackages.values()) { 22955 if (p.mOverlayTarget != null) { 22956 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 22957 if (pkg != null) { 22958 overlayPackages.add(pkg); 22959 } 22960 } 22961 } 22962 } 22963 return overlayPackages; 22964 } 22965 22966 @Override 22967 public List<String> getTargetPackageNames(int userId) { 22968 List<String> targetPackages = new ArrayList<>(); 22969 synchronized (mPackages) { 22970 for (PackageParser.Package p : mPackages.values()) { 22971 if (p.mOverlayTarget == null) { 22972 targetPackages.add(p.packageName); 22973 } 22974 } 22975 } 22976 return targetPackages; 22977 } 22978 22979 22980 @Override 22981 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 22982 @Nullable List<String> overlayPackageNames) { 22983 synchronized (mPackages) { 22984 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 22985 Slog.e(TAG, "failed to find package " + targetPackageName); 22986 return false; 22987 } 22988 22989 ArrayList<String> paths = null; 22990 if (overlayPackageNames != null) { 22991 final int N = overlayPackageNames.size(); 22992 paths = new ArrayList<String>(N); 22993 for (int i = 0; i < N; i++) { 22994 final String packageName = overlayPackageNames.get(i); 22995 final PackageParser.Package pkg = mPackages.get(packageName); 22996 if (pkg == null) { 22997 Slog.e(TAG, "failed to find package " + packageName); 22998 return false; 22999 } 23000 paths.add(pkg.baseCodePath); 23001 } 23002 } 23003 23004 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23005 mEnabledOverlayPaths.get(userId); 23006 if (userSpecificOverlays == null) { 23007 userSpecificOverlays = new ArrayMap<String, ArrayList<String>>(); 23008 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23009 } 23010 23011 if (paths != null && paths.size() > 0) { 23012 userSpecificOverlays.put(targetPackageName, paths); 23013 } else { 23014 userSpecificOverlays.remove(targetPackageName); 23015 } 23016 return true; 23017 } 23018 } 23019 } 23020 23021 @Override 23022 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23023 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23024 synchronized (mPackages) { 23025 final long identity = Binder.clearCallingIdentity(); 23026 try { 23027 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23028 packageNames, userId); 23029 } finally { 23030 Binder.restoreCallingIdentity(identity); 23031 } 23032 } 23033 } 23034 23035 @Override 23036 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23037 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23038 synchronized (mPackages) { 23039 final long identity = Binder.clearCallingIdentity(); 23040 try { 23041 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23042 packageNames, userId); 23043 } finally { 23044 Binder.restoreCallingIdentity(identity); 23045 } 23046 } 23047 } 23048 23049 private static void enforceSystemOrPhoneCaller(String tag) { 23050 int callingUid = Binder.getCallingUid(); 23051 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23052 throw new SecurityException( 23053 "Cannot call " + tag + " from UID " + callingUid); 23054 } 23055 } 23056 23057 boolean isHistoricalPackageUsageAvailable() { 23058 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23059 } 23060 23061 /** 23062 * Return a <b>copy</b> of the collection of packages known to the package manager. 23063 * @return A copy of the values of mPackages. 23064 */ 23065 Collection<PackageParser.Package> getPackages() { 23066 synchronized (mPackages) { 23067 return new ArrayList<>(mPackages.values()); 23068 } 23069 } 23070 23071 /** 23072 * Logs process start information (including base APK hash) to the security log. 23073 * @hide 23074 */ 23075 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23076 String apkFile, int pid) { 23077 if (!SecurityLog.isLoggingEnabled()) { 23078 return; 23079 } 23080 Bundle data = new Bundle(); 23081 data.putLong("startTimestamp", System.currentTimeMillis()); 23082 data.putString("processName", processName); 23083 data.putInt("uid", uid); 23084 data.putString("seinfo", seinfo); 23085 data.putString("apkFile", apkFile); 23086 data.putInt("pid", pid); 23087 Message msg = mProcessLoggingHandler.obtainMessage( 23088 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23089 msg.setData(data); 23090 mProcessLoggingHandler.sendMessage(msg); 23091 } 23092 23093 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23094 return mCompilerStats.getPackageStats(pkgName); 23095 } 23096 23097 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23098 return getOrCreateCompilerPackageStats(pkg.packageName); 23099 } 23100 23101 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23102 return mCompilerStats.getOrCreatePackageStats(pkgName); 23103 } 23104 23105 public void deleteCompilerPackageStats(String pkgName) { 23106 mCompilerStats.deletePackageStats(pkgName); 23107 } 23108 23109 @Override 23110 public int getInstallReason(String packageName, int userId) { 23111 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23112 true /* requireFullPermission */, false /* checkShell */, 23113 "get install reason"); 23114 synchronized (mPackages) { 23115 final PackageSetting ps = mSettings.mPackages.get(packageName); 23116 if (ps != null) { 23117 return ps.getInstallReason(userId); 23118 } 23119 } 23120 return PackageManager.INSTALL_REASON_UNKNOWN; 23121 } 23122 23123 @Override 23124 public boolean canRequestPackageInstalls(String packageName, int userId) { 23125 int callingUid = Binder.getCallingUid(); 23126 int uid = getPackageUid(packageName, 0, userId); 23127 if (callingUid != uid && callingUid != Process.ROOT_UID 23128 && callingUid != Process.SYSTEM_UID) { 23129 throw new SecurityException( 23130 "Caller uid " + callingUid + " does not own package " + packageName); 23131 } 23132 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23133 if (info == null) { 23134 return false; 23135 } 23136 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23137 throw new UnsupportedOperationException( 23138 "Operation only supported on apps targeting Android O or higher"); 23139 } 23140 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23141 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23142 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23143 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23144 } 23145 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23146 return false; 23147 } 23148 if (mExternalSourcesPolicy != null) { 23149 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23150 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23151 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23152 } 23153 } 23154 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23155 } 23156} 23157