PackageManagerService.java revision 4d1de7da79010be3e1f0eb85aa50b6002a8241fd
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 // Tracks available target package names -> overlay package paths. 665 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 666 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 667 668 /** 669 * Tracks new system packages [received in an OTA] that we expect to 670 * find updated user-installed versions. Keys are package name, values 671 * are package location. 672 */ 673 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 674 /** 675 * Tracks high priority intent filters for protected actions. During boot, certain 676 * filter actions are protected and should never be allowed to have a high priority 677 * intent filter for them. However, there is one, and only one exception -- the 678 * setup wizard. It must be able to define a high priority intent filter for these 679 * actions to ensure there are no escapes from the wizard. We need to delay processing 680 * of these during boot as we need to look at all of the system packages in order 681 * to know which component is the setup wizard. 682 */ 683 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 684 /** 685 * Whether or not processing protected filters should be deferred. 686 */ 687 private boolean mDeferProtectedFilters = true; 688 689 /** 690 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 691 */ 692 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 693 /** 694 * Whether or not system app permissions should be promoted from install to runtime. 695 */ 696 boolean mPromoteSystemApps; 697 698 @GuardedBy("mPackages") 699 final Settings mSettings; 700 701 /** 702 * Set of package names that are currently "frozen", which means active 703 * surgery is being done on the code/data for that package. The platform 704 * will refuse to launch frozen packages to avoid race conditions. 705 * 706 * @see PackageFreezer 707 */ 708 @GuardedBy("mPackages") 709 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 710 711 final ProtectedPackages mProtectedPackages; 712 713 boolean mFirstBoot; 714 715 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 716 717 // System configuration read by SystemConfig. 718 final int[] mGlobalGids; 719 final SparseArray<ArraySet<String>> mSystemPermissions; 720 @GuardedBy("mAvailableFeatures") 721 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 722 723 // If mac_permissions.xml was found for seinfo labeling. 724 boolean mFoundPolicyFile; 725 726 private final InstantAppRegistry mInstantAppRegistry; 727 728 @GuardedBy("mPackages") 729 int mChangedPackagesSequenceNumber; 730 /** 731 * List of changed [installed, removed or updated] packages. 732 * mapping from user id -> sequence number -> package name 733 */ 734 @GuardedBy("mPackages") 735 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 736 /** 737 * The sequence number of the last change to a package. 738 * mapping from user id -> package name -> sequence number 739 */ 740 @GuardedBy("mPackages") 741 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 742 743 public static final class SharedLibraryEntry { 744 public final String path; 745 public final String apk; 746 public final SharedLibraryInfo info; 747 748 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 749 String declaringPackageName, int declaringPackageVersionCode) { 750 path = _path; 751 apk = _apk; 752 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 753 declaringPackageName, declaringPackageVersionCode), null); 754 } 755 } 756 757 // Currently known shared libraries. 758 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 759 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 760 new ArrayMap<>(); 761 762 // All available activities, for your resolving pleasure. 763 final ActivityIntentResolver mActivities = 764 new ActivityIntentResolver(); 765 766 // All available receivers, for your resolving pleasure. 767 final ActivityIntentResolver mReceivers = 768 new ActivityIntentResolver(); 769 770 // All available services, for your resolving pleasure. 771 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 772 773 // All available providers, for your resolving pleasure. 774 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 775 776 // Mapping from provider base names (first directory in content URI codePath) 777 // to the provider information. 778 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 779 new ArrayMap<String, PackageParser.Provider>(); 780 781 // Mapping from instrumentation class names to info about them. 782 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 783 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 784 785 // Mapping from permission names to info about them. 786 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 787 new ArrayMap<String, PackageParser.PermissionGroup>(); 788 789 // Packages whose data we have transfered into another package, thus 790 // should no longer exist. 791 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 792 793 // Broadcast actions that are only available to the system. 794 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 795 796 /** List of packages waiting for verification. */ 797 final SparseArray<PackageVerificationState> mPendingVerification 798 = new SparseArray<PackageVerificationState>(); 799 800 /** Set of packages associated with each app op permission. */ 801 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 802 803 final PackageInstallerService mInstallerService; 804 805 private final PackageDexOptimizer mPackageDexOptimizer; 806 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 807 // is used by other apps). 808 private final DexManager mDexManager; 809 810 private AtomicInteger mNextMoveId = new AtomicInteger(); 811 private final MoveCallbacks mMoveCallbacks; 812 813 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 814 815 // Cache of users who need badging. 816 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 817 818 /** Token for keys in mPendingVerification. */ 819 private int mPendingVerificationToken = 0; 820 821 volatile boolean mSystemReady; 822 volatile boolean mSafeMode; 823 volatile boolean mHasSystemUidErrors; 824 825 ApplicationInfo mAndroidApplication; 826 final ActivityInfo mResolveActivity = new ActivityInfo(); 827 final ResolveInfo mResolveInfo = new ResolveInfo(); 828 ComponentName mResolveComponentName; 829 PackageParser.Package mPlatformPackage; 830 ComponentName mCustomResolverComponentName; 831 832 boolean mResolverReplaced = false; 833 834 private final @Nullable ComponentName mIntentFilterVerifierComponent; 835 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 836 837 private int mIntentFilterVerificationToken = 0; 838 839 /** The service connection to the ephemeral resolver */ 840 final EphemeralResolverConnection mInstantAppResolverConnection; 841 842 /** Component used to install ephemeral applications */ 843 ComponentName mInstantAppInstallerComponent; 844 final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo(); 845 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 846 847 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 848 = new SparseArray<IntentFilterVerificationState>(); 849 850 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 851 852 // List of packages names to keep cached, even if they are uninstalled for all users 853 private List<String> mKeepUninstalledPackages; 854 855 private UserManagerInternal mUserManagerInternal; 856 857 private DeviceIdleController.LocalService mDeviceIdleController; 858 859 private File mCacheDir; 860 861 private ArraySet<String> mPrivappPermissionsViolations; 862 863 private Future<?> mPrepareAppDataFuture; 864 865 private static class IFVerificationParams { 866 PackageParser.Package pkg; 867 boolean replacing; 868 int userId; 869 int verifierUid; 870 871 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 872 int _userId, int _verifierUid) { 873 pkg = _pkg; 874 replacing = _replacing; 875 userId = _userId; 876 replacing = _replacing; 877 verifierUid = _verifierUid; 878 } 879 } 880 881 private interface IntentFilterVerifier<T extends IntentFilter> { 882 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 883 T filter, String packageName); 884 void startVerifications(int userId); 885 void receiveVerificationResponse(int verificationId); 886 } 887 888 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 889 private Context mContext; 890 private ComponentName mIntentFilterVerifierComponent; 891 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 892 893 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 894 mContext = context; 895 mIntentFilterVerifierComponent = verifierComponent; 896 } 897 898 private String getDefaultScheme() { 899 return IntentFilter.SCHEME_HTTPS; 900 } 901 902 @Override 903 public void startVerifications(int userId) { 904 // Launch verifications requests 905 int count = mCurrentIntentFilterVerifications.size(); 906 for (int n=0; n<count; n++) { 907 int verificationId = mCurrentIntentFilterVerifications.get(n); 908 final IntentFilterVerificationState ivs = 909 mIntentFilterVerificationStates.get(verificationId); 910 911 String packageName = ivs.getPackageName(); 912 913 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 914 final int filterCount = filters.size(); 915 ArraySet<String> domainsSet = new ArraySet<>(); 916 for (int m=0; m<filterCount; m++) { 917 PackageParser.ActivityIntentInfo filter = filters.get(m); 918 domainsSet.addAll(filter.getHostsList()); 919 } 920 synchronized (mPackages) { 921 if (mSettings.createIntentFilterVerificationIfNeededLPw( 922 packageName, domainsSet) != null) { 923 scheduleWriteSettingsLocked(); 924 } 925 } 926 sendVerificationRequest(userId, verificationId, ivs); 927 } 928 mCurrentIntentFilterVerifications.clear(); 929 } 930 931 private void sendVerificationRequest(int userId, int verificationId, 932 IntentFilterVerificationState ivs) { 933 934 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 935 verificationIntent.putExtra( 936 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 937 verificationId); 938 verificationIntent.putExtra( 939 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 940 getDefaultScheme()); 941 verificationIntent.putExtra( 942 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 943 ivs.getHostsString()); 944 verificationIntent.putExtra( 945 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 946 ivs.getPackageName()); 947 verificationIntent.setComponent(mIntentFilterVerifierComponent); 948 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 949 950 UserHandle user = new UserHandle(userId); 951 mContext.sendBroadcastAsUser(verificationIntent, user); 952 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 953 "Sending IntentFilter verification broadcast"); 954 } 955 956 public void receiveVerificationResponse(int verificationId) { 957 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 958 959 final boolean verified = ivs.isVerified(); 960 961 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 962 final int count = filters.size(); 963 if (DEBUG_DOMAIN_VERIFICATION) { 964 Slog.i(TAG, "Received verification response " + verificationId 965 + " for " + count + " filters, verified=" + verified); 966 } 967 for (int n=0; n<count; n++) { 968 PackageParser.ActivityIntentInfo filter = filters.get(n); 969 filter.setVerified(verified); 970 971 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 972 + " verified with result:" + verified + " and hosts:" 973 + ivs.getHostsString()); 974 } 975 976 mIntentFilterVerificationStates.remove(verificationId); 977 978 final String packageName = ivs.getPackageName(); 979 IntentFilterVerificationInfo ivi = null; 980 981 synchronized (mPackages) { 982 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 983 } 984 if (ivi == null) { 985 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 986 + verificationId + " packageName:" + packageName); 987 return; 988 } 989 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 990 "Updating IntentFilterVerificationInfo for package " + packageName 991 +" verificationId:" + verificationId); 992 993 synchronized (mPackages) { 994 if (verified) { 995 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 996 } else { 997 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 998 } 999 scheduleWriteSettingsLocked(); 1000 1001 final int userId = ivs.getUserId(); 1002 if (userId != UserHandle.USER_ALL) { 1003 final int userStatus = 1004 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1005 1006 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1007 boolean needUpdate = false; 1008 1009 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1010 // already been set by the User thru the Disambiguation dialog 1011 switch (userStatus) { 1012 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1013 if (verified) { 1014 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1015 } else { 1016 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1017 } 1018 needUpdate = true; 1019 break; 1020 1021 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1022 if (verified) { 1023 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1024 needUpdate = true; 1025 } 1026 break; 1027 1028 default: 1029 // Nothing to do 1030 } 1031 1032 if (needUpdate) { 1033 mSettings.updateIntentFilterVerificationStatusLPw( 1034 packageName, updatedStatus, userId); 1035 scheduleWritePackageRestrictionsLocked(userId); 1036 } 1037 } 1038 } 1039 } 1040 1041 @Override 1042 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1043 ActivityIntentInfo filter, String packageName) { 1044 if (!hasValidDomains(filter)) { 1045 return false; 1046 } 1047 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1048 if (ivs == null) { 1049 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1050 packageName); 1051 } 1052 if (DEBUG_DOMAIN_VERIFICATION) { 1053 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1054 } 1055 ivs.addFilter(filter); 1056 return true; 1057 } 1058 1059 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1060 int userId, int verificationId, String packageName) { 1061 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1062 verifierUid, userId, packageName); 1063 ivs.setPendingState(); 1064 synchronized (mPackages) { 1065 mIntentFilterVerificationStates.append(verificationId, ivs); 1066 mCurrentIntentFilterVerifications.add(verificationId); 1067 } 1068 return ivs; 1069 } 1070 } 1071 1072 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1073 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1074 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1075 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1076 } 1077 1078 // Set of pending broadcasts for aggregating enable/disable of components. 1079 static class PendingPackageBroadcasts { 1080 // for each user id, a map of <package name -> components within that package> 1081 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1082 1083 public PendingPackageBroadcasts() { 1084 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1085 } 1086 1087 public ArrayList<String> get(int userId, String packageName) { 1088 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1089 return packages.get(packageName); 1090 } 1091 1092 public void put(int userId, String packageName, ArrayList<String> components) { 1093 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1094 packages.put(packageName, components); 1095 } 1096 1097 public void remove(int userId, String packageName) { 1098 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1099 if (packages != null) { 1100 packages.remove(packageName); 1101 } 1102 } 1103 1104 public void remove(int userId) { 1105 mUidMap.remove(userId); 1106 } 1107 1108 public int userIdCount() { 1109 return mUidMap.size(); 1110 } 1111 1112 public int userIdAt(int n) { 1113 return mUidMap.keyAt(n); 1114 } 1115 1116 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1117 return mUidMap.get(userId); 1118 } 1119 1120 public int size() { 1121 // total number of pending broadcast entries across all userIds 1122 int num = 0; 1123 for (int i = 0; i< mUidMap.size(); i++) { 1124 num += mUidMap.valueAt(i).size(); 1125 } 1126 return num; 1127 } 1128 1129 public void clear() { 1130 mUidMap.clear(); 1131 } 1132 1133 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1134 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1135 if (map == null) { 1136 map = new ArrayMap<String, ArrayList<String>>(); 1137 mUidMap.put(userId, map); 1138 } 1139 return map; 1140 } 1141 } 1142 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1143 1144 // Service Connection to remote media container service to copy 1145 // package uri's from external media onto secure containers 1146 // or internal storage. 1147 private IMediaContainerService mContainerService = null; 1148 1149 static final int SEND_PENDING_BROADCAST = 1; 1150 static final int MCS_BOUND = 3; 1151 static final int END_COPY = 4; 1152 static final int INIT_COPY = 5; 1153 static final int MCS_UNBIND = 6; 1154 static final int START_CLEANING_PACKAGE = 7; 1155 static final int FIND_INSTALL_LOC = 8; 1156 static final int POST_INSTALL = 9; 1157 static final int MCS_RECONNECT = 10; 1158 static final int MCS_GIVE_UP = 11; 1159 static final int UPDATED_MEDIA_STATUS = 12; 1160 static final int WRITE_SETTINGS = 13; 1161 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1162 static final int PACKAGE_VERIFIED = 15; 1163 static final int CHECK_PENDING_VERIFICATION = 16; 1164 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1165 static final int INTENT_FILTER_VERIFIED = 18; 1166 static final int WRITE_PACKAGE_LIST = 19; 1167 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1168 1169 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1170 1171 // Delay time in millisecs 1172 static final int BROADCAST_DELAY = 10 * 1000; 1173 1174 static UserManagerService sUserManager; 1175 1176 // Stores a list of users whose package restrictions file needs to be updated 1177 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1178 1179 final private DefaultContainerConnection mDefContainerConn = 1180 new DefaultContainerConnection(); 1181 class DefaultContainerConnection implements ServiceConnection { 1182 public void onServiceConnected(ComponentName name, IBinder service) { 1183 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1184 final IMediaContainerService imcs = IMediaContainerService.Stub 1185 .asInterface(Binder.allowBlocking(service)); 1186 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1187 } 1188 1189 public void onServiceDisconnected(ComponentName name) { 1190 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1191 } 1192 } 1193 1194 // Recordkeeping of restore-after-install operations that are currently in flight 1195 // between the Package Manager and the Backup Manager 1196 static class PostInstallData { 1197 public InstallArgs args; 1198 public PackageInstalledInfo res; 1199 1200 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1201 args = _a; 1202 res = _r; 1203 } 1204 } 1205 1206 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1207 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1208 1209 // XML tags for backup/restore of various bits of state 1210 private static final String TAG_PREFERRED_BACKUP = "pa"; 1211 private static final String TAG_DEFAULT_APPS = "da"; 1212 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1213 1214 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1215 private static final String TAG_ALL_GRANTS = "rt-grants"; 1216 private static final String TAG_GRANT = "grant"; 1217 private static final String ATTR_PACKAGE_NAME = "pkg"; 1218 1219 private static final String TAG_PERMISSION = "perm"; 1220 private static final String ATTR_PERMISSION_NAME = "name"; 1221 private static final String ATTR_IS_GRANTED = "g"; 1222 private static final String ATTR_USER_SET = "set"; 1223 private static final String ATTR_USER_FIXED = "fixed"; 1224 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1225 1226 // System/policy permission grants are not backed up 1227 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1228 FLAG_PERMISSION_POLICY_FIXED 1229 | FLAG_PERMISSION_SYSTEM_FIXED 1230 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1231 1232 // And we back up these user-adjusted states 1233 private static final int USER_RUNTIME_GRANT_MASK = 1234 FLAG_PERMISSION_USER_SET 1235 | FLAG_PERMISSION_USER_FIXED 1236 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1237 1238 final @Nullable String mRequiredVerifierPackage; 1239 final @NonNull String mRequiredInstallerPackage; 1240 final @NonNull String mRequiredUninstallerPackage; 1241 final @Nullable String mSetupWizardPackage; 1242 final @Nullable String mStorageManagerPackage; 1243 final @NonNull String mServicesSystemSharedLibraryPackageName; 1244 final @NonNull String mSharedSystemSharedLibraryPackageName; 1245 1246 final boolean mPermissionReviewRequired; 1247 1248 private final PackageUsage mPackageUsage = new PackageUsage(); 1249 private final CompilerStats mCompilerStats = new CompilerStats(); 1250 1251 class PackageHandler extends Handler { 1252 private boolean mBound = false; 1253 final ArrayList<HandlerParams> mPendingInstalls = 1254 new ArrayList<HandlerParams>(); 1255 1256 private boolean connectToService() { 1257 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1258 " DefaultContainerService"); 1259 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1261 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1262 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1264 mBound = true; 1265 return true; 1266 } 1267 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1268 return false; 1269 } 1270 1271 private void disconnectService() { 1272 mContainerService = null; 1273 mBound = false; 1274 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1275 mContext.unbindService(mDefContainerConn); 1276 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1277 } 1278 1279 PackageHandler(Looper looper) { 1280 super(looper); 1281 } 1282 1283 public void handleMessage(Message msg) { 1284 try { 1285 doHandleMessage(msg); 1286 } finally { 1287 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1288 } 1289 } 1290 1291 void doHandleMessage(Message msg) { 1292 switch (msg.what) { 1293 case INIT_COPY: { 1294 HandlerParams params = (HandlerParams) msg.obj; 1295 int idx = mPendingInstalls.size(); 1296 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1297 // If a bind was already initiated we dont really 1298 // need to do anything. The pending install 1299 // will be processed later on. 1300 if (!mBound) { 1301 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1302 System.identityHashCode(mHandler)); 1303 // If this is the only one pending we might 1304 // have to bind to the service again. 1305 if (!connectToService()) { 1306 Slog.e(TAG, "Failed to bind to media container service"); 1307 params.serviceError(); 1308 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1309 System.identityHashCode(mHandler)); 1310 if (params.traceMethod != null) { 1311 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1312 params.traceCookie); 1313 } 1314 return; 1315 } else { 1316 // Once we bind to the service, the first 1317 // pending request will be processed. 1318 mPendingInstalls.add(idx, params); 1319 } 1320 } else { 1321 mPendingInstalls.add(idx, params); 1322 // Already bound to the service. Just make 1323 // sure we trigger off processing the first request. 1324 if (idx == 0) { 1325 mHandler.sendEmptyMessage(MCS_BOUND); 1326 } 1327 } 1328 break; 1329 } 1330 case MCS_BOUND: { 1331 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1332 if (msg.obj != null) { 1333 mContainerService = (IMediaContainerService) msg.obj; 1334 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1335 System.identityHashCode(mHandler)); 1336 } 1337 if (mContainerService == null) { 1338 if (!mBound) { 1339 // Something seriously wrong since we are not bound and we are not 1340 // waiting for connection. Bail out. 1341 Slog.e(TAG, "Cannot bind to media container service"); 1342 for (HandlerParams params : mPendingInstalls) { 1343 // Indicate service bind error 1344 params.serviceError(); 1345 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1346 System.identityHashCode(params)); 1347 if (params.traceMethod != null) { 1348 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1349 params.traceMethod, params.traceCookie); 1350 } 1351 return; 1352 } 1353 mPendingInstalls.clear(); 1354 } else { 1355 Slog.w(TAG, "Waiting to connect to media container service"); 1356 } 1357 } else if (mPendingInstalls.size() > 0) { 1358 HandlerParams params = mPendingInstalls.get(0); 1359 if (params != null) { 1360 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1361 System.identityHashCode(params)); 1362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1363 if (params.startCopy()) { 1364 // We are done... look for more work or to 1365 // go idle. 1366 if (DEBUG_SD_INSTALL) Log.i(TAG, 1367 "Checking for more work or unbind..."); 1368 // Delete pending install 1369 if (mPendingInstalls.size() > 0) { 1370 mPendingInstalls.remove(0); 1371 } 1372 if (mPendingInstalls.size() == 0) { 1373 if (mBound) { 1374 if (DEBUG_SD_INSTALL) Log.i(TAG, 1375 "Posting delayed MCS_UNBIND"); 1376 removeMessages(MCS_UNBIND); 1377 Message ubmsg = obtainMessage(MCS_UNBIND); 1378 // Unbind after a little delay, to avoid 1379 // continual thrashing. 1380 sendMessageDelayed(ubmsg, 10000); 1381 } 1382 } else { 1383 // There are more pending requests in queue. 1384 // Just post MCS_BOUND message to trigger processing 1385 // of next pending install. 1386 if (DEBUG_SD_INSTALL) Log.i(TAG, 1387 "Posting MCS_BOUND for next work"); 1388 mHandler.sendEmptyMessage(MCS_BOUND); 1389 } 1390 } 1391 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1392 } 1393 } else { 1394 // Should never happen ideally. 1395 Slog.w(TAG, "Empty queue"); 1396 } 1397 break; 1398 } 1399 case MCS_RECONNECT: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1401 if (mPendingInstalls.size() > 0) { 1402 if (mBound) { 1403 disconnectService(); 1404 } 1405 if (!connectToService()) { 1406 Slog.e(TAG, "Failed to bind to media container service"); 1407 for (HandlerParams params : mPendingInstalls) { 1408 // Indicate service bind error 1409 params.serviceError(); 1410 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1411 System.identityHashCode(params)); 1412 } 1413 mPendingInstalls.clear(); 1414 } 1415 } 1416 break; 1417 } 1418 case MCS_UNBIND: { 1419 // If there is no actual work left, then time to unbind. 1420 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1421 1422 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1423 if (mBound) { 1424 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1425 1426 disconnectService(); 1427 } 1428 } else if (mPendingInstalls.size() > 0) { 1429 // There are more pending requests in queue. 1430 // Just post MCS_BOUND message to trigger processing 1431 // of next pending install. 1432 mHandler.sendEmptyMessage(MCS_BOUND); 1433 } 1434 1435 break; 1436 } 1437 case MCS_GIVE_UP: { 1438 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1439 HandlerParams params = mPendingInstalls.remove(0); 1440 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1441 System.identityHashCode(params)); 1442 break; 1443 } 1444 case SEND_PENDING_BROADCAST: { 1445 String packages[]; 1446 ArrayList<String> components[]; 1447 int size = 0; 1448 int uids[]; 1449 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1450 synchronized (mPackages) { 1451 if (mPendingBroadcasts == null) { 1452 return; 1453 } 1454 size = mPendingBroadcasts.size(); 1455 if (size <= 0) { 1456 // Nothing to be done. Just return 1457 return; 1458 } 1459 packages = new String[size]; 1460 components = new ArrayList[size]; 1461 uids = new int[size]; 1462 int i = 0; // filling out the above arrays 1463 1464 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1465 int packageUserId = mPendingBroadcasts.userIdAt(n); 1466 Iterator<Map.Entry<String, ArrayList<String>>> it 1467 = mPendingBroadcasts.packagesForUserId(packageUserId) 1468 .entrySet().iterator(); 1469 while (it.hasNext() && i < size) { 1470 Map.Entry<String, ArrayList<String>> ent = it.next(); 1471 packages[i] = ent.getKey(); 1472 components[i] = ent.getValue(); 1473 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1474 uids[i] = (ps != null) 1475 ? UserHandle.getUid(packageUserId, ps.appId) 1476 : -1; 1477 i++; 1478 } 1479 } 1480 size = i; 1481 mPendingBroadcasts.clear(); 1482 } 1483 // Send broadcasts 1484 for (int i = 0; i < size; i++) { 1485 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1486 } 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1488 break; 1489 } 1490 case START_CLEANING_PACKAGE: { 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1492 final String packageName = (String)msg.obj; 1493 final int userId = msg.arg1; 1494 final boolean andCode = msg.arg2 != 0; 1495 synchronized (mPackages) { 1496 if (userId == UserHandle.USER_ALL) { 1497 int[] users = sUserManager.getUserIds(); 1498 for (int user : users) { 1499 mSettings.addPackageToCleanLPw( 1500 new PackageCleanItem(user, packageName, andCode)); 1501 } 1502 } else { 1503 mSettings.addPackageToCleanLPw( 1504 new PackageCleanItem(userId, packageName, andCode)); 1505 } 1506 } 1507 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1508 startCleaningPackages(); 1509 } break; 1510 case POST_INSTALL: { 1511 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1512 1513 PostInstallData data = mRunningInstalls.get(msg.arg1); 1514 final boolean didRestore = (msg.arg2 != 0); 1515 mRunningInstalls.delete(msg.arg1); 1516 1517 if (data != null) { 1518 InstallArgs args = data.args; 1519 PackageInstalledInfo parentRes = data.res; 1520 1521 final boolean grantPermissions = (args.installFlags 1522 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1523 final boolean killApp = (args.installFlags 1524 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1525 final String[] grantedPermissions = args.installGrantPermissions; 1526 1527 // Handle the parent package 1528 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1529 grantedPermissions, didRestore, args.installerPackageName, 1530 args.observer); 1531 1532 // Handle the child packages 1533 final int childCount = (parentRes.addedChildPackages != null) 1534 ? parentRes.addedChildPackages.size() : 0; 1535 for (int i = 0; i < childCount; i++) { 1536 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1537 handlePackagePostInstall(childRes, grantPermissions, killApp, 1538 grantedPermissions, false, args.installerPackageName, 1539 args.observer); 1540 } 1541 1542 // Log tracing if needed 1543 if (args.traceMethod != null) { 1544 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1545 args.traceCookie); 1546 } 1547 } else { 1548 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1549 } 1550 1551 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1552 } break; 1553 case UPDATED_MEDIA_STATUS: { 1554 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1555 boolean reportStatus = msg.arg1 == 1; 1556 boolean doGc = msg.arg2 == 1; 1557 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1558 if (doGc) { 1559 // Force a gc to clear up stale containers. 1560 Runtime.getRuntime().gc(); 1561 } 1562 if (msg.obj != null) { 1563 @SuppressWarnings("unchecked") 1564 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1565 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1566 // Unload containers 1567 unloadAllContainers(args); 1568 } 1569 if (reportStatus) { 1570 try { 1571 if (DEBUG_SD_INSTALL) Log.i(TAG, 1572 "Invoking StorageManagerService call back"); 1573 PackageHelper.getStorageManager().finishMediaUpdate(); 1574 } catch (RemoteException e) { 1575 Log.e(TAG, "StorageManagerService not running?"); 1576 } 1577 } 1578 } break; 1579 case WRITE_SETTINGS: { 1580 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1581 synchronized (mPackages) { 1582 removeMessages(WRITE_SETTINGS); 1583 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1584 mSettings.writeLPr(); 1585 mDirtyUsers.clear(); 1586 } 1587 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1588 } break; 1589 case WRITE_PACKAGE_RESTRICTIONS: { 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1591 synchronized (mPackages) { 1592 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1593 for (int userId : mDirtyUsers) { 1594 mSettings.writePackageRestrictionsLPr(userId); 1595 } 1596 mDirtyUsers.clear(); 1597 } 1598 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1599 } break; 1600 case WRITE_PACKAGE_LIST: { 1601 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1602 synchronized (mPackages) { 1603 removeMessages(WRITE_PACKAGE_LIST); 1604 mSettings.writePackageListLPr(msg.arg1); 1605 } 1606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1607 } break; 1608 case CHECK_PENDING_VERIFICATION: { 1609 final int verificationId = msg.arg1; 1610 final PackageVerificationState state = mPendingVerification.get(verificationId); 1611 1612 if ((state != null) && !state.timeoutExtended()) { 1613 final InstallArgs args = state.getInstallArgs(); 1614 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1615 1616 Slog.i(TAG, "Verification timed out for " + originUri); 1617 mPendingVerification.remove(verificationId); 1618 1619 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1620 1621 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1622 Slog.i(TAG, "Continuing with installation of " + originUri); 1623 state.setVerifierResponse(Binder.getCallingUid(), 1624 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1625 broadcastPackageVerified(verificationId, originUri, 1626 PackageManager.VERIFICATION_ALLOW, 1627 state.getInstallArgs().getUser()); 1628 try { 1629 ret = args.copyApk(mContainerService, true); 1630 } catch (RemoteException e) { 1631 Slog.e(TAG, "Could not contact the ContainerService"); 1632 } 1633 } else { 1634 broadcastPackageVerified(verificationId, originUri, 1635 PackageManager.VERIFICATION_REJECT, 1636 state.getInstallArgs().getUser()); 1637 } 1638 1639 Trace.asyncTraceEnd( 1640 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1641 1642 processPendingInstall(args, ret); 1643 mHandler.sendEmptyMessage(MCS_UNBIND); 1644 } 1645 break; 1646 } 1647 case PACKAGE_VERIFIED: { 1648 final int verificationId = msg.arg1; 1649 1650 final PackageVerificationState state = mPendingVerification.get(verificationId); 1651 if (state == null) { 1652 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1653 break; 1654 } 1655 1656 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1657 1658 state.setVerifierResponse(response.callerUid, response.code); 1659 1660 if (state.isVerificationComplete()) { 1661 mPendingVerification.remove(verificationId); 1662 1663 final InstallArgs args = state.getInstallArgs(); 1664 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1665 1666 int ret; 1667 if (state.isInstallAllowed()) { 1668 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1669 broadcastPackageVerified(verificationId, originUri, 1670 response.code, state.getInstallArgs().getUser()); 1671 try { 1672 ret = args.copyApk(mContainerService, true); 1673 } catch (RemoteException e) { 1674 Slog.e(TAG, "Could not contact the ContainerService"); 1675 } 1676 } else { 1677 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1678 } 1679 1680 Trace.asyncTraceEnd( 1681 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1682 1683 processPendingInstall(args, ret); 1684 mHandler.sendEmptyMessage(MCS_UNBIND); 1685 } 1686 1687 break; 1688 } 1689 case START_INTENT_FILTER_VERIFICATIONS: { 1690 IFVerificationParams params = (IFVerificationParams) msg.obj; 1691 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1692 params.replacing, params.pkg); 1693 break; 1694 } 1695 case INTENT_FILTER_VERIFIED: { 1696 final int verificationId = msg.arg1; 1697 1698 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1699 verificationId); 1700 if (state == null) { 1701 Slog.w(TAG, "Invalid IntentFilter verification token " 1702 + verificationId + " received"); 1703 break; 1704 } 1705 1706 final int userId = state.getUserId(); 1707 1708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1709 "Processing IntentFilter verification with token:" 1710 + verificationId + " and userId:" + userId); 1711 1712 final IntentFilterVerificationResponse response = 1713 (IntentFilterVerificationResponse) msg.obj; 1714 1715 state.setVerifierResponse(response.callerUid, response.code); 1716 1717 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1718 "IntentFilter verification with token:" + verificationId 1719 + " and userId:" + userId 1720 + " is settings verifier response with response code:" 1721 + response.code); 1722 1723 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1724 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1725 + response.getFailedDomainsString()); 1726 } 1727 1728 if (state.isVerificationComplete()) { 1729 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1730 } else { 1731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1732 "IntentFilter verification with token:" + verificationId 1733 + " was not said to be complete"); 1734 } 1735 1736 break; 1737 } 1738 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1739 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1740 mInstantAppResolverConnection, 1741 (EphemeralRequest) msg.obj, 1742 mInstantAppInstallerActivity, 1743 mHandler); 1744 } 1745 } 1746 } 1747 } 1748 1749 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1750 boolean killApp, String[] grantedPermissions, 1751 boolean launchedForRestore, String installerPackage, 1752 IPackageInstallObserver2 installObserver) { 1753 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1754 // Send the removed broadcasts 1755 if (res.removedInfo != null) { 1756 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1757 } 1758 1759 // Now that we successfully installed the package, grant runtime 1760 // permissions if requested before broadcasting the install. Also 1761 // for legacy apps in permission review mode we clear the permission 1762 // review flag which is used to emulate runtime permissions for 1763 // legacy apps. 1764 if (grantPermissions) { 1765 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1766 } 1767 1768 final boolean update = res.removedInfo != null 1769 && res.removedInfo.removedPackage != null; 1770 1771 // If this is the first time we have child packages for a disabled privileged 1772 // app that had no children, we grant requested runtime permissions to the new 1773 // children if the parent on the system image had them already granted. 1774 if (res.pkg.parentPackage != null) { 1775 synchronized (mPackages) { 1776 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1777 } 1778 } 1779 1780 synchronized (mPackages) { 1781 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1782 } 1783 1784 final String packageName = res.pkg.applicationInfo.packageName; 1785 1786 // Determine the set of users who are adding this package for 1787 // the first time vs. those who are seeing an update. 1788 int[] firstUsers = EMPTY_INT_ARRAY; 1789 int[] updateUsers = EMPTY_INT_ARRAY; 1790 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1791 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1792 for (int newUser : res.newUsers) { 1793 if (ps.getInstantApp(newUser)) { 1794 continue; 1795 } 1796 if (allNewUsers) { 1797 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1798 continue; 1799 } 1800 boolean isNew = true; 1801 for (int origUser : res.origUsers) { 1802 if (origUser == newUser) { 1803 isNew = false; 1804 break; 1805 } 1806 } 1807 if (isNew) { 1808 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1809 } else { 1810 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1811 } 1812 } 1813 1814 // Send installed broadcasts if the package is not a static shared lib. 1815 if (res.pkg.staticSharedLibName == null) { 1816 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1817 1818 // Send added for users that see the package for the first time 1819 // sendPackageAddedForNewUsers also deals with system apps 1820 int appId = UserHandle.getAppId(res.uid); 1821 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1822 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1823 1824 // Send added for users that don't see the package for the first time 1825 Bundle extras = new Bundle(1); 1826 extras.putInt(Intent.EXTRA_UID, res.uid); 1827 if (update) { 1828 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1829 } 1830 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1831 extras, 0 /*flags*/, null /*targetPackage*/, 1832 null /*finishedReceiver*/, updateUsers); 1833 1834 // Send replaced for users that don't see the package for the first time 1835 if (update) { 1836 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1837 packageName, extras, 0 /*flags*/, 1838 null /*targetPackage*/, null /*finishedReceiver*/, 1839 updateUsers); 1840 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1841 null /*package*/, null /*extras*/, 0 /*flags*/, 1842 packageName /*targetPackage*/, 1843 null /*finishedReceiver*/, updateUsers); 1844 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1845 // First-install and we did a restore, so we're responsible for the 1846 // first-launch broadcast. 1847 if (DEBUG_BACKUP) { 1848 Slog.i(TAG, "Post-restore of " + packageName 1849 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1850 } 1851 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1852 } 1853 1854 // Send broadcast package appeared if forward locked/external for all users 1855 // treat asec-hosted packages like removable media on upgrade 1856 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1857 if (DEBUG_INSTALL) { 1858 Slog.i(TAG, "upgrading pkg " + res.pkg 1859 + " is ASEC-hosted -> AVAILABLE"); 1860 } 1861 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1862 ArrayList<String> pkgList = new ArrayList<>(1); 1863 pkgList.add(packageName); 1864 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1865 } 1866 } 1867 1868 // Work that needs to happen on first install within each user 1869 if (firstUsers != null && firstUsers.length > 0) { 1870 synchronized (mPackages) { 1871 for (int userId : firstUsers) { 1872 // If this app is a browser and it's newly-installed for some 1873 // users, clear any default-browser state in those users. The 1874 // app's nature doesn't depend on the user, so we can just check 1875 // its browser nature in any user and generalize. 1876 if (packageIsBrowser(packageName, userId)) { 1877 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1878 } 1879 1880 // We may also need to apply pending (restored) runtime 1881 // permission grants within these users. 1882 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1883 } 1884 } 1885 } 1886 1887 // Log current value of "unknown sources" setting 1888 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1889 getUnknownSourcesSettings()); 1890 1891 // Force a gc to clear up things 1892 Runtime.getRuntime().gc(); 1893 1894 // Remove the replaced package's older resources safely now 1895 // We delete after a gc for applications on sdcard. 1896 if (res.removedInfo != null && res.removedInfo.args != null) { 1897 synchronized (mInstallLock) { 1898 res.removedInfo.args.doPostDeleteLI(true); 1899 } 1900 } 1901 1902 // Notify DexManager that the package was installed for new users. 1903 // The updated users should already be indexed and the package code paths 1904 // should not change. 1905 // Don't notify the manager for ephemeral apps as they are not expected to 1906 // survive long enough to benefit of background optimizations. 1907 for (int userId : firstUsers) { 1908 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1909 mDexManager.notifyPackageInstalled(info, userId); 1910 } 1911 } 1912 1913 // If someone is watching installs - notify them 1914 if (installObserver != null) { 1915 try { 1916 Bundle extras = extrasForInstallResult(res); 1917 installObserver.onPackageInstalled(res.name, res.returnCode, 1918 res.returnMsg, extras); 1919 } catch (RemoteException e) { 1920 Slog.i(TAG, "Observer no longer exists."); 1921 } 1922 } 1923 } 1924 1925 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1926 PackageParser.Package pkg) { 1927 if (pkg.parentPackage == null) { 1928 return; 1929 } 1930 if (pkg.requestedPermissions == null) { 1931 return; 1932 } 1933 final PackageSetting disabledSysParentPs = mSettings 1934 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1935 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1936 || !disabledSysParentPs.isPrivileged() 1937 || (disabledSysParentPs.childPackageNames != null 1938 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1939 return; 1940 } 1941 final int[] allUserIds = sUserManager.getUserIds(); 1942 final int permCount = pkg.requestedPermissions.size(); 1943 for (int i = 0; i < permCount; i++) { 1944 String permission = pkg.requestedPermissions.get(i); 1945 BasePermission bp = mSettings.mPermissions.get(permission); 1946 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1947 continue; 1948 } 1949 for (int userId : allUserIds) { 1950 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1951 permission, userId)) { 1952 grantRuntimePermission(pkg.packageName, permission, userId); 1953 } 1954 } 1955 } 1956 } 1957 1958 private StorageEventListener mStorageListener = new StorageEventListener() { 1959 @Override 1960 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1961 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1962 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1963 final String volumeUuid = vol.getFsUuid(); 1964 1965 // Clean up any users or apps that were removed or recreated 1966 // while this volume was missing 1967 sUserManager.reconcileUsers(volumeUuid); 1968 reconcileApps(volumeUuid); 1969 1970 // Clean up any install sessions that expired or were 1971 // cancelled while this volume was missing 1972 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1973 1974 loadPrivatePackages(vol); 1975 1976 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1977 unloadPrivatePackages(vol); 1978 } 1979 } 1980 1981 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1982 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1983 updateExternalMediaStatus(true, false); 1984 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1985 updateExternalMediaStatus(false, false); 1986 } 1987 } 1988 } 1989 1990 @Override 1991 public void onVolumeForgotten(String fsUuid) { 1992 if (TextUtils.isEmpty(fsUuid)) { 1993 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1994 return; 1995 } 1996 1997 // Remove any apps installed on the forgotten volume 1998 synchronized (mPackages) { 1999 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2000 for (PackageSetting ps : packages) { 2001 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2002 deletePackageVersioned(new VersionedPackage(ps.name, 2003 PackageManager.VERSION_CODE_HIGHEST), 2004 new LegacyPackageDeleteObserver(null).getBinder(), 2005 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2006 // Try very hard to release any references to this package 2007 // so we don't risk the system server being killed due to 2008 // open FDs 2009 AttributeCache.instance().removePackage(ps.name); 2010 } 2011 2012 mSettings.onVolumeForgotten(fsUuid); 2013 mSettings.writeLPr(); 2014 } 2015 } 2016 }; 2017 2018 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2019 String[] grantedPermissions) { 2020 for (int userId : userIds) { 2021 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2022 } 2023 } 2024 2025 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2026 String[] grantedPermissions) { 2027 SettingBase sb = (SettingBase) pkg.mExtras; 2028 if (sb == null) { 2029 return; 2030 } 2031 2032 PermissionsState permissionsState = sb.getPermissionsState(); 2033 2034 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2035 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2036 2037 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2038 >= Build.VERSION_CODES.M; 2039 2040 for (String permission : pkg.requestedPermissions) { 2041 final BasePermission bp; 2042 synchronized (mPackages) { 2043 bp = mSettings.mPermissions.get(permission); 2044 } 2045 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2046 && (grantedPermissions == null 2047 || ArrayUtils.contains(grantedPermissions, permission))) { 2048 final int flags = permissionsState.getPermissionFlags(permission, userId); 2049 if (supportsRuntimePermissions) { 2050 // Installer cannot change immutable permissions. 2051 if ((flags & immutableFlags) == 0) { 2052 grantRuntimePermission(pkg.packageName, permission, userId); 2053 } 2054 } else if (mPermissionReviewRequired) { 2055 // In permission review mode we clear the review flag when we 2056 // are asked to install the app with all permissions granted. 2057 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2058 updatePermissionFlags(permission, pkg.packageName, 2059 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2060 } 2061 } 2062 } 2063 } 2064 } 2065 2066 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2067 Bundle extras = null; 2068 switch (res.returnCode) { 2069 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2070 extras = new Bundle(); 2071 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2072 res.origPermission); 2073 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2074 res.origPackage); 2075 break; 2076 } 2077 case PackageManager.INSTALL_SUCCEEDED: { 2078 extras = new Bundle(); 2079 extras.putBoolean(Intent.EXTRA_REPLACING, 2080 res.removedInfo != null && res.removedInfo.removedPackage != null); 2081 break; 2082 } 2083 } 2084 return extras; 2085 } 2086 2087 void scheduleWriteSettingsLocked() { 2088 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2089 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2090 } 2091 } 2092 2093 void scheduleWritePackageListLocked(int userId) { 2094 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2095 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2096 msg.arg1 = userId; 2097 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2098 } 2099 } 2100 2101 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2102 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2103 scheduleWritePackageRestrictionsLocked(userId); 2104 } 2105 2106 void scheduleWritePackageRestrictionsLocked(int userId) { 2107 final int[] userIds = (userId == UserHandle.USER_ALL) 2108 ? sUserManager.getUserIds() : new int[]{userId}; 2109 for (int nextUserId : userIds) { 2110 if (!sUserManager.exists(nextUserId)) return; 2111 mDirtyUsers.add(nextUserId); 2112 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2113 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2114 } 2115 } 2116 } 2117 2118 public static PackageManagerService main(Context context, Installer installer, 2119 boolean factoryTest, boolean onlyCore) { 2120 // Self-check for initial settings. 2121 PackageManagerServiceCompilerMapping.checkProperties(); 2122 2123 PackageManagerService m = new PackageManagerService(context, installer, 2124 factoryTest, onlyCore); 2125 m.enableSystemUserPackages(); 2126 ServiceManager.addService("package", m); 2127 return m; 2128 } 2129 2130 private void enableSystemUserPackages() { 2131 if (!UserManager.isSplitSystemUser()) { 2132 return; 2133 } 2134 // For system user, enable apps based on the following conditions: 2135 // - app is whitelisted or belong to one of these groups: 2136 // -- system app which has no launcher icons 2137 // -- system app which has INTERACT_ACROSS_USERS permission 2138 // -- system IME app 2139 // - app is not in the blacklist 2140 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2141 Set<String> enableApps = new ArraySet<>(); 2142 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2143 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2144 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2145 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2146 enableApps.addAll(wlApps); 2147 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2148 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2149 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2150 enableApps.removeAll(blApps); 2151 Log.i(TAG, "Applications installed for system user: " + enableApps); 2152 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2153 UserHandle.SYSTEM); 2154 final int allAppsSize = allAps.size(); 2155 synchronized (mPackages) { 2156 for (int i = 0; i < allAppsSize; i++) { 2157 String pName = allAps.get(i); 2158 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2159 // Should not happen, but we shouldn't be failing if it does 2160 if (pkgSetting == null) { 2161 continue; 2162 } 2163 boolean install = enableApps.contains(pName); 2164 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2165 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2166 + " for system user"); 2167 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2168 } 2169 } 2170 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2171 } 2172 } 2173 2174 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2175 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2176 Context.DISPLAY_SERVICE); 2177 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2178 } 2179 2180 /** 2181 * Requests that files preopted on a secondary system partition be copied to the data partition 2182 * if possible. Note that the actual copying of the files is accomplished by init for security 2183 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2184 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2185 */ 2186 private static void requestCopyPreoptedFiles() { 2187 final int WAIT_TIME_MS = 100; 2188 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2189 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2190 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2191 // We will wait for up to 100 seconds. 2192 final long timeStart = SystemClock.uptimeMillis(); 2193 final long timeEnd = timeStart + 100 * 1000; 2194 long timeNow = timeStart; 2195 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2196 try { 2197 Thread.sleep(WAIT_TIME_MS); 2198 } catch (InterruptedException e) { 2199 // Do nothing 2200 } 2201 timeNow = SystemClock.uptimeMillis(); 2202 if (timeNow > timeEnd) { 2203 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2204 Slog.wtf(TAG, "cppreopt did not finish!"); 2205 break; 2206 } 2207 } 2208 2209 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2210 } 2211 } 2212 2213 public PackageManagerService(Context context, Installer installer, 2214 boolean factoryTest, boolean onlyCore) { 2215 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2216 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2217 SystemClock.uptimeMillis()); 2218 2219 if (mSdkVersion <= 0) { 2220 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2221 } 2222 2223 mContext = context; 2224 2225 mPermissionReviewRequired = context.getResources().getBoolean( 2226 R.bool.config_permissionReviewRequired); 2227 2228 mFactoryTest = factoryTest; 2229 mOnlyCore = onlyCore; 2230 mMetrics = new DisplayMetrics(); 2231 mSettings = new Settings(mPackages); 2232 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2237 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2238 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 2245 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2246 if (separateProcesses != null && separateProcesses.length() > 0) { 2247 if ("*".equals(separateProcesses)) { 2248 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2249 mSeparateProcesses = null; 2250 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2251 } else { 2252 mDefParseFlags = 0; 2253 mSeparateProcesses = separateProcesses.split(","); 2254 Slog.w(TAG, "Running with debug.separate_processes: " 2255 + separateProcesses); 2256 } 2257 } else { 2258 mDefParseFlags = 0; 2259 mSeparateProcesses = null; 2260 } 2261 2262 mInstaller = installer; 2263 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2264 "*dexopt*"); 2265 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2266 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2267 2268 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2269 FgThread.get().getLooper()); 2270 2271 getDefaultDisplayMetrics(context, mMetrics); 2272 2273 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2274 SystemConfig systemConfig = SystemConfig.getInstance(); 2275 mGlobalGids = systemConfig.getGlobalGids(); 2276 mSystemPermissions = systemConfig.getSystemPermissions(); 2277 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2279 2280 mProtectedPackages = new ProtectedPackages(mContext); 2281 2282 synchronized (mInstallLock) { 2283 // writer 2284 synchronized (mPackages) { 2285 mHandlerThread = new ServiceThread(TAG, 2286 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2287 mHandlerThread.start(); 2288 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2289 mProcessLoggingHandler = new ProcessLoggingHandler(); 2290 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2291 2292 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2293 mInstantAppRegistry = new InstantAppRegistry(this); 2294 2295 File dataDir = Environment.getDataDirectory(); 2296 mAppInstallDir = new File(dataDir, "app"); 2297 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2298 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2299 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2300 sUserManager = new UserManagerService(context, this, 2301 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2302 2303 // Propagate permission configuration in to package manager. 2304 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2305 = systemConfig.getPermissions(); 2306 for (int i=0; i<permConfig.size(); i++) { 2307 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2308 BasePermission bp = mSettings.mPermissions.get(perm.name); 2309 if (bp == null) { 2310 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2311 mSettings.mPermissions.put(perm.name, bp); 2312 } 2313 if (perm.gids != null) { 2314 bp.setGids(perm.gids, perm.perUser); 2315 } 2316 } 2317 2318 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2319 final int builtInLibCount = libConfig.size(); 2320 for (int i = 0; i < builtInLibCount; i++) { 2321 String name = libConfig.keyAt(i); 2322 String path = libConfig.valueAt(i); 2323 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2324 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2325 } 2326 2327 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2328 2329 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2330 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2331 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2332 2333 // Clean up orphaned packages for which the code path doesn't exist 2334 // and they are an update to a system app - caused by bug/32321269 2335 final int packageSettingCount = mSettings.mPackages.size(); 2336 for (int i = packageSettingCount - 1; i >= 0; i--) { 2337 PackageSetting ps = mSettings.mPackages.valueAt(i); 2338 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2339 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2340 mSettings.mPackages.removeAt(i); 2341 mSettings.enableSystemPackageLPw(ps.name); 2342 } 2343 } 2344 2345 if (mFirstBoot) { 2346 requestCopyPreoptedFiles(); 2347 } 2348 2349 String customResolverActivity = Resources.getSystem().getString( 2350 R.string.config_customResolverActivity); 2351 if (TextUtils.isEmpty(customResolverActivity)) { 2352 customResolverActivity = null; 2353 } else { 2354 mCustomResolverComponentName = ComponentName.unflattenFromString( 2355 customResolverActivity); 2356 } 2357 2358 long startTime = SystemClock.uptimeMillis(); 2359 2360 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2361 startTime); 2362 2363 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2364 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2365 2366 if (bootClassPath == null) { 2367 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2368 } 2369 2370 if (systemServerClassPath == null) { 2371 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2372 } 2373 2374 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2375 final String[] dexCodeInstructionSets = 2376 getDexCodeInstructionSets( 2377 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2378 2379 /** 2380 * Ensure all external libraries have had dexopt run on them. 2381 */ 2382 if (mSharedLibraries.size() > 0) { 2383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2384 // NOTE: For now, we're compiling these system "shared libraries" 2385 // (and framework jars) into all available architectures. It's possible 2386 // to compile them only when we come across an app that uses them (there's 2387 // already logic for that in scanPackageLI) but that adds some complexity. 2388 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2389 final int libCount = mSharedLibraries.size(); 2390 for (int i = 0; i < libCount; i++) { 2391 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2392 final int versionCount = versionedLib.size(); 2393 for (int j = 0; j < versionCount; j++) { 2394 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2395 final String libPath = libEntry.path != null 2396 ? libEntry.path : libEntry.apk; 2397 if (libPath == null) { 2398 continue; 2399 } 2400 try { 2401 // Shared libraries do not have profiles so we perform a full 2402 // AOT compilation (if needed). 2403 int dexoptNeeded = DexFile.getDexOptNeeded( 2404 libPath, dexCodeInstructionSet, 2405 getCompilerFilterForReason(REASON_SHARED_APK), 2406 false /* newProfile */); 2407 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2408 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2409 dexCodeInstructionSet, dexoptNeeded, null, 2410 DEXOPT_PUBLIC, 2411 getCompilerFilterForReason(REASON_SHARED_APK), 2412 StorageManager.UUID_PRIVATE_INTERNAL, 2413 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2414 } 2415 } catch (FileNotFoundException e) { 2416 Slog.w(TAG, "Library not found: " + libPath); 2417 } catch (IOException | InstallerException e) { 2418 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2419 + e.getMessage()); 2420 } 2421 } 2422 } 2423 } 2424 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2425 } 2426 2427 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2428 2429 final VersionInfo ver = mSettings.getInternalVersion(); 2430 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2431 2432 // when upgrading from pre-M, promote system app permissions from install to runtime 2433 mPromoteSystemApps = 2434 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2435 2436 // When upgrading from pre-N, we need to handle package extraction like first boot, 2437 // as there is no profiling data available. 2438 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2439 2440 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2441 2442 // save off the names of pre-existing system packages prior to scanning; we don't 2443 // want to automatically grant runtime permissions for new system apps 2444 if (mPromoteSystemApps) { 2445 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2446 while (pkgSettingIter.hasNext()) { 2447 PackageSetting ps = pkgSettingIter.next(); 2448 if (isSystemApp(ps)) { 2449 mExistingSystemPackages.add(ps.name); 2450 } 2451 } 2452 } 2453 2454 mCacheDir = preparePackageParserCache(mIsUpgrade); 2455 2456 // Set flag to monitor and not change apk file paths when 2457 // scanning install directories. 2458 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2459 2460 if (mIsUpgrade || mFirstBoot) { 2461 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2462 } 2463 2464 // Collect vendor overlay packages. (Do this before scanning any apps.) 2465 // For security and version matching reason, only consider 2466 // overlay packages if they reside in the right directory. 2467 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2468 if (overlayThemeDir.isEmpty()) { 2469 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2470 } 2471 if (!overlayThemeDir.isEmpty()) { 2472 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2473 | PackageParser.PARSE_IS_SYSTEM 2474 | PackageParser.PARSE_IS_SYSTEM_DIR 2475 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2476 } 2477 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2478 | PackageParser.PARSE_IS_SYSTEM 2479 | PackageParser.PARSE_IS_SYSTEM_DIR 2480 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2481 2482 // Find base frameworks (resource packages without code). 2483 scanDirTracedLI(frameworkDir, mDefParseFlags 2484 | PackageParser.PARSE_IS_SYSTEM 2485 | PackageParser.PARSE_IS_SYSTEM_DIR 2486 | PackageParser.PARSE_IS_PRIVILEGED, 2487 scanFlags | SCAN_NO_DEX, 0); 2488 2489 // Collected privileged system packages. 2490 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2491 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2492 | PackageParser.PARSE_IS_SYSTEM 2493 | PackageParser.PARSE_IS_SYSTEM_DIR 2494 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2495 2496 // Collect ordinary system packages. 2497 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2498 scanDirTracedLI(systemAppDir, mDefParseFlags 2499 | PackageParser.PARSE_IS_SYSTEM 2500 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2501 2502 // Collect all vendor packages. 2503 File vendorAppDir = new File("/vendor/app"); 2504 try { 2505 vendorAppDir = vendorAppDir.getCanonicalFile(); 2506 } catch (IOException e) { 2507 // failed to look up canonical path, continue with original one 2508 } 2509 scanDirTracedLI(vendorAppDir, mDefParseFlags 2510 | PackageParser.PARSE_IS_SYSTEM 2511 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2512 2513 // Collect all OEM packages. 2514 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2515 scanDirTracedLI(oemAppDir, mDefParseFlags 2516 | PackageParser.PARSE_IS_SYSTEM 2517 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2518 2519 // Prune any system packages that no longer exist. 2520 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2521 if (!mOnlyCore) { 2522 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2523 while (psit.hasNext()) { 2524 PackageSetting ps = psit.next(); 2525 2526 /* 2527 * If this is not a system app, it can't be a 2528 * disable system app. 2529 */ 2530 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2531 continue; 2532 } 2533 2534 /* 2535 * If the package is scanned, it's not erased. 2536 */ 2537 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2538 if (scannedPkg != null) { 2539 /* 2540 * If the system app is both scanned and in the 2541 * disabled packages list, then it must have been 2542 * added via OTA. Remove it from the currently 2543 * scanned package so the previously user-installed 2544 * application can be scanned. 2545 */ 2546 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2547 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2548 + ps.name + "; removing system app. Last known codePath=" 2549 + ps.codePathString + ", installStatus=" + ps.installStatus 2550 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2551 + scannedPkg.mVersionCode); 2552 removePackageLI(scannedPkg, true); 2553 mExpectingBetter.put(ps.name, ps.codePath); 2554 } 2555 2556 continue; 2557 } 2558 2559 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2560 psit.remove(); 2561 logCriticalInfo(Log.WARN, "System package " + ps.name 2562 + " no longer exists; it's data will be wiped"); 2563 // Actual deletion of code and data will be handled by later 2564 // reconciliation step 2565 } else { 2566 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2567 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2568 possiblyDeletedUpdatedSystemApps.add(ps.name); 2569 } 2570 } 2571 } 2572 } 2573 2574 //look for any incomplete package installations 2575 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2576 for (int i = 0; i < deletePkgsList.size(); i++) { 2577 // Actual deletion of code and data will be handled by later 2578 // reconciliation step 2579 final String packageName = deletePkgsList.get(i).name; 2580 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2581 synchronized (mPackages) { 2582 mSettings.removePackageLPw(packageName); 2583 } 2584 } 2585 2586 //delete tmp files 2587 deleteTempPackageFiles(); 2588 2589 // Remove any shared userIDs that have no associated packages 2590 mSettings.pruneSharedUsersLPw(); 2591 2592 if (!mOnlyCore) { 2593 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2594 SystemClock.uptimeMillis()); 2595 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2596 2597 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2598 | PackageParser.PARSE_FORWARD_LOCK, 2599 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2600 2601 /** 2602 * Remove disable package settings for any updated system 2603 * apps that were removed via an OTA. If they're not a 2604 * previously-updated app, remove them completely. 2605 * Otherwise, just revoke their system-level permissions. 2606 */ 2607 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2608 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2609 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2610 2611 String msg; 2612 if (deletedPkg == null) { 2613 msg = "Updated system package " + deletedAppName 2614 + " no longer exists; it's data will be wiped"; 2615 // Actual deletion of code and data will be handled by later 2616 // reconciliation step 2617 } else { 2618 msg = "Updated system app + " + deletedAppName 2619 + " no longer present; removing system privileges for " 2620 + deletedAppName; 2621 2622 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2623 2624 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2625 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2626 } 2627 logCriticalInfo(Log.WARN, msg); 2628 } 2629 2630 /** 2631 * Make sure all system apps that we expected to appear on 2632 * the userdata partition actually showed up. If they never 2633 * appeared, crawl back and revive the system version. 2634 */ 2635 for (int i = 0; i < mExpectingBetter.size(); i++) { 2636 final String packageName = mExpectingBetter.keyAt(i); 2637 if (!mPackages.containsKey(packageName)) { 2638 final File scanFile = mExpectingBetter.valueAt(i); 2639 2640 logCriticalInfo(Log.WARN, "Expected better " + packageName 2641 + " but never showed up; reverting to system"); 2642 2643 int reparseFlags = mDefParseFlags; 2644 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2645 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2646 | PackageParser.PARSE_IS_SYSTEM_DIR 2647 | PackageParser.PARSE_IS_PRIVILEGED; 2648 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2649 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2650 | PackageParser.PARSE_IS_SYSTEM_DIR; 2651 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2652 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2653 | PackageParser.PARSE_IS_SYSTEM_DIR; 2654 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2655 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2656 | PackageParser.PARSE_IS_SYSTEM_DIR; 2657 } else { 2658 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2659 continue; 2660 } 2661 2662 mSettings.enableSystemPackageLPw(packageName); 2663 2664 try { 2665 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2666 } catch (PackageManagerException e) { 2667 Slog.e(TAG, "Failed to parse original system package: " 2668 + e.getMessage()); 2669 } 2670 } 2671 } 2672 } 2673 mExpectingBetter.clear(); 2674 2675 // Resolve the storage manager. 2676 mStorageManagerPackage = getStorageManagerPackageName(); 2677 2678 // Resolve protected action filters. Only the setup wizard is allowed to 2679 // have a high priority filter for these actions. 2680 mSetupWizardPackage = getSetupWizardPackageName(); 2681 if (mProtectedFilters.size() > 0) { 2682 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2683 Slog.i(TAG, "No setup wizard;" 2684 + " All protected intents capped to priority 0"); 2685 } 2686 for (ActivityIntentInfo filter : mProtectedFilters) { 2687 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2688 if (DEBUG_FILTERS) { 2689 Slog.i(TAG, "Found setup wizard;" 2690 + " allow priority " + filter.getPriority() + ";" 2691 + " package: " + filter.activity.info.packageName 2692 + " activity: " + filter.activity.className 2693 + " priority: " + filter.getPriority()); 2694 } 2695 // skip setup wizard; allow it to keep the high priority filter 2696 continue; 2697 } 2698 Slog.w(TAG, "Protected action; cap priority to 0;" 2699 + " package: " + filter.activity.info.packageName 2700 + " activity: " + filter.activity.className 2701 + " origPrio: " + filter.getPriority()); 2702 filter.setPriority(0); 2703 } 2704 } 2705 mDeferProtectedFilters = false; 2706 mProtectedFilters.clear(); 2707 2708 // Now that we know all of the shared libraries, update all clients to have 2709 // the correct library paths. 2710 updateAllSharedLibrariesLPw(null); 2711 2712 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2713 // NOTE: We ignore potential failures here during a system scan (like 2714 // the rest of the commands above) because there's precious little we 2715 // can do about it. A settings error is reported, though. 2716 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2717 } 2718 2719 // Now that we know all the packages we are keeping, 2720 // read and update their last usage times. 2721 mPackageUsage.read(mPackages); 2722 mCompilerStats.read(); 2723 2724 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2725 SystemClock.uptimeMillis()); 2726 Slog.i(TAG, "Time to scan packages: " 2727 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2728 + " seconds"); 2729 2730 // If the platform SDK has changed since the last time we booted, 2731 // we need to re-grant app permission to catch any new ones that 2732 // appear. This is really a hack, and means that apps can in some 2733 // cases get permissions that the user didn't initially explicitly 2734 // allow... it would be nice to have some better way to handle 2735 // this situation. 2736 int updateFlags = UPDATE_PERMISSIONS_ALL; 2737 if (ver.sdkVersion != mSdkVersion) { 2738 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2739 + mSdkVersion + "; regranting permissions for internal storage"); 2740 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2741 } 2742 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2743 ver.sdkVersion = mSdkVersion; 2744 2745 // If this is the first boot or an update from pre-M, and it is a normal 2746 // boot, then we need to initialize the default preferred apps across 2747 // all defined users. 2748 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2749 for (UserInfo user : sUserManager.getUsers(true)) { 2750 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2751 applyFactoryDefaultBrowserLPw(user.id); 2752 primeDomainVerificationsLPw(user.id); 2753 } 2754 } 2755 2756 // Prepare storage for system user really early during boot, 2757 // since core system apps like SettingsProvider and SystemUI 2758 // can't wait for user to start 2759 final int storageFlags; 2760 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2761 storageFlags = StorageManager.FLAG_STORAGE_DE; 2762 } else { 2763 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2764 } 2765 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2766 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2767 true /* onlyCoreApps */); 2768 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2769 if (deferPackages == null || deferPackages.isEmpty()) { 2770 return; 2771 } 2772 int count = 0; 2773 for (String pkgName : deferPackages) { 2774 PackageParser.Package pkg = null; 2775 synchronized (mPackages) { 2776 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2777 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2778 pkg = ps.pkg; 2779 } 2780 } 2781 if (pkg != null) { 2782 synchronized (mInstallLock) { 2783 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2784 true /* maybeMigrateAppData */); 2785 } 2786 count++; 2787 } 2788 } 2789 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2790 }, "prepareAppData"); 2791 2792 // If this is first boot after an OTA, and a normal boot, then 2793 // we need to clear code cache directories. 2794 // Note that we do *not* clear the application profiles. These remain valid 2795 // across OTAs and are used to drive profile verification (post OTA) and 2796 // profile compilation (without waiting to collect a fresh set of profiles). 2797 if (mIsUpgrade && !onlyCore) { 2798 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2799 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2800 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2801 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2802 // No apps are running this early, so no need to freeze 2803 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2804 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2805 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2806 } 2807 } 2808 ver.fingerprint = Build.FINGERPRINT; 2809 } 2810 2811 checkDefaultBrowser(); 2812 2813 // clear only after permissions and other defaults have been updated 2814 mExistingSystemPackages.clear(); 2815 mPromoteSystemApps = false; 2816 2817 // All the changes are done during package scanning. 2818 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2819 2820 // can downgrade to reader 2821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2822 mSettings.writeLPr(); 2823 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2824 2825 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2826 // early on (before the package manager declares itself as early) because other 2827 // components in the system server might ask for package contexts for these apps. 2828 // 2829 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2830 // (i.e, that the data partition is unavailable). 2831 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2832 long start = System.nanoTime(); 2833 List<PackageParser.Package> coreApps = new ArrayList<>(); 2834 for (PackageParser.Package pkg : mPackages.values()) { 2835 if (pkg.coreApp) { 2836 coreApps.add(pkg); 2837 } 2838 } 2839 2840 int[] stats = performDexOptUpgrade(coreApps, false, 2841 getCompilerFilterForReason(REASON_CORE_APP)); 2842 2843 final int elapsedTimeSeconds = 2844 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2845 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2846 2847 if (DEBUG_DEXOPT) { 2848 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2849 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2850 } 2851 2852 2853 // TODO: Should we log these stats to tron too ? 2854 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2855 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2856 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2857 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2858 } 2859 2860 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2861 SystemClock.uptimeMillis()); 2862 2863 if (!mOnlyCore) { 2864 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2865 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2866 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2867 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2868 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2869 mIntentFilterVerifierComponent); 2870 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2871 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2872 SharedLibraryInfo.VERSION_UNDEFINED); 2873 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2874 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2875 SharedLibraryInfo.VERSION_UNDEFINED); 2876 } else { 2877 mRequiredVerifierPackage = null; 2878 mRequiredInstallerPackage = null; 2879 mRequiredUninstallerPackage = null; 2880 mIntentFilterVerifierComponent = null; 2881 mIntentFilterVerifier = null; 2882 mServicesSystemSharedLibraryPackageName = null; 2883 mSharedSystemSharedLibraryPackageName = null; 2884 } 2885 2886 mInstallerService = new PackageInstallerService(context, this); 2887 2888 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2889 if (ephemeralResolverComponent != null) { 2890 if (DEBUG_EPHEMERAL) { 2891 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2892 } 2893 mInstantAppResolverConnection = 2894 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2895 } else { 2896 mInstantAppResolverConnection = null; 2897 } 2898 mInstantAppInstallerComponent = getEphemeralInstallerLPr(); 2899 if (mInstantAppInstallerComponent != null) { 2900 if (DEBUG_EPHEMERAL) { 2901 Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent); 2902 } 2903 setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent); 2904 } 2905 2906 // Read and update the usage of dex files. 2907 // Do this at the end of PM init so that all the packages have their 2908 // data directory reconciled. 2909 // At this point we know the code paths of the packages, so we can validate 2910 // the disk file and build the internal cache. 2911 // The usage file is expected to be small so loading and verifying it 2912 // should take a fairly small time compare to the other activities (e.g. package 2913 // scanning). 2914 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2915 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2916 for (int userId : currentUserIds) { 2917 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2918 } 2919 mDexManager.load(userPackages); 2920 } // synchronized (mPackages) 2921 } // synchronized (mInstallLock) 2922 2923 // Now after opening every single application zip, make sure they 2924 // are all flushed. Not really needed, but keeps things nice and 2925 // tidy. 2926 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2927 Runtime.getRuntime().gc(); 2928 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2929 2930 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2931 FallbackCategoryProvider.loadFallbacks(); 2932 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2933 2934 // The initial scanning above does many calls into installd while 2935 // holding the mPackages lock, but we're mostly interested in yelling 2936 // once we have a booted system. 2937 mInstaller.setWarnIfHeld(mPackages); 2938 2939 // Expose private service for system components to use. 2940 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2941 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2942 } 2943 2944 private static File preparePackageParserCache(boolean isUpgrade) { 2945 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2946 return null; 2947 } 2948 2949 // Disable package parsing on eng builds to allow for faster incremental development. 2950 if ("eng".equals(Build.TYPE)) { 2951 return null; 2952 } 2953 2954 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2955 Slog.i(TAG, "Disabling package parser cache due to system property."); 2956 return null; 2957 } 2958 2959 // The base directory for the package parser cache lives under /data/system/. 2960 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2961 "package_cache"); 2962 if (cacheBaseDir == null) { 2963 return null; 2964 } 2965 2966 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2967 // This also serves to "GC" unused entries when the package cache version changes (which 2968 // can only happen during upgrades). 2969 if (isUpgrade) { 2970 FileUtils.deleteContents(cacheBaseDir); 2971 } 2972 2973 2974 // Return the versioned package cache directory. This is something like 2975 // "/data/system/package_cache/1" 2976 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2977 2978 // The following is a workaround to aid development on non-numbered userdebug 2979 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2980 // the system partition is newer. 2981 // 2982 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2983 // that starts with "eng." to signify that this is an engineering build and not 2984 // destined for release. 2985 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2986 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2987 2988 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2989 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2990 // in general and should not be used for production changes. In this specific case, 2991 // we know that they will work. 2992 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2993 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2994 FileUtils.deleteContents(cacheBaseDir); 2995 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2996 } 2997 } 2998 2999 return cacheDir; 3000 } 3001 3002 @Override 3003 public boolean isFirstBoot() { 3004 return mFirstBoot; 3005 } 3006 3007 @Override 3008 public boolean isOnlyCoreApps() { 3009 return mOnlyCore; 3010 } 3011 3012 @Override 3013 public boolean isUpgrade() { 3014 return mIsUpgrade; 3015 } 3016 3017 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3018 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3019 3020 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3021 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3022 UserHandle.USER_SYSTEM); 3023 if (matches.size() == 1) { 3024 return matches.get(0).getComponentInfo().packageName; 3025 } else if (matches.size() == 0) { 3026 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3027 return null; 3028 } 3029 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3030 } 3031 3032 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3033 synchronized (mPackages) { 3034 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3035 if (libraryEntry == null) { 3036 throw new IllegalStateException("Missing required shared library:" + name); 3037 } 3038 return libraryEntry.apk; 3039 } 3040 } 3041 3042 private @NonNull String getRequiredInstallerLPr() { 3043 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3044 intent.addCategory(Intent.CATEGORY_DEFAULT); 3045 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3046 3047 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3048 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3049 UserHandle.USER_SYSTEM); 3050 if (matches.size() == 1) { 3051 ResolveInfo resolveInfo = matches.get(0); 3052 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3053 throw new RuntimeException("The installer must be a privileged app"); 3054 } 3055 return matches.get(0).getComponentInfo().packageName; 3056 } else { 3057 throw new RuntimeException("There must be exactly one installer; found " + matches); 3058 } 3059 } 3060 3061 private @NonNull String getRequiredUninstallerLPr() { 3062 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3063 intent.addCategory(Intent.CATEGORY_DEFAULT); 3064 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3065 3066 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3067 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3068 UserHandle.USER_SYSTEM); 3069 if (resolveInfo == null || 3070 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3071 throw new RuntimeException("There must be exactly one uninstaller; found " 3072 + resolveInfo); 3073 } 3074 return resolveInfo.getComponentInfo().packageName; 3075 } 3076 3077 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3078 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3079 3080 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3081 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3082 UserHandle.USER_SYSTEM); 3083 ResolveInfo best = null; 3084 final int N = matches.size(); 3085 for (int i = 0; i < N; i++) { 3086 final ResolveInfo cur = matches.get(i); 3087 final String packageName = cur.getComponentInfo().packageName; 3088 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3089 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3090 continue; 3091 } 3092 3093 if (best == null || cur.priority > best.priority) { 3094 best = cur; 3095 } 3096 } 3097 3098 if (best != null) { 3099 return best.getComponentInfo().getComponentName(); 3100 } else { 3101 throw new RuntimeException("There must be at least one intent filter verifier"); 3102 } 3103 } 3104 3105 private @Nullable ComponentName getEphemeralResolverLPr() { 3106 final String[] packageArray = 3107 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3108 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3109 if (DEBUG_EPHEMERAL) { 3110 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3111 } 3112 return null; 3113 } 3114 3115 final int resolveFlags = 3116 MATCH_DIRECT_BOOT_AWARE 3117 | MATCH_DIRECT_BOOT_UNAWARE 3118 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3119 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3120 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3121 resolveFlags, UserHandle.USER_SYSTEM); 3122 3123 final int N = resolvers.size(); 3124 if (N == 0) { 3125 if (DEBUG_EPHEMERAL) { 3126 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3127 } 3128 return null; 3129 } 3130 3131 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3132 for (int i = 0; i < N; i++) { 3133 final ResolveInfo info = resolvers.get(i); 3134 3135 if (info.serviceInfo == null) { 3136 continue; 3137 } 3138 3139 final String packageName = info.serviceInfo.packageName; 3140 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3141 if (DEBUG_EPHEMERAL) { 3142 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3143 + " pkg: " + packageName + ", info:" + info); 3144 } 3145 continue; 3146 } 3147 3148 if (DEBUG_EPHEMERAL) { 3149 Slog.v(TAG, "Ephemeral resolver found;" 3150 + " pkg: " + packageName + ", info:" + info); 3151 } 3152 return new ComponentName(packageName, info.serviceInfo.name); 3153 } 3154 if (DEBUG_EPHEMERAL) { 3155 Slog.v(TAG, "Ephemeral resolver NOT found"); 3156 } 3157 return null; 3158 } 3159 3160 private @Nullable ComponentName getEphemeralInstallerLPr() { 3161 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3162 intent.addCategory(Intent.CATEGORY_DEFAULT); 3163 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3164 3165 final int resolveFlags = 3166 MATCH_DIRECT_BOOT_AWARE 3167 | MATCH_DIRECT_BOOT_UNAWARE 3168 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3169 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3170 resolveFlags, UserHandle.USER_SYSTEM); 3171 Iterator<ResolveInfo> iter = matches.iterator(); 3172 while (iter.hasNext()) { 3173 final ResolveInfo rInfo = iter.next(); 3174 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3175 if (ps != null) { 3176 final PermissionsState permissionsState = ps.getPermissionsState(); 3177 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3178 continue; 3179 } 3180 } 3181 iter.remove(); 3182 } 3183 if (matches.size() == 0) { 3184 return null; 3185 } else if (matches.size() == 1) { 3186 return matches.get(0).getComponentInfo().getComponentName(); 3187 } else { 3188 throw new RuntimeException( 3189 "There must be at most one ephemeral installer; found " + matches); 3190 } 3191 } 3192 3193 private void primeDomainVerificationsLPw(int userId) { 3194 if (DEBUG_DOMAIN_VERIFICATION) { 3195 Slog.d(TAG, "Priming domain verifications in user " + userId); 3196 } 3197 3198 SystemConfig systemConfig = SystemConfig.getInstance(); 3199 ArraySet<String> packages = systemConfig.getLinkedApps(); 3200 3201 for (String packageName : packages) { 3202 PackageParser.Package pkg = mPackages.get(packageName); 3203 if (pkg != null) { 3204 if (!pkg.isSystemApp()) { 3205 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3206 continue; 3207 } 3208 3209 ArraySet<String> domains = null; 3210 for (PackageParser.Activity a : pkg.activities) { 3211 for (ActivityIntentInfo filter : a.intents) { 3212 if (hasValidDomains(filter)) { 3213 if (domains == null) { 3214 domains = new ArraySet<String>(); 3215 } 3216 domains.addAll(filter.getHostsList()); 3217 } 3218 } 3219 } 3220 3221 if (domains != null && domains.size() > 0) { 3222 if (DEBUG_DOMAIN_VERIFICATION) { 3223 Slog.v(TAG, " + " + packageName); 3224 } 3225 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3226 // state w.r.t. the formal app-linkage "no verification attempted" state; 3227 // and then 'always' in the per-user state actually used for intent resolution. 3228 final IntentFilterVerificationInfo ivi; 3229 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3230 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3231 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3232 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3233 } else { 3234 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3235 + "' does not handle web links"); 3236 } 3237 } else { 3238 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3239 } 3240 } 3241 3242 scheduleWritePackageRestrictionsLocked(userId); 3243 scheduleWriteSettingsLocked(); 3244 } 3245 3246 private void applyFactoryDefaultBrowserLPw(int userId) { 3247 // The default browser app's package name is stored in a string resource, 3248 // with a product-specific overlay used for vendor customization. 3249 String browserPkg = mContext.getResources().getString( 3250 com.android.internal.R.string.default_browser); 3251 if (!TextUtils.isEmpty(browserPkg)) { 3252 // non-empty string => required to be a known package 3253 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3254 if (ps == null) { 3255 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3256 browserPkg = null; 3257 } else { 3258 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3259 } 3260 } 3261 3262 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3263 // default. If there's more than one, just leave everything alone. 3264 if (browserPkg == null) { 3265 calculateDefaultBrowserLPw(userId); 3266 } 3267 } 3268 3269 private void calculateDefaultBrowserLPw(int userId) { 3270 List<String> allBrowsers = resolveAllBrowserApps(userId); 3271 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3272 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3273 } 3274 3275 private List<String> resolveAllBrowserApps(int userId) { 3276 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3277 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3278 PackageManager.MATCH_ALL, userId); 3279 3280 final int count = list.size(); 3281 List<String> result = new ArrayList<String>(count); 3282 for (int i=0; i<count; i++) { 3283 ResolveInfo info = list.get(i); 3284 if (info.activityInfo == null 3285 || !info.handleAllWebDataURI 3286 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3287 || result.contains(info.activityInfo.packageName)) { 3288 continue; 3289 } 3290 result.add(info.activityInfo.packageName); 3291 } 3292 3293 return result; 3294 } 3295 3296 private boolean packageIsBrowser(String packageName, int userId) { 3297 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3298 PackageManager.MATCH_ALL, userId); 3299 final int N = list.size(); 3300 for (int i = 0; i < N; i++) { 3301 ResolveInfo info = list.get(i); 3302 if (packageName.equals(info.activityInfo.packageName)) { 3303 return true; 3304 } 3305 } 3306 return false; 3307 } 3308 3309 private void checkDefaultBrowser() { 3310 final int myUserId = UserHandle.myUserId(); 3311 final String packageName = getDefaultBrowserPackageName(myUserId); 3312 if (packageName != null) { 3313 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3314 if (info == null) { 3315 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3316 synchronized (mPackages) { 3317 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3318 } 3319 } 3320 } 3321 } 3322 3323 @Override 3324 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3325 throws RemoteException { 3326 try { 3327 return super.onTransact(code, data, reply, flags); 3328 } catch (RuntimeException e) { 3329 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3330 Slog.wtf(TAG, "Package Manager Crash", e); 3331 } 3332 throw e; 3333 } 3334 } 3335 3336 static int[] appendInts(int[] cur, int[] add) { 3337 if (add == null) return cur; 3338 if (cur == null) return add; 3339 final int N = add.length; 3340 for (int i=0; i<N; i++) { 3341 cur = appendInt(cur, add[i]); 3342 } 3343 return cur; 3344 } 3345 3346 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3347 if (!sUserManager.exists(userId)) return null; 3348 if (ps == null) { 3349 return null; 3350 } 3351 final PackageParser.Package p = ps.pkg; 3352 if (p == null) { 3353 return null; 3354 } 3355 // Filter out ephemeral app metadata: 3356 // * The system/shell/root can see metadata for any app 3357 // * An installed app can see metadata for 1) other installed apps 3358 // and 2) ephemeral apps that have explicitly interacted with it 3359 // * Ephemeral apps can only see their own metadata 3360 // * Holding a signature permission allows seeing instant apps 3361 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3362 if (callingAppId != Process.SYSTEM_UID 3363 && callingAppId != Process.SHELL_UID 3364 && callingAppId != Process.ROOT_UID 3365 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3366 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3367 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3368 if (instantAppPackageName != null) { 3369 // ephemeral apps can only get information on themselves 3370 if (!instantAppPackageName.equals(p.packageName)) { 3371 return null; 3372 } 3373 } else { 3374 if (ps.getInstantApp(userId)) { 3375 // only get access to the ephemeral app if we've been granted access 3376 if (!mInstantAppRegistry.isInstantAccessGranted( 3377 userId, callingAppId, ps.appId)) { 3378 return null; 3379 } 3380 } 3381 } 3382 } 3383 3384 final PermissionsState permissionsState = ps.getPermissionsState(); 3385 3386 // Compute GIDs only if requested 3387 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3388 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3389 // Compute granted permissions only if package has requested permissions 3390 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3391 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3392 final PackageUserState state = ps.readUserState(userId); 3393 3394 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3395 && ps.isSystem()) { 3396 flags |= MATCH_ANY_USER; 3397 } 3398 3399 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3400 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3401 3402 if (packageInfo == null) { 3403 return null; 3404 } 3405 3406 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3407 resolveExternalPackageNameLPr(p); 3408 3409 return packageInfo; 3410 } 3411 3412 @Override 3413 public void checkPackageStartable(String packageName, int userId) { 3414 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3415 3416 synchronized (mPackages) { 3417 final PackageSetting ps = mSettings.mPackages.get(packageName); 3418 if (ps == null) { 3419 throw new SecurityException("Package " + packageName + " was not found!"); 3420 } 3421 3422 if (!ps.getInstalled(userId)) { 3423 throw new SecurityException( 3424 "Package " + packageName + " was not installed for user " + userId + "!"); 3425 } 3426 3427 if (mSafeMode && !ps.isSystem()) { 3428 throw new SecurityException("Package " + packageName + " not a system app!"); 3429 } 3430 3431 if (mFrozenPackages.contains(packageName)) { 3432 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3433 } 3434 3435 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3436 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3437 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3438 } 3439 } 3440 } 3441 3442 @Override 3443 public boolean isPackageAvailable(String packageName, int userId) { 3444 if (!sUserManager.exists(userId)) return false; 3445 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3446 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3447 synchronized (mPackages) { 3448 PackageParser.Package p = mPackages.get(packageName); 3449 if (p != null) { 3450 final PackageSetting ps = (PackageSetting) p.mExtras; 3451 if (ps != null) { 3452 final PackageUserState state = ps.readUserState(userId); 3453 if (state != null) { 3454 return PackageParser.isAvailable(state); 3455 } 3456 } 3457 } 3458 } 3459 return false; 3460 } 3461 3462 @Override 3463 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3464 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3465 flags, userId); 3466 } 3467 3468 @Override 3469 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3470 int flags, int userId) { 3471 return getPackageInfoInternal(versionedPackage.getPackageName(), 3472 // TODO: We will change version code to long, so in the new API it is long 3473 (int) versionedPackage.getVersionCode(), flags, userId); 3474 } 3475 3476 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3477 int flags, int userId) { 3478 if (!sUserManager.exists(userId)) return null; 3479 flags = updateFlagsForPackage(flags, userId, packageName); 3480 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3481 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3482 3483 // reader 3484 synchronized (mPackages) { 3485 // Normalize package name to handle renamed packages and static libs 3486 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3487 3488 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3489 if (matchFactoryOnly) { 3490 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3491 if (ps != null) { 3492 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3493 return null; 3494 } 3495 return generatePackageInfo(ps, flags, userId); 3496 } 3497 } 3498 3499 PackageParser.Package p = mPackages.get(packageName); 3500 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3501 return null; 3502 } 3503 if (DEBUG_PACKAGE_INFO) 3504 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3505 if (p != null) { 3506 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3507 Binder.getCallingUid(), userId)) { 3508 return null; 3509 } 3510 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3511 } 3512 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3513 final PackageSetting ps = mSettings.mPackages.get(packageName); 3514 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3515 return null; 3516 } 3517 return generatePackageInfo(ps, flags, userId); 3518 } 3519 } 3520 return null; 3521 } 3522 3523 3524 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3525 // System/shell/root get to see all static libs 3526 final int appId = UserHandle.getAppId(uid); 3527 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3528 || appId == Process.ROOT_UID) { 3529 return false; 3530 } 3531 3532 // No package means no static lib as it is always on internal storage 3533 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3534 return false; 3535 } 3536 3537 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3538 ps.pkg.staticSharedLibVersion); 3539 if (libEntry == null) { 3540 return false; 3541 } 3542 3543 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3544 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3545 if (uidPackageNames == null) { 3546 return true; 3547 } 3548 3549 for (String uidPackageName : uidPackageNames) { 3550 if (ps.name.equals(uidPackageName)) { 3551 return false; 3552 } 3553 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3554 if (uidPs != null) { 3555 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3556 libEntry.info.getName()); 3557 if (index < 0) { 3558 continue; 3559 } 3560 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3561 return false; 3562 } 3563 } 3564 } 3565 return true; 3566 } 3567 3568 @Override 3569 public String[] currentToCanonicalPackageNames(String[] names) { 3570 String[] out = new String[names.length]; 3571 // reader 3572 synchronized (mPackages) { 3573 for (int i=names.length-1; i>=0; i--) { 3574 PackageSetting ps = mSettings.mPackages.get(names[i]); 3575 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3576 } 3577 } 3578 return out; 3579 } 3580 3581 @Override 3582 public String[] canonicalToCurrentPackageNames(String[] names) { 3583 String[] out = new String[names.length]; 3584 // reader 3585 synchronized (mPackages) { 3586 for (int i=names.length-1; i>=0; i--) { 3587 String cur = mSettings.getRenamedPackageLPr(names[i]); 3588 out[i] = cur != null ? cur : names[i]; 3589 } 3590 } 3591 return out; 3592 } 3593 3594 @Override 3595 public int getPackageUid(String packageName, int flags, int userId) { 3596 if (!sUserManager.exists(userId)) return -1; 3597 flags = updateFlagsForPackage(flags, userId, packageName); 3598 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3599 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3600 3601 // reader 3602 synchronized (mPackages) { 3603 final PackageParser.Package p = mPackages.get(packageName); 3604 if (p != null && p.isMatch(flags)) { 3605 return UserHandle.getUid(userId, p.applicationInfo.uid); 3606 } 3607 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3608 final PackageSetting ps = mSettings.mPackages.get(packageName); 3609 if (ps != null && ps.isMatch(flags)) { 3610 return UserHandle.getUid(userId, ps.appId); 3611 } 3612 } 3613 } 3614 3615 return -1; 3616 } 3617 3618 @Override 3619 public int[] getPackageGids(String packageName, int flags, int userId) { 3620 if (!sUserManager.exists(userId)) return null; 3621 flags = updateFlagsForPackage(flags, userId, packageName); 3622 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3623 false /* requireFullPermission */, false /* checkShell */, 3624 "getPackageGids"); 3625 3626 // reader 3627 synchronized (mPackages) { 3628 final PackageParser.Package p = mPackages.get(packageName); 3629 if (p != null && p.isMatch(flags)) { 3630 PackageSetting ps = (PackageSetting) p.mExtras; 3631 // TODO: Shouldn't this be checking for package installed state for userId and 3632 // return null? 3633 return ps.getPermissionsState().computeGids(userId); 3634 } 3635 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3636 final PackageSetting ps = mSettings.mPackages.get(packageName); 3637 if (ps != null && ps.isMatch(flags)) { 3638 return ps.getPermissionsState().computeGids(userId); 3639 } 3640 } 3641 } 3642 3643 return null; 3644 } 3645 3646 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3647 if (bp.perm != null) { 3648 return PackageParser.generatePermissionInfo(bp.perm, flags); 3649 } 3650 PermissionInfo pi = new PermissionInfo(); 3651 pi.name = bp.name; 3652 pi.packageName = bp.sourcePackage; 3653 pi.nonLocalizedLabel = bp.name; 3654 pi.protectionLevel = bp.protectionLevel; 3655 return pi; 3656 } 3657 3658 @Override 3659 public PermissionInfo getPermissionInfo(String name, int flags) { 3660 // reader 3661 synchronized (mPackages) { 3662 final BasePermission p = mSettings.mPermissions.get(name); 3663 if (p != null) { 3664 return generatePermissionInfo(p, flags); 3665 } 3666 return null; 3667 } 3668 } 3669 3670 @Override 3671 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3672 int flags) { 3673 // reader 3674 synchronized (mPackages) { 3675 if (group != null && !mPermissionGroups.containsKey(group)) { 3676 // This is thrown as NameNotFoundException 3677 return null; 3678 } 3679 3680 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3681 for (BasePermission p : mSettings.mPermissions.values()) { 3682 if (group == null) { 3683 if (p.perm == null || p.perm.info.group == null) { 3684 out.add(generatePermissionInfo(p, flags)); 3685 } 3686 } else { 3687 if (p.perm != null && group.equals(p.perm.info.group)) { 3688 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3689 } 3690 } 3691 } 3692 return new ParceledListSlice<>(out); 3693 } 3694 } 3695 3696 @Override 3697 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3698 // reader 3699 synchronized (mPackages) { 3700 return PackageParser.generatePermissionGroupInfo( 3701 mPermissionGroups.get(name), flags); 3702 } 3703 } 3704 3705 @Override 3706 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3707 // reader 3708 synchronized (mPackages) { 3709 final int N = mPermissionGroups.size(); 3710 ArrayList<PermissionGroupInfo> out 3711 = new ArrayList<PermissionGroupInfo>(N); 3712 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3713 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3714 } 3715 return new ParceledListSlice<>(out); 3716 } 3717 } 3718 3719 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3720 int uid, int userId) { 3721 if (!sUserManager.exists(userId)) return null; 3722 PackageSetting ps = mSettings.mPackages.get(packageName); 3723 if (ps != null) { 3724 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3725 return null; 3726 } 3727 if (ps.pkg == null) { 3728 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3729 if (pInfo != null) { 3730 return pInfo.applicationInfo; 3731 } 3732 return null; 3733 } 3734 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3735 ps.readUserState(userId), userId); 3736 if (ai != null) { 3737 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3738 } 3739 return ai; 3740 } 3741 return null; 3742 } 3743 3744 @Override 3745 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3746 if (!sUserManager.exists(userId)) return null; 3747 flags = updateFlagsForApplication(flags, userId, packageName); 3748 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3749 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3750 3751 // writer 3752 synchronized (mPackages) { 3753 // Normalize package name to handle renamed packages and static libs 3754 packageName = resolveInternalPackageNameLPr(packageName, 3755 PackageManager.VERSION_CODE_HIGHEST); 3756 3757 PackageParser.Package p = mPackages.get(packageName); 3758 if (DEBUG_PACKAGE_INFO) Log.v( 3759 TAG, "getApplicationInfo " + packageName 3760 + ": " + p); 3761 if (p != null) { 3762 PackageSetting ps = mSettings.mPackages.get(packageName); 3763 if (ps == null) return null; 3764 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3765 return null; 3766 } 3767 // Note: isEnabledLP() does not apply here - always return info 3768 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3769 p, flags, ps.readUserState(userId), userId); 3770 if (ai != null) { 3771 ai.packageName = resolveExternalPackageNameLPr(p); 3772 } 3773 return ai; 3774 } 3775 if ("android".equals(packageName)||"system".equals(packageName)) { 3776 return mAndroidApplication; 3777 } 3778 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3779 // Already generates the external package name 3780 return generateApplicationInfoFromSettingsLPw(packageName, 3781 Binder.getCallingUid(), flags, userId); 3782 } 3783 } 3784 return null; 3785 } 3786 3787 private String normalizePackageNameLPr(String packageName) { 3788 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3789 return normalizedPackageName != null ? normalizedPackageName : packageName; 3790 } 3791 3792 @Override 3793 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3794 final IPackageDataObserver observer) { 3795 mContext.enforceCallingOrSelfPermission( 3796 android.Manifest.permission.CLEAR_APP_CACHE, null); 3797 mHandler.post(() -> { 3798 boolean success = false; 3799 try { 3800 freeStorage(volumeUuid, freeStorageSize, 0); 3801 success = true; 3802 } catch (IOException e) { 3803 Slog.w(TAG, e); 3804 } 3805 if (observer != null) { 3806 try { 3807 observer.onRemoveCompleted(null, success); 3808 } catch (RemoteException e) { 3809 Slog.w(TAG, e); 3810 } 3811 } 3812 }); 3813 } 3814 3815 @Override 3816 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3817 final IntentSender pi) { 3818 mContext.enforceCallingOrSelfPermission( 3819 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3820 mHandler.post(() -> { 3821 boolean success = false; 3822 try { 3823 freeStorage(volumeUuid, freeStorageSize, 0); 3824 success = true; 3825 } catch (IOException e) { 3826 Slog.w(TAG, e); 3827 } 3828 if (pi != null) { 3829 try { 3830 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3831 } catch (SendIntentException e) { 3832 Slog.w(TAG, e); 3833 } 3834 } 3835 }); 3836 } 3837 3838 /** 3839 * Blocking call to clear various types of cached data across the system 3840 * until the requested bytes are available. 3841 */ 3842 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3843 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3844 final File file = storage.findPathForUuid(volumeUuid); 3845 3846 if (ENABLE_FREE_CACHE_V2) { 3847 final boolean aggressive = (storageFlags 3848 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3849 3850 // 1. Pre-flight to determine if we have any chance to succeed 3851 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3852 3853 // 3. Consider parsed APK data (aggressive only) 3854 if (aggressive) { 3855 FileUtils.deleteContents(mCacheDir); 3856 } 3857 if (file.getUsableSpace() >= bytes) return; 3858 3859 // 4. Consider cached app data (above quotas) 3860 try { 3861 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3862 } catch (InstallerException ignored) { 3863 } 3864 if (file.getUsableSpace() >= bytes) return; 3865 3866 // 5. Consider shared libraries with refcount=0 and age>2h 3867 // 6. Consider dexopt output (aggressive only) 3868 // 7. Consider ephemeral apps not used in last week 3869 3870 // 8. Consider cached app data (below quotas) 3871 try { 3872 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3873 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3874 } catch (InstallerException ignored) { 3875 } 3876 if (file.getUsableSpace() >= bytes) return; 3877 3878 // 9. Consider DropBox entries 3879 // 10. Consider ephemeral cookies 3880 3881 } else { 3882 try { 3883 mInstaller.freeCache(volumeUuid, bytes, 0); 3884 } catch (InstallerException ignored) { 3885 } 3886 if (file.getUsableSpace() >= bytes) return; 3887 } 3888 3889 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3890 } 3891 3892 /** 3893 * Update given flags based on encryption status of current user. 3894 */ 3895 private int updateFlags(int flags, int userId) { 3896 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3897 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3898 // Caller expressed an explicit opinion about what encryption 3899 // aware/unaware components they want to see, so fall through and 3900 // give them what they want 3901 } else { 3902 // Caller expressed no opinion, so match based on user state 3903 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3904 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3905 } else { 3906 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3907 } 3908 } 3909 return flags; 3910 } 3911 3912 private UserManagerInternal getUserManagerInternal() { 3913 if (mUserManagerInternal == null) { 3914 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3915 } 3916 return mUserManagerInternal; 3917 } 3918 3919 private DeviceIdleController.LocalService getDeviceIdleController() { 3920 if (mDeviceIdleController == null) { 3921 mDeviceIdleController = 3922 LocalServices.getService(DeviceIdleController.LocalService.class); 3923 } 3924 return mDeviceIdleController; 3925 } 3926 3927 /** 3928 * Update given flags when being used to request {@link PackageInfo}. 3929 */ 3930 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3931 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3932 boolean triaged = true; 3933 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3934 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3935 // Caller is asking for component details, so they'd better be 3936 // asking for specific encryption matching behavior, or be triaged 3937 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3938 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3939 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3940 triaged = false; 3941 } 3942 } 3943 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3944 | PackageManager.MATCH_SYSTEM_ONLY 3945 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3946 triaged = false; 3947 } 3948 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3949 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3950 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3951 + Debug.getCallers(5)); 3952 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3953 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3954 // If the caller wants all packages and has a restricted profile associated with it, 3955 // then match all users. This is to make sure that launchers that need to access work 3956 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3957 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3958 flags |= PackageManager.MATCH_ANY_USER; 3959 } 3960 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3961 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3962 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3963 } 3964 return updateFlags(flags, userId); 3965 } 3966 3967 /** 3968 * Update given flags when being used to request {@link ApplicationInfo}. 3969 */ 3970 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3971 return updateFlagsForPackage(flags, userId, cookie); 3972 } 3973 3974 /** 3975 * Update given flags when being used to request {@link ComponentInfo}. 3976 */ 3977 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3978 if (cookie instanceof Intent) { 3979 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3980 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3981 } 3982 } 3983 3984 boolean triaged = true; 3985 // Caller is asking for component details, so they'd better be 3986 // asking for specific encryption matching behavior, or be triaged 3987 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3988 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3989 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3990 triaged = false; 3991 } 3992 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3993 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3994 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3995 } 3996 3997 return updateFlags(flags, userId); 3998 } 3999 4000 /** 4001 * Update given intent when being used to request {@link ResolveInfo}. 4002 */ 4003 private Intent updateIntentForResolve(Intent intent) { 4004 if (intent.getSelector() != null) { 4005 intent = intent.getSelector(); 4006 } 4007 if (DEBUG_PREFERRED) { 4008 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4009 } 4010 return intent; 4011 } 4012 4013 /** 4014 * Update given flags when being used to request {@link ResolveInfo}. 4015 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4016 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4017 * flag set. However, this flag is only honoured in three circumstances: 4018 * <ul> 4019 * <li>when called from a system process</li> 4020 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4021 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4022 * action and a {@code android.intent.category.BROWSABLE} category</li> 4023 * </ul> 4024 */ 4025 int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) { 4026 // Safe mode means we shouldn't match any third-party components 4027 if (mSafeMode) { 4028 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4029 } 4030 final int callingUid = Binder.getCallingUid(); 4031 if (getInstantAppPackageName(callingUid) != null) { 4032 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4033 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4034 flags |= PackageManager.MATCH_INSTANT; 4035 } else { 4036 // Otherwise, prevent leaking ephemeral components 4037 final boolean isSpecialProcess = 4038 callingUid == Process.SYSTEM_UID 4039 || callingUid == Process.SHELL_UID 4040 || callingUid == 0; 4041 final boolean allowMatchInstant = 4042 (includeInstantApp 4043 && Intent.ACTION_VIEW.equals(intent.getAction()) 4044 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4045 && hasWebURI(intent)) 4046 || isSpecialProcess 4047 || mContext.checkCallingOrSelfPermission( 4048 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4049 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4050 if (!allowMatchInstant) { 4051 flags &= ~PackageManager.MATCH_INSTANT; 4052 } 4053 } 4054 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4055 } 4056 4057 @Override 4058 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4059 if (!sUserManager.exists(userId)) return null; 4060 flags = updateFlagsForComponent(flags, userId, component); 4061 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4062 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4063 synchronized (mPackages) { 4064 PackageParser.Activity a = mActivities.mActivities.get(component); 4065 4066 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4067 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4068 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4069 if (ps == null) return null; 4070 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4071 userId); 4072 } 4073 if (mResolveComponentName.equals(component)) { 4074 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4075 new PackageUserState(), userId); 4076 } 4077 } 4078 return null; 4079 } 4080 4081 @Override 4082 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4083 String resolvedType) { 4084 synchronized (mPackages) { 4085 if (component.equals(mResolveComponentName)) { 4086 // The resolver supports EVERYTHING! 4087 return true; 4088 } 4089 PackageParser.Activity a = mActivities.mActivities.get(component); 4090 if (a == null) { 4091 return false; 4092 } 4093 for (int i=0; i<a.intents.size(); i++) { 4094 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4095 intent.getData(), intent.getCategories(), TAG) >= 0) { 4096 return true; 4097 } 4098 } 4099 return false; 4100 } 4101 } 4102 4103 @Override 4104 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4105 if (!sUserManager.exists(userId)) return null; 4106 flags = updateFlagsForComponent(flags, userId, component); 4107 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4108 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4109 synchronized (mPackages) { 4110 PackageParser.Activity a = mReceivers.mActivities.get(component); 4111 if (DEBUG_PACKAGE_INFO) Log.v( 4112 TAG, "getReceiverInfo " + component + ": " + a); 4113 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4114 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4115 if (ps == null) return null; 4116 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4117 userId); 4118 } 4119 } 4120 return null; 4121 } 4122 4123 @Override 4124 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4125 if (!sUserManager.exists(userId)) return null; 4126 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4127 4128 flags = updateFlagsForPackage(flags, userId, null); 4129 4130 final boolean canSeeStaticLibraries = 4131 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4132 == PERMISSION_GRANTED 4133 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4134 == PERMISSION_GRANTED 4135 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4136 == PERMISSION_GRANTED 4137 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4138 == PERMISSION_GRANTED; 4139 4140 synchronized (mPackages) { 4141 List<SharedLibraryInfo> result = null; 4142 4143 final int libCount = mSharedLibraries.size(); 4144 for (int i = 0; i < libCount; i++) { 4145 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4146 if (versionedLib == null) { 4147 continue; 4148 } 4149 4150 final int versionCount = versionedLib.size(); 4151 for (int j = 0; j < versionCount; j++) { 4152 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4153 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4154 break; 4155 } 4156 final long identity = Binder.clearCallingIdentity(); 4157 try { 4158 // TODO: We will change version code to long, so in the new API it is long 4159 PackageInfo packageInfo = getPackageInfoVersioned( 4160 libInfo.getDeclaringPackage(), flags, userId); 4161 if (packageInfo == null) { 4162 continue; 4163 } 4164 } finally { 4165 Binder.restoreCallingIdentity(identity); 4166 } 4167 4168 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4169 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4170 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4171 4172 if (result == null) { 4173 result = new ArrayList<>(); 4174 } 4175 result.add(resLibInfo); 4176 } 4177 } 4178 4179 return result != null ? new ParceledListSlice<>(result) : null; 4180 } 4181 } 4182 4183 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4184 SharedLibraryInfo libInfo, int flags, int userId) { 4185 List<VersionedPackage> versionedPackages = null; 4186 final int packageCount = mSettings.mPackages.size(); 4187 for (int i = 0; i < packageCount; i++) { 4188 PackageSetting ps = mSettings.mPackages.valueAt(i); 4189 4190 if (ps == null) { 4191 continue; 4192 } 4193 4194 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4195 continue; 4196 } 4197 4198 final String libName = libInfo.getName(); 4199 if (libInfo.isStatic()) { 4200 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4201 if (libIdx < 0) { 4202 continue; 4203 } 4204 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4205 continue; 4206 } 4207 if (versionedPackages == null) { 4208 versionedPackages = new ArrayList<>(); 4209 } 4210 // If the dependent is a static shared lib, use the public package name 4211 String dependentPackageName = ps.name; 4212 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4213 dependentPackageName = ps.pkg.manifestPackageName; 4214 } 4215 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4216 } else if (ps.pkg != null) { 4217 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4218 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4219 if (versionedPackages == null) { 4220 versionedPackages = new ArrayList<>(); 4221 } 4222 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4223 } 4224 } 4225 } 4226 4227 return versionedPackages; 4228 } 4229 4230 @Override 4231 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4232 if (!sUserManager.exists(userId)) return null; 4233 flags = updateFlagsForComponent(flags, userId, component); 4234 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4235 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4236 synchronized (mPackages) { 4237 PackageParser.Service s = mServices.mServices.get(component); 4238 if (DEBUG_PACKAGE_INFO) Log.v( 4239 TAG, "getServiceInfo " + component + ": " + s); 4240 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4241 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4242 if (ps == null) return null; 4243 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4244 userId); 4245 } 4246 } 4247 return null; 4248 } 4249 4250 @Override 4251 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4252 if (!sUserManager.exists(userId)) return null; 4253 flags = updateFlagsForComponent(flags, userId, component); 4254 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4255 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4256 synchronized (mPackages) { 4257 PackageParser.Provider p = mProviders.mProviders.get(component); 4258 if (DEBUG_PACKAGE_INFO) Log.v( 4259 TAG, "getProviderInfo " + component + ": " + p); 4260 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4261 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4262 if (ps == null) return null; 4263 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4264 userId); 4265 } 4266 } 4267 return null; 4268 } 4269 4270 @Override 4271 public String[] getSystemSharedLibraryNames() { 4272 synchronized (mPackages) { 4273 Set<String> libs = null; 4274 final int libCount = mSharedLibraries.size(); 4275 for (int i = 0; i < libCount; i++) { 4276 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4277 if (versionedLib == null) { 4278 continue; 4279 } 4280 final int versionCount = versionedLib.size(); 4281 for (int j = 0; j < versionCount; j++) { 4282 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4283 if (!libEntry.info.isStatic()) { 4284 if (libs == null) { 4285 libs = new ArraySet<>(); 4286 } 4287 libs.add(libEntry.info.getName()); 4288 break; 4289 } 4290 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4291 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4292 UserHandle.getUserId(Binder.getCallingUid()))) { 4293 if (libs == null) { 4294 libs = new ArraySet<>(); 4295 } 4296 libs.add(libEntry.info.getName()); 4297 break; 4298 } 4299 } 4300 } 4301 4302 if (libs != null) { 4303 String[] libsArray = new String[libs.size()]; 4304 libs.toArray(libsArray); 4305 return libsArray; 4306 } 4307 4308 return null; 4309 } 4310 } 4311 4312 @Override 4313 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4314 synchronized (mPackages) { 4315 return mServicesSystemSharedLibraryPackageName; 4316 } 4317 } 4318 4319 @Override 4320 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4321 synchronized (mPackages) { 4322 return mSharedSystemSharedLibraryPackageName; 4323 } 4324 } 4325 4326 private void updateSequenceNumberLP(String packageName, int[] userList) { 4327 for (int i = userList.length - 1; i >= 0; --i) { 4328 final int userId = userList[i]; 4329 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4330 if (changedPackages == null) { 4331 changedPackages = new SparseArray<>(); 4332 mChangedPackages.put(userId, changedPackages); 4333 } 4334 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4335 if (sequenceNumbers == null) { 4336 sequenceNumbers = new HashMap<>(); 4337 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4338 } 4339 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4340 if (sequenceNumber != null) { 4341 changedPackages.remove(sequenceNumber); 4342 } 4343 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4344 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4345 } 4346 mChangedPackagesSequenceNumber++; 4347 } 4348 4349 @Override 4350 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4351 synchronized (mPackages) { 4352 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4353 return null; 4354 } 4355 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4356 if (changedPackages == null) { 4357 return null; 4358 } 4359 final List<String> packageNames = 4360 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4361 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4362 final String packageName = changedPackages.get(i); 4363 if (packageName != null) { 4364 packageNames.add(packageName); 4365 } 4366 } 4367 return packageNames.isEmpty() 4368 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4369 } 4370 } 4371 4372 @Override 4373 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4374 ArrayList<FeatureInfo> res; 4375 synchronized (mAvailableFeatures) { 4376 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4377 res.addAll(mAvailableFeatures.values()); 4378 } 4379 final FeatureInfo fi = new FeatureInfo(); 4380 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4381 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4382 res.add(fi); 4383 4384 return new ParceledListSlice<>(res); 4385 } 4386 4387 @Override 4388 public boolean hasSystemFeature(String name, int version) { 4389 synchronized (mAvailableFeatures) { 4390 final FeatureInfo feat = mAvailableFeatures.get(name); 4391 if (feat == null) { 4392 return false; 4393 } else { 4394 return feat.version >= version; 4395 } 4396 } 4397 } 4398 4399 @Override 4400 public int checkPermission(String permName, String pkgName, int userId) { 4401 if (!sUserManager.exists(userId)) { 4402 return PackageManager.PERMISSION_DENIED; 4403 } 4404 4405 synchronized (mPackages) { 4406 final PackageParser.Package p = mPackages.get(pkgName); 4407 if (p != null && p.mExtras != null) { 4408 final PackageSetting ps = (PackageSetting) p.mExtras; 4409 final PermissionsState permissionsState = ps.getPermissionsState(); 4410 if (permissionsState.hasPermission(permName, userId)) { 4411 return PackageManager.PERMISSION_GRANTED; 4412 } 4413 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4414 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4415 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4416 return PackageManager.PERMISSION_GRANTED; 4417 } 4418 } 4419 } 4420 4421 return PackageManager.PERMISSION_DENIED; 4422 } 4423 4424 @Override 4425 public int checkUidPermission(String permName, int uid) { 4426 final int userId = UserHandle.getUserId(uid); 4427 4428 if (!sUserManager.exists(userId)) { 4429 return PackageManager.PERMISSION_DENIED; 4430 } 4431 4432 synchronized (mPackages) { 4433 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4434 if (obj != null) { 4435 final SettingBase ps = (SettingBase) obj; 4436 final PermissionsState permissionsState = ps.getPermissionsState(); 4437 if (permissionsState.hasPermission(permName, userId)) { 4438 return PackageManager.PERMISSION_GRANTED; 4439 } 4440 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4441 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4442 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4443 return PackageManager.PERMISSION_GRANTED; 4444 } 4445 } else { 4446 ArraySet<String> perms = mSystemPermissions.get(uid); 4447 if (perms != null) { 4448 if (perms.contains(permName)) { 4449 return PackageManager.PERMISSION_GRANTED; 4450 } 4451 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4452 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4453 return PackageManager.PERMISSION_GRANTED; 4454 } 4455 } 4456 } 4457 } 4458 4459 return PackageManager.PERMISSION_DENIED; 4460 } 4461 4462 @Override 4463 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4464 if (UserHandle.getCallingUserId() != userId) { 4465 mContext.enforceCallingPermission( 4466 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4467 "isPermissionRevokedByPolicy for user " + userId); 4468 } 4469 4470 if (checkPermission(permission, packageName, userId) 4471 == PackageManager.PERMISSION_GRANTED) { 4472 return false; 4473 } 4474 4475 final long identity = Binder.clearCallingIdentity(); 4476 try { 4477 final int flags = getPermissionFlags(permission, packageName, userId); 4478 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4479 } finally { 4480 Binder.restoreCallingIdentity(identity); 4481 } 4482 } 4483 4484 @Override 4485 public String getPermissionControllerPackageName() { 4486 synchronized (mPackages) { 4487 return mRequiredInstallerPackage; 4488 } 4489 } 4490 4491 /** 4492 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4493 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4494 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4495 * @param message the message to log on security exception 4496 */ 4497 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4498 boolean checkShell, String message) { 4499 if (userId < 0) { 4500 throw new IllegalArgumentException("Invalid userId " + userId); 4501 } 4502 if (checkShell) { 4503 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4504 } 4505 if (userId == UserHandle.getUserId(callingUid)) return; 4506 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4507 if (requireFullPermission) { 4508 mContext.enforceCallingOrSelfPermission( 4509 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4510 } else { 4511 try { 4512 mContext.enforceCallingOrSelfPermission( 4513 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4514 } catch (SecurityException se) { 4515 mContext.enforceCallingOrSelfPermission( 4516 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4517 } 4518 } 4519 } 4520 } 4521 4522 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4523 if (callingUid == Process.SHELL_UID) { 4524 if (userHandle >= 0 4525 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4526 throw new SecurityException("Shell does not have permission to access user " 4527 + userHandle); 4528 } else if (userHandle < 0) { 4529 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4530 + Debug.getCallers(3)); 4531 } 4532 } 4533 } 4534 4535 private BasePermission findPermissionTreeLP(String permName) { 4536 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4537 if (permName.startsWith(bp.name) && 4538 permName.length() > bp.name.length() && 4539 permName.charAt(bp.name.length()) == '.') { 4540 return bp; 4541 } 4542 } 4543 return null; 4544 } 4545 4546 private BasePermission checkPermissionTreeLP(String permName) { 4547 if (permName != null) { 4548 BasePermission bp = findPermissionTreeLP(permName); 4549 if (bp != null) { 4550 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4551 return bp; 4552 } 4553 throw new SecurityException("Calling uid " 4554 + Binder.getCallingUid() 4555 + " is not allowed to add to permission tree " 4556 + bp.name + " owned by uid " + bp.uid); 4557 } 4558 } 4559 throw new SecurityException("No permission tree found for " + permName); 4560 } 4561 4562 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4563 if (s1 == null) { 4564 return s2 == null; 4565 } 4566 if (s2 == null) { 4567 return false; 4568 } 4569 if (s1.getClass() != s2.getClass()) { 4570 return false; 4571 } 4572 return s1.equals(s2); 4573 } 4574 4575 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4576 if (pi1.icon != pi2.icon) return false; 4577 if (pi1.logo != pi2.logo) return false; 4578 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4579 if (!compareStrings(pi1.name, pi2.name)) return false; 4580 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4581 // We'll take care of setting this one. 4582 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4583 // These are not currently stored in settings. 4584 //if (!compareStrings(pi1.group, pi2.group)) return false; 4585 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4586 //if (pi1.labelRes != pi2.labelRes) return false; 4587 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4588 return true; 4589 } 4590 4591 int permissionInfoFootprint(PermissionInfo info) { 4592 int size = info.name.length(); 4593 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4594 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4595 return size; 4596 } 4597 4598 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4599 int size = 0; 4600 for (BasePermission perm : mSettings.mPermissions.values()) { 4601 if (perm.uid == tree.uid) { 4602 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4603 } 4604 } 4605 return size; 4606 } 4607 4608 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4609 // We calculate the max size of permissions defined by this uid and throw 4610 // if that plus the size of 'info' would exceed our stated maximum. 4611 if (tree.uid != Process.SYSTEM_UID) { 4612 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4613 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4614 throw new SecurityException("Permission tree size cap exceeded"); 4615 } 4616 } 4617 } 4618 4619 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4620 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4621 throw new SecurityException("Label must be specified in permission"); 4622 } 4623 BasePermission tree = checkPermissionTreeLP(info.name); 4624 BasePermission bp = mSettings.mPermissions.get(info.name); 4625 boolean added = bp == null; 4626 boolean changed = true; 4627 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4628 if (added) { 4629 enforcePermissionCapLocked(info, tree); 4630 bp = new BasePermission(info.name, tree.sourcePackage, 4631 BasePermission.TYPE_DYNAMIC); 4632 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4633 throw new SecurityException( 4634 "Not allowed to modify non-dynamic permission " 4635 + info.name); 4636 } else { 4637 if (bp.protectionLevel == fixedLevel 4638 && bp.perm.owner.equals(tree.perm.owner) 4639 && bp.uid == tree.uid 4640 && comparePermissionInfos(bp.perm.info, info)) { 4641 changed = false; 4642 } 4643 } 4644 bp.protectionLevel = fixedLevel; 4645 info = new PermissionInfo(info); 4646 info.protectionLevel = fixedLevel; 4647 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4648 bp.perm.info.packageName = tree.perm.info.packageName; 4649 bp.uid = tree.uid; 4650 if (added) { 4651 mSettings.mPermissions.put(info.name, bp); 4652 } 4653 if (changed) { 4654 if (!async) { 4655 mSettings.writeLPr(); 4656 } else { 4657 scheduleWriteSettingsLocked(); 4658 } 4659 } 4660 return added; 4661 } 4662 4663 @Override 4664 public boolean addPermission(PermissionInfo info) { 4665 synchronized (mPackages) { 4666 return addPermissionLocked(info, false); 4667 } 4668 } 4669 4670 @Override 4671 public boolean addPermissionAsync(PermissionInfo info) { 4672 synchronized (mPackages) { 4673 return addPermissionLocked(info, true); 4674 } 4675 } 4676 4677 @Override 4678 public void removePermission(String name) { 4679 synchronized (mPackages) { 4680 checkPermissionTreeLP(name); 4681 BasePermission bp = mSettings.mPermissions.get(name); 4682 if (bp != null) { 4683 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4684 throw new SecurityException( 4685 "Not allowed to modify non-dynamic permission " 4686 + name); 4687 } 4688 mSettings.mPermissions.remove(name); 4689 mSettings.writeLPr(); 4690 } 4691 } 4692 } 4693 4694 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4695 BasePermission bp) { 4696 int index = pkg.requestedPermissions.indexOf(bp.name); 4697 if (index == -1) { 4698 throw new SecurityException("Package " + pkg.packageName 4699 + " has not requested permission " + bp.name); 4700 } 4701 if (!bp.isRuntime() && !bp.isDevelopment()) { 4702 throw new SecurityException("Permission " + bp.name 4703 + " is not a changeable permission type"); 4704 } 4705 } 4706 4707 @Override 4708 public void grantRuntimePermission(String packageName, String name, final int userId) { 4709 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4710 } 4711 4712 private void grantRuntimePermission(String packageName, String name, final int userId, 4713 boolean overridePolicy) { 4714 if (!sUserManager.exists(userId)) { 4715 Log.e(TAG, "No such user:" + userId); 4716 return; 4717 } 4718 4719 mContext.enforceCallingOrSelfPermission( 4720 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4721 "grantRuntimePermission"); 4722 4723 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4724 true /* requireFullPermission */, true /* checkShell */, 4725 "grantRuntimePermission"); 4726 4727 final int uid; 4728 final SettingBase sb; 4729 4730 synchronized (mPackages) { 4731 final PackageParser.Package pkg = mPackages.get(packageName); 4732 if (pkg == null) { 4733 throw new IllegalArgumentException("Unknown package: " + packageName); 4734 } 4735 4736 final BasePermission bp = mSettings.mPermissions.get(name); 4737 if (bp == null) { 4738 throw new IllegalArgumentException("Unknown permission: " + name); 4739 } 4740 4741 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4742 4743 // If a permission review is required for legacy apps we represent 4744 // their permissions as always granted runtime ones since we need 4745 // to keep the review required permission flag per user while an 4746 // install permission's state is shared across all users. 4747 if (mPermissionReviewRequired 4748 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4749 && bp.isRuntime()) { 4750 return; 4751 } 4752 4753 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4754 sb = (SettingBase) pkg.mExtras; 4755 if (sb == null) { 4756 throw new IllegalArgumentException("Unknown package: " + packageName); 4757 } 4758 4759 final PermissionsState permissionsState = sb.getPermissionsState(); 4760 4761 final int flags = permissionsState.getPermissionFlags(name, userId); 4762 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4763 throw new SecurityException("Cannot grant system fixed permission " 4764 + name + " for package " + packageName); 4765 } 4766 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4767 throw new SecurityException("Cannot grant policy fixed permission " 4768 + name + " for package " + packageName); 4769 } 4770 4771 if (bp.isDevelopment()) { 4772 // Development permissions must be handled specially, since they are not 4773 // normal runtime permissions. For now they apply to all users. 4774 if (permissionsState.grantInstallPermission(bp) != 4775 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4776 scheduleWriteSettingsLocked(); 4777 } 4778 return; 4779 } 4780 4781 final PackageSetting ps = mSettings.mPackages.get(packageName); 4782 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4783 throw new SecurityException("Cannot grant non-ephemeral permission" 4784 + name + " for package " + packageName); 4785 } 4786 4787 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4788 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4789 return; 4790 } 4791 4792 final int result = permissionsState.grantRuntimePermission(bp, userId); 4793 switch (result) { 4794 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4795 return; 4796 } 4797 4798 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4799 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4800 mHandler.post(new Runnable() { 4801 @Override 4802 public void run() { 4803 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4804 } 4805 }); 4806 } 4807 break; 4808 } 4809 4810 if (bp.isRuntime()) { 4811 logPermissionGranted(mContext, name, packageName); 4812 } 4813 4814 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4815 4816 // Not critical if that is lost - app has to request again. 4817 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4818 } 4819 4820 // Only need to do this if user is initialized. Otherwise it's a new user 4821 // and there are no processes running as the user yet and there's no need 4822 // to make an expensive call to remount processes for the changed permissions. 4823 if (READ_EXTERNAL_STORAGE.equals(name) 4824 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4825 final long token = Binder.clearCallingIdentity(); 4826 try { 4827 if (sUserManager.isInitialized(userId)) { 4828 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4829 StorageManagerInternal.class); 4830 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4831 } 4832 } finally { 4833 Binder.restoreCallingIdentity(token); 4834 } 4835 } 4836 } 4837 4838 @Override 4839 public void revokeRuntimePermission(String packageName, String name, int userId) { 4840 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4841 } 4842 4843 private void revokeRuntimePermission(String packageName, String name, int userId, 4844 boolean overridePolicy) { 4845 if (!sUserManager.exists(userId)) { 4846 Log.e(TAG, "No such user:" + userId); 4847 return; 4848 } 4849 4850 mContext.enforceCallingOrSelfPermission( 4851 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4852 "revokeRuntimePermission"); 4853 4854 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4855 true /* requireFullPermission */, true /* checkShell */, 4856 "revokeRuntimePermission"); 4857 4858 final int appId; 4859 4860 synchronized (mPackages) { 4861 final PackageParser.Package pkg = mPackages.get(packageName); 4862 if (pkg == null) { 4863 throw new IllegalArgumentException("Unknown package: " + packageName); 4864 } 4865 4866 final BasePermission bp = mSettings.mPermissions.get(name); 4867 if (bp == null) { 4868 throw new IllegalArgumentException("Unknown permission: " + name); 4869 } 4870 4871 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4872 4873 // If a permission review is required for legacy apps we represent 4874 // their permissions as always granted runtime ones since we need 4875 // to keep the review required permission flag per user while an 4876 // install permission's state is shared across all users. 4877 if (mPermissionReviewRequired 4878 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4879 && bp.isRuntime()) { 4880 return; 4881 } 4882 4883 SettingBase sb = (SettingBase) pkg.mExtras; 4884 if (sb == null) { 4885 throw new IllegalArgumentException("Unknown package: " + packageName); 4886 } 4887 4888 final PermissionsState permissionsState = sb.getPermissionsState(); 4889 4890 final int flags = permissionsState.getPermissionFlags(name, userId); 4891 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4892 throw new SecurityException("Cannot revoke system fixed permission " 4893 + name + " for package " + packageName); 4894 } 4895 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4896 throw new SecurityException("Cannot revoke policy fixed permission " 4897 + name + " for package " + packageName); 4898 } 4899 4900 if (bp.isDevelopment()) { 4901 // Development permissions must be handled specially, since they are not 4902 // normal runtime permissions. For now they apply to all users. 4903 if (permissionsState.revokeInstallPermission(bp) != 4904 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4905 scheduleWriteSettingsLocked(); 4906 } 4907 return; 4908 } 4909 4910 if (permissionsState.revokeRuntimePermission(bp, userId) == 4911 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4912 return; 4913 } 4914 4915 if (bp.isRuntime()) { 4916 logPermissionRevoked(mContext, name, packageName); 4917 } 4918 4919 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4920 4921 // Critical, after this call app should never have the permission. 4922 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4923 4924 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4925 } 4926 4927 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4928 } 4929 4930 /** 4931 * Get the first event id for the permission. 4932 * 4933 * <p>There are four events for each permission: <ul> 4934 * <li>Request permission: first id + 0</li> 4935 * <li>Grant permission: first id + 1</li> 4936 * <li>Request for permission denied: first id + 2</li> 4937 * <li>Revoke permission: first id + 3</li> 4938 * </ul></p> 4939 * 4940 * @param name name of the permission 4941 * 4942 * @return The first event id for the permission 4943 */ 4944 private static int getBaseEventId(@NonNull String name) { 4945 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4946 4947 if (eventIdIndex == -1) { 4948 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4949 || "user".equals(Build.TYPE)) { 4950 Log.i(TAG, "Unknown permission " + name); 4951 4952 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4953 } else { 4954 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4955 // 4956 // Also update 4957 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4958 // - metrics_constants.proto 4959 throw new IllegalStateException("Unknown permission " + name); 4960 } 4961 } 4962 4963 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4964 } 4965 4966 /** 4967 * Log that a permission was revoked. 4968 * 4969 * @param context Context of the caller 4970 * @param name name of the permission 4971 * @param packageName package permission if for 4972 */ 4973 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4974 @NonNull String packageName) { 4975 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4976 } 4977 4978 /** 4979 * Log that a permission request was granted. 4980 * 4981 * @param context Context of the caller 4982 * @param name name of the permission 4983 * @param packageName package permission if for 4984 */ 4985 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4986 @NonNull String packageName) { 4987 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4988 } 4989 4990 @Override 4991 public void resetRuntimePermissions() { 4992 mContext.enforceCallingOrSelfPermission( 4993 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4994 "revokeRuntimePermission"); 4995 4996 int callingUid = Binder.getCallingUid(); 4997 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4998 mContext.enforceCallingOrSelfPermission( 4999 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5000 "resetRuntimePermissions"); 5001 } 5002 5003 synchronized (mPackages) { 5004 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5005 for (int userId : UserManagerService.getInstance().getUserIds()) { 5006 final int packageCount = mPackages.size(); 5007 for (int i = 0; i < packageCount; i++) { 5008 PackageParser.Package pkg = mPackages.valueAt(i); 5009 if (!(pkg.mExtras instanceof PackageSetting)) { 5010 continue; 5011 } 5012 PackageSetting ps = (PackageSetting) pkg.mExtras; 5013 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5014 } 5015 } 5016 } 5017 } 5018 5019 @Override 5020 public int getPermissionFlags(String name, String packageName, int userId) { 5021 if (!sUserManager.exists(userId)) { 5022 return 0; 5023 } 5024 5025 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5026 5027 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5028 true /* requireFullPermission */, false /* checkShell */, 5029 "getPermissionFlags"); 5030 5031 synchronized (mPackages) { 5032 final PackageParser.Package pkg = mPackages.get(packageName); 5033 if (pkg == null) { 5034 return 0; 5035 } 5036 5037 final BasePermission bp = mSettings.mPermissions.get(name); 5038 if (bp == null) { 5039 return 0; 5040 } 5041 5042 SettingBase sb = (SettingBase) pkg.mExtras; 5043 if (sb == null) { 5044 return 0; 5045 } 5046 5047 PermissionsState permissionsState = sb.getPermissionsState(); 5048 return permissionsState.getPermissionFlags(name, userId); 5049 } 5050 } 5051 5052 @Override 5053 public void updatePermissionFlags(String name, String packageName, int flagMask, 5054 int flagValues, int userId) { 5055 if (!sUserManager.exists(userId)) { 5056 return; 5057 } 5058 5059 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5060 5061 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5062 true /* requireFullPermission */, true /* checkShell */, 5063 "updatePermissionFlags"); 5064 5065 // Only the system can change these flags and nothing else. 5066 if (getCallingUid() != Process.SYSTEM_UID) { 5067 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5068 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5069 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5070 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5071 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5072 } 5073 5074 synchronized (mPackages) { 5075 final PackageParser.Package pkg = mPackages.get(packageName); 5076 if (pkg == null) { 5077 throw new IllegalArgumentException("Unknown package: " + packageName); 5078 } 5079 5080 final BasePermission bp = mSettings.mPermissions.get(name); 5081 if (bp == null) { 5082 throw new IllegalArgumentException("Unknown permission: " + name); 5083 } 5084 5085 SettingBase sb = (SettingBase) pkg.mExtras; 5086 if (sb == null) { 5087 throw new IllegalArgumentException("Unknown package: " + packageName); 5088 } 5089 5090 PermissionsState permissionsState = sb.getPermissionsState(); 5091 5092 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5093 5094 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5095 // Install and runtime permissions are stored in different places, 5096 // so figure out what permission changed and persist the change. 5097 if (permissionsState.getInstallPermissionState(name) != null) { 5098 scheduleWriteSettingsLocked(); 5099 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5100 || hadState) { 5101 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5102 } 5103 } 5104 } 5105 } 5106 5107 /** 5108 * Update the permission flags for all packages and runtime permissions of a user in order 5109 * to allow device or profile owner to remove POLICY_FIXED. 5110 */ 5111 @Override 5112 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5113 if (!sUserManager.exists(userId)) { 5114 return; 5115 } 5116 5117 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5118 5119 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5120 true /* requireFullPermission */, true /* checkShell */, 5121 "updatePermissionFlagsForAllApps"); 5122 5123 // Only the system can change system fixed flags. 5124 if (getCallingUid() != Process.SYSTEM_UID) { 5125 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5126 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5127 } 5128 5129 synchronized (mPackages) { 5130 boolean changed = false; 5131 final int packageCount = mPackages.size(); 5132 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5133 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5134 SettingBase sb = (SettingBase) pkg.mExtras; 5135 if (sb == null) { 5136 continue; 5137 } 5138 PermissionsState permissionsState = sb.getPermissionsState(); 5139 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5140 userId, flagMask, flagValues); 5141 } 5142 if (changed) { 5143 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5144 } 5145 } 5146 } 5147 5148 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5149 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5150 != PackageManager.PERMISSION_GRANTED 5151 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5152 != PackageManager.PERMISSION_GRANTED) { 5153 throw new SecurityException(message + " requires " 5154 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5155 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5156 } 5157 } 5158 5159 @Override 5160 public boolean shouldShowRequestPermissionRationale(String permissionName, 5161 String packageName, int userId) { 5162 if (UserHandle.getCallingUserId() != userId) { 5163 mContext.enforceCallingPermission( 5164 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5165 "canShowRequestPermissionRationale for user " + userId); 5166 } 5167 5168 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5169 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5170 return false; 5171 } 5172 5173 if (checkPermission(permissionName, packageName, userId) 5174 == PackageManager.PERMISSION_GRANTED) { 5175 return false; 5176 } 5177 5178 final int flags; 5179 5180 final long identity = Binder.clearCallingIdentity(); 5181 try { 5182 flags = getPermissionFlags(permissionName, 5183 packageName, userId); 5184 } finally { 5185 Binder.restoreCallingIdentity(identity); 5186 } 5187 5188 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5189 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5190 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5191 5192 if ((flags & fixedFlags) != 0) { 5193 return false; 5194 } 5195 5196 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5197 } 5198 5199 @Override 5200 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5201 mContext.enforceCallingOrSelfPermission( 5202 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5203 "addOnPermissionsChangeListener"); 5204 5205 synchronized (mPackages) { 5206 mOnPermissionChangeListeners.addListenerLocked(listener); 5207 } 5208 } 5209 5210 @Override 5211 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5212 synchronized (mPackages) { 5213 mOnPermissionChangeListeners.removeListenerLocked(listener); 5214 } 5215 } 5216 5217 @Override 5218 public boolean isProtectedBroadcast(String actionName) { 5219 synchronized (mPackages) { 5220 if (mProtectedBroadcasts.contains(actionName)) { 5221 return true; 5222 } else if (actionName != null) { 5223 // TODO: remove these terrible hacks 5224 if (actionName.startsWith("android.net.netmon.lingerExpired") 5225 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5226 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5227 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5228 return true; 5229 } 5230 } 5231 } 5232 return false; 5233 } 5234 5235 @Override 5236 public int checkSignatures(String pkg1, String pkg2) { 5237 synchronized (mPackages) { 5238 final PackageParser.Package p1 = mPackages.get(pkg1); 5239 final PackageParser.Package p2 = mPackages.get(pkg2); 5240 if (p1 == null || p1.mExtras == null 5241 || p2 == null || p2.mExtras == null) { 5242 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5243 } 5244 return compareSignatures(p1.mSignatures, p2.mSignatures); 5245 } 5246 } 5247 5248 @Override 5249 public int checkUidSignatures(int uid1, int uid2) { 5250 // Map to base uids. 5251 uid1 = UserHandle.getAppId(uid1); 5252 uid2 = UserHandle.getAppId(uid2); 5253 // reader 5254 synchronized (mPackages) { 5255 Signature[] s1; 5256 Signature[] s2; 5257 Object obj = mSettings.getUserIdLPr(uid1); 5258 if (obj != null) { 5259 if (obj instanceof SharedUserSetting) { 5260 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5261 } else if (obj instanceof PackageSetting) { 5262 s1 = ((PackageSetting)obj).signatures.mSignatures; 5263 } else { 5264 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5265 } 5266 } else { 5267 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5268 } 5269 obj = mSettings.getUserIdLPr(uid2); 5270 if (obj != null) { 5271 if (obj instanceof SharedUserSetting) { 5272 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5273 } else if (obj instanceof PackageSetting) { 5274 s2 = ((PackageSetting)obj).signatures.mSignatures; 5275 } else { 5276 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5277 } 5278 } else { 5279 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5280 } 5281 return compareSignatures(s1, s2); 5282 } 5283 } 5284 5285 /** 5286 * This method should typically only be used when granting or revoking 5287 * permissions, since the app may immediately restart after this call. 5288 * <p> 5289 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5290 * guard your work against the app being relaunched. 5291 */ 5292 private void killUid(int appId, int userId, String reason) { 5293 final long identity = Binder.clearCallingIdentity(); 5294 try { 5295 IActivityManager am = ActivityManager.getService(); 5296 if (am != null) { 5297 try { 5298 am.killUid(appId, userId, reason); 5299 } catch (RemoteException e) { 5300 /* ignore - same process */ 5301 } 5302 } 5303 } finally { 5304 Binder.restoreCallingIdentity(identity); 5305 } 5306 } 5307 5308 /** 5309 * Compares two sets of signatures. Returns: 5310 * <br /> 5311 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5312 * <br /> 5313 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5314 * <br /> 5315 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5316 * <br /> 5317 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5318 * <br /> 5319 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5320 */ 5321 static int compareSignatures(Signature[] s1, Signature[] s2) { 5322 if (s1 == null) { 5323 return s2 == null 5324 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5325 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5326 } 5327 5328 if (s2 == null) { 5329 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5330 } 5331 5332 if (s1.length != s2.length) { 5333 return PackageManager.SIGNATURE_NO_MATCH; 5334 } 5335 5336 // Since both signature sets are of size 1, we can compare without HashSets. 5337 if (s1.length == 1) { 5338 return s1[0].equals(s2[0]) ? 5339 PackageManager.SIGNATURE_MATCH : 5340 PackageManager.SIGNATURE_NO_MATCH; 5341 } 5342 5343 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5344 for (Signature sig : s1) { 5345 set1.add(sig); 5346 } 5347 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5348 for (Signature sig : s2) { 5349 set2.add(sig); 5350 } 5351 // Make sure s2 contains all signatures in s1. 5352 if (set1.equals(set2)) { 5353 return PackageManager.SIGNATURE_MATCH; 5354 } 5355 return PackageManager.SIGNATURE_NO_MATCH; 5356 } 5357 5358 /** 5359 * If the database version for this type of package (internal storage or 5360 * external storage) is less than the version where package signatures 5361 * were updated, return true. 5362 */ 5363 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5364 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5365 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5366 } 5367 5368 /** 5369 * Used for backward compatibility to make sure any packages with 5370 * certificate chains get upgraded to the new style. {@code existingSigs} 5371 * will be in the old format (since they were stored on disk from before the 5372 * system upgrade) and {@code scannedSigs} will be in the newer format. 5373 */ 5374 private int compareSignaturesCompat(PackageSignatures existingSigs, 5375 PackageParser.Package scannedPkg) { 5376 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5377 return PackageManager.SIGNATURE_NO_MATCH; 5378 } 5379 5380 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5381 for (Signature sig : existingSigs.mSignatures) { 5382 existingSet.add(sig); 5383 } 5384 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5385 for (Signature sig : scannedPkg.mSignatures) { 5386 try { 5387 Signature[] chainSignatures = sig.getChainSignatures(); 5388 for (Signature chainSig : chainSignatures) { 5389 scannedCompatSet.add(chainSig); 5390 } 5391 } catch (CertificateEncodingException e) { 5392 scannedCompatSet.add(sig); 5393 } 5394 } 5395 /* 5396 * Make sure the expanded scanned set contains all signatures in the 5397 * existing one. 5398 */ 5399 if (scannedCompatSet.equals(existingSet)) { 5400 // Migrate the old signatures to the new scheme. 5401 existingSigs.assignSignatures(scannedPkg.mSignatures); 5402 // The new KeySets will be re-added later in the scanning process. 5403 synchronized (mPackages) { 5404 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5405 } 5406 return PackageManager.SIGNATURE_MATCH; 5407 } 5408 return PackageManager.SIGNATURE_NO_MATCH; 5409 } 5410 5411 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5412 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5413 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5414 } 5415 5416 private int compareSignaturesRecover(PackageSignatures existingSigs, 5417 PackageParser.Package scannedPkg) { 5418 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5419 return PackageManager.SIGNATURE_NO_MATCH; 5420 } 5421 5422 String msg = null; 5423 try { 5424 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5425 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5426 + scannedPkg.packageName); 5427 return PackageManager.SIGNATURE_MATCH; 5428 } 5429 } catch (CertificateException e) { 5430 msg = e.getMessage(); 5431 } 5432 5433 logCriticalInfo(Log.INFO, 5434 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5435 return PackageManager.SIGNATURE_NO_MATCH; 5436 } 5437 5438 @Override 5439 public List<String> getAllPackages() { 5440 synchronized (mPackages) { 5441 return new ArrayList<String>(mPackages.keySet()); 5442 } 5443 } 5444 5445 @Override 5446 public String[] getPackagesForUid(int uid) { 5447 final int userId = UserHandle.getUserId(uid); 5448 uid = UserHandle.getAppId(uid); 5449 // reader 5450 synchronized (mPackages) { 5451 Object obj = mSettings.getUserIdLPr(uid); 5452 if (obj instanceof SharedUserSetting) { 5453 final SharedUserSetting sus = (SharedUserSetting) obj; 5454 final int N = sus.packages.size(); 5455 String[] res = new String[N]; 5456 final Iterator<PackageSetting> it = sus.packages.iterator(); 5457 int i = 0; 5458 while (it.hasNext()) { 5459 PackageSetting ps = it.next(); 5460 if (ps.getInstalled(userId)) { 5461 res[i++] = ps.name; 5462 } else { 5463 res = ArrayUtils.removeElement(String.class, res, res[i]); 5464 } 5465 } 5466 return res; 5467 } else if (obj instanceof PackageSetting) { 5468 final PackageSetting ps = (PackageSetting) obj; 5469 if (ps.getInstalled(userId)) { 5470 return new String[]{ps.name}; 5471 } 5472 } 5473 } 5474 return null; 5475 } 5476 5477 @Override 5478 public String getNameForUid(int uid) { 5479 // reader 5480 synchronized (mPackages) { 5481 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5482 if (obj instanceof SharedUserSetting) { 5483 final SharedUserSetting sus = (SharedUserSetting) obj; 5484 return sus.name + ":" + sus.userId; 5485 } else if (obj instanceof PackageSetting) { 5486 final PackageSetting ps = (PackageSetting) obj; 5487 return ps.name; 5488 } 5489 } 5490 return null; 5491 } 5492 5493 @Override 5494 public int getUidForSharedUser(String sharedUserName) { 5495 if(sharedUserName == null) { 5496 return -1; 5497 } 5498 // reader 5499 synchronized (mPackages) { 5500 SharedUserSetting suid; 5501 try { 5502 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5503 if (suid != null) { 5504 return suid.userId; 5505 } 5506 } catch (PackageManagerException ignore) { 5507 // can't happen, but, still need to catch it 5508 } 5509 return -1; 5510 } 5511 } 5512 5513 @Override 5514 public int getFlagsForUid(int uid) { 5515 synchronized (mPackages) { 5516 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5517 if (obj instanceof SharedUserSetting) { 5518 final SharedUserSetting sus = (SharedUserSetting) obj; 5519 return sus.pkgFlags; 5520 } else if (obj instanceof PackageSetting) { 5521 final PackageSetting ps = (PackageSetting) obj; 5522 return ps.pkgFlags; 5523 } 5524 } 5525 return 0; 5526 } 5527 5528 @Override 5529 public int getPrivateFlagsForUid(int uid) { 5530 synchronized (mPackages) { 5531 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5532 if (obj instanceof SharedUserSetting) { 5533 final SharedUserSetting sus = (SharedUserSetting) obj; 5534 return sus.pkgPrivateFlags; 5535 } else if (obj instanceof PackageSetting) { 5536 final PackageSetting ps = (PackageSetting) obj; 5537 return ps.pkgPrivateFlags; 5538 } 5539 } 5540 return 0; 5541 } 5542 5543 @Override 5544 public boolean isUidPrivileged(int uid) { 5545 uid = UserHandle.getAppId(uid); 5546 // reader 5547 synchronized (mPackages) { 5548 Object obj = mSettings.getUserIdLPr(uid); 5549 if (obj instanceof SharedUserSetting) { 5550 final SharedUserSetting sus = (SharedUserSetting) obj; 5551 final Iterator<PackageSetting> it = sus.packages.iterator(); 5552 while (it.hasNext()) { 5553 if (it.next().isPrivileged()) { 5554 return true; 5555 } 5556 } 5557 } else if (obj instanceof PackageSetting) { 5558 final PackageSetting ps = (PackageSetting) obj; 5559 return ps.isPrivileged(); 5560 } 5561 } 5562 return false; 5563 } 5564 5565 @Override 5566 public String[] getAppOpPermissionPackages(String permissionName) { 5567 synchronized (mPackages) { 5568 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5569 if (pkgs == null) { 5570 return null; 5571 } 5572 return pkgs.toArray(new String[pkgs.size()]); 5573 } 5574 } 5575 5576 @Override 5577 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5578 int flags, int userId) { 5579 return resolveIntentInternal( 5580 intent, resolvedType, flags, userId, false /*includeInstantApp*/); 5581 } 5582 5583 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5584 int flags, int userId, boolean includeInstantApp) { 5585 try { 5586 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5587 5588 if (!sUserManager.exists(userId)) return null; 5589 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 5590 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5591 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5592 5593 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5594 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5595 flags, userId, includeInstantApp); 5596 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5597 5598 final ResolveInfo bestChoice = 5599 chooseBestActivity(intent, resolvedType, flags, query, userId); 5600 return bestChoice; 5601 } finally { 5602 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5603 } 5604 } 5605 5606 @Override 5607 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5608 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5609 throw new SecurityException( 5610 "findPersistentPreferredActivity can only be run by the system"); 5611 } 5612 if (!sUserManager.exists(userId)) { 5613 return null; 5614 } 5615 intent = updateIntentForResolve(intent); 5616 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5617 final int flags = updateFlagsForResolve(0, userId, intent, false); 5618 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5619 userId); 5620 synchronized (mPackages) { 5621 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5622 userId); 5623 } 5624 } 5625 5626 @Override 5627 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5628 IntentFilter filter, int match, ComponentName activity) { 5629 final int userId = UserHandle.getCallingUserId(); 5630 if (DEBUG_PREFERRED) { 5631 Log.v(TAG, "setLastChosenActivity intent=" + intent 5632 + " resolvedType=" + resolvedType 5633 + " flags=" + flags 5634 + " filter=" + filter 5635 + " match=" + match 5636 + " activity=" + activity); 5637 filter.dump(new PrintStreamPrinter(System.out), " "); 5638 } 5639 intent.setComponent(null); 5640 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5641 userId); 5642 // Find any earlier preferred or last chosen entries and nuke them 5643 findPreferredActivity(intent, resolvedType, 5644 flags, query, 0, false, true, false, userId); 5645 // Add the new activity as the last chosen for this filter 5646 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5647 "Setting last chosen"); 5648 } 5649 5650 @Override 5651 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5652 final int userId = UserHandle.getCallingUserId(); 5653 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5654 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5655 userId); 5656 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5657 false, false, false, userId); 5658 } 5659 5660 private boolean isEphemeralDisabled() { 5661 // ephemeral apps have been disabled across the board 5662 if (DISABLE_EPHEMERAL_APPS) { 5663 return true; 5664 } 5665 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5666 if (!mSystemReady) { 5667 return true; 5668 } 5669 // we can't get a content resolver until the system is ready; these checks must happen last 5670 final ContentResolver resolver = mContext.getContentResolver(); 5671 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5672 return true; 5673 } 5674 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5675 } 5676 5677 private boolean isEphemeralAllowed( 5678 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5679 boolean skipPackageCheck) { 5680 // Short circuit and return early if possible. 5681 if (isEphemeralDisabled()) { 5682 return false; 5683 } 5684 final int callingUser = UserHandle.getCallingUserId(); 5685 if (callingUser != UserHandle.USER_SYSTEM) { 5686 return false; 5687 } 5688 if (mInstantAppResolverConnection == null) { 5689 return false; 5690 } 5691 if (mInstantAppInstallerComponent == null) { 5692 return false; 5693 } 5694 if (intent.getComponent() != null) { 5695 return false; 5696 } 5697 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5698 return false; 5699 } 5700 if (!skipPackageCheck && intent.getPackage() != null) { 5701 return false; 5702 } 5703 final boolean isWebUri = hasWebURI(intent); 5704 if (!isWebUri || intent.getData().getHost() == null) { 5705 return false; 5706 } 5707 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5708 // Or if there's already an ephemeral app installed that handles the action 5709 synchronized (mPackages) { 5710 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5711 for (int n = 0; n < count; n++) { 5712 ResolveInfo info = resolvedActivities.get(n); 5713 String packageName = info.activityInfo.packageName; 5714 PackageSetting ps = mSettings.mPackages.get(packageName); 5715 if (ps != null) { 5716 // Try to get the status from User settings first 5717 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5718 int status = (int) (packedStatus >> 32); 5719 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5720 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5721 if (DEBUG_EPHEMERAL) { 5722 Slog.v(TAG, "DENY ephemeral apps;" 5723 + " pkg: " + packageName + ", status: " + status); 5724 } 5725 return false; 5726 } 5727 if (ps.getInstantApp(userId)) { 5728 return false; 5729 } 5730 } 5731 } 5732 } 5733 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5734 return true; 5735 } 5736 5737 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5738 Intent origIntent, String resolvedType, String callingPackage, 5739 int userId) { 5740 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5741 new EphemeralRequest(responseObj, origIntent, resolvedType, 5742 callingPackage, userId)); 5743 mHandler.sendMessage(msg); 5744 } 5745 5746 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5747 int flags, List<ResolveInfo> query, int userId) { 5748 if (query != null) { 5749 final int N = query.size(); 5750 if (N == 1) { 5751 return query.get(0); 5752 } else if (N > 1) { 5753 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5754 // If there is more than one activity with the same priority, 5755 // then let the user decide between them. 5756 ResolveInfo r0 = query.get(0); 5757 ResolveInfo r1 = query.get(1); 5758 if (DEBUG_INTENT_MATCHING || debug) { 5759 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5760 + r1.activityInfo.name + "=" + r1.priority); 5761 } 5762 // If the first activity has a higher priority, or a different 5763 // default, then it is always desirable to pick it. 5764 if (r0.priority != r1.priority 5765 || r0.preferredOrder != r1.preferredOrder 5766 || r0.isDefault != r1.isDefault) { 5767 return query.get(0); 5768 } 5769 // If we have saved a preference for a preferred activity for 5770 // this Intent, use that. 5771 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5772 flags, query, r0.priority, true, false, debug, userId); 5773 if (ri != null) { 5774 return ri; 5775 } 5776 // If we have an ephemeral app, use it 5777 for (int i = 0; i < N; i++) { 5778 ri = query.get(i); 5779 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5780 return ri; 5781 } 5782 } 5783 ri = new ResolveInfo(mResolveInfo); 5784 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5785 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5786 // If all of the options come from the same package, show the application's 5787 // label and icon instead of the generic resolver's. 5788 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5789 // and then throw away the ResolveInfo itself, meaning that the caller loses 5790 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5791 // a fallback for this case; we only set the target package's resources on 5792 // the ResolveInfo, not the ActivityInfo. 5793 final String intentPackage = intent.getPackage(); 5794 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5795 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5796 ri.resolvePackageName = intentPackage; 5797 if (userNeedsBadging(userId)) { 5798 ri.noResourceId = true; 5799 } else { 5800 ri.icon = appi.icon; 5801 } 5802 ri.iconResourceId = appi.icon; 5803 ri.labelRes = appi.labelRes; 5804 } 5805 ri.activityInfo.applicationInfo = new ApplicationInfo( 5806 ri.activityInfo.applicationInfo); 5807 if (userId != 0) { 5808 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5809 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5810 } 5811 // Make sure that the resolver is displayable in car mode 5812 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5813 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5814 return ri; 5815 } 5816 } 5817 return null; 5818 } 5819 5820 /** 5821 * Return true if the given list is not empty and all of its contents have 5822 * an activityInfo with the given package name. 5823 */ 5824 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5825 if (ArrayUtils.isEmpty(list)) { 5826 return false; 5827 } 5828 for (int i = 0, N = list.size(); i < N; i++) { 5829 final ResolveInfo ri = list.get(i); 5830 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5831 if (ai == null || !packageName.equals(ai.packageName)) { 5832 return false; 5833 } 5834 } 5835 return true; 5836 } 5837 5838 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5839 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5840 final int N = query.size(); 5841 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5842 .get(userId); 5843 // Get the list of persistent preferred activities that handle the intent 5844 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5845 List<PersistentPreferredActivity> pprefs = ppir != null 5846 ? ppir.queryIntent(intent, resolvedType, 5847 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5848 userId) 5849 : null; 5850 if (pprefs != null && pprefs.size() > 0) { 5851 final int M = pprefs.size(); 5852 for (int i=0; i<M; i++) { 5853 final PersistentPreferredActivity ppa = pprefs.get(i); 5854 if (DEBUG_PREFERRED || debug) { 5855 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5856 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5857 + "\n component=" + ppa.mComponent); 5858 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5859 } 5860 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5861 flags | MATCH_DISABLED_COMPONENTS, userId); 5862 if (DEBUG_PREFERRED || debug) { 5863 Slog.v(TAG, "Found persistent preferred activity:"); 5864 if (ai != null) { 5865 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5866 } else { 5867 Slog.v(TAG, " null"); 5868 } 5869 } 5870 if (ai == null) { 5871 // This previously registered persistent preferred activity 5872 // component is no longer known. Ignore it and do NOT remove it. 5873 continue; 5874 } 5875 for (int j=0; j<N; j++) { 5876 final ResolveInfo ri = query.get(j); 5877 if (!ri.activityInfo.applicationInfo.packageName 5878 .equals(ai.applicationInfo.packageName)) { 5879 continue; 5880 } 5881 if (!ri.activityInfo.name.equals(ai.name)) { 5882 continue; 5883 } 5884 // Found a persistent preference that can handle the intent. 5885 if (DEBUG_PREFERRED || debug) { 5886 Slog.v(TAG, "Returning persistent preferred activity: " + 5887 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5888 } 5889 return ri; 5890 } 5891 } 5892 } 5893 return null; 5894 } 5895 5896 // TODO: handle preferred activities missing while user has amnesia 5897 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5898 List<ResolveInfo> query, int priority, boolean always, 5899 boolean removeMatches, boolean debug, int userId) { 5900 if (!sUserManager.exists(userId)) return null; 5901 flags = updateFlagsForResolve(flags, userId, intent, false); 5902 intent = updateIntentForResolve(intent); 5903 // writer 5904 synchronized (mPackages) { 5905 // Try to find a matching persistent preferred activity. 5906 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5907 debug, userId); 5908 5909 // If a persistent preferred activity matched, use it. 5910 if (pri != null) { 5911 return pri; 5912 } 5913 5914 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5915 // Get the list of preferred activities that handle the intent 5916 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5917 List<PreferredActivity> prefs = pir != null 5918 ? pir.queryIntent(intent, resolvedType, 5919 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5920 userId) 5921 : null; 5922 if (prefs != null && prefs.size() > 0) { 5923 boolean changed = false; 5924 try { 5925 // First figure out how good the original match set is. 5926 // We will only allow preferred activities that came 5927 // from the same match quality. 5928 int match = 0; 5929 5930 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5931 5932 final int N = query.size(); 5933 for (int j=0; j<N; j++) { 5934 final ResolveInfo ri = query.get(j); 5935 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5936 + ": 0x" + Integer.toHexString(match)); 5937 if (ri.match > match) { 5938 match = ri.match; 5939 } 5940 } 5941 5942 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5943 + Integer.toHexString(match)); 5944 5945 match &= IntentFilter.MATCH_CATEGORY_MASK; 5946 final int M = prefs.size(); 5947 for (int i=0; i<M; i++) { 5948 final PreferredActivity pa = prefs.get(i); 5949 if (DEBUG_PREFERRED || debug) { 5950 Slog.v(TAG, "Checking PreferredActivity ds=" 5951 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5952 + "\n component=" + pa.mPref.mComponent); 5953 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5954 } 5955 if (pa.mPref.mMatch != match) { 5956 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5957 + Integer.toHexString(pa.mPref.mMatch)); 5958 continue; 5959 } 5960 // If it's not an "always" type preferred activity and that's what we're 5961 // looking for, skip it. 5962 if (always && !pa.mPref.mAlways) { 5963 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5964 continue; 5965 } 5966 final ActivityInfo ai = getActivityInfo( 5967 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5968 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5969 userId); 5970 if (DEBUG_PREFERRED || debug) { 5971 Slog.v(TAG, "Found preferred activity:"); 5972 if (ai != null) { 5973 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5974 } else { 5975 Slog.v(TAG, " null"); 5976 } 5977 } 5978 if (ai == null) { 5979 // This previously registered preferred activity 5980 // component is no longer known. Most likely an update 5981 // to the app was installed and in the new version this 5982 // component no longer exists. Clean it up by removing 5983 // it from the preferred activities list, and skip it. 5984 Slog.w(TAG, "Removing dangling preferred activity: " 5985 + pa.mPref.mComponent); 5986 pir.removeFilter(pa); 5987 changed = true; 5988 continue; 5989 } 5990 for (int j=0; j<N; j++) { 5991 final ResolveInfo ri = query.get(j); 5992 if (!ri.activityInfo.applicationInfo.packageName 5993 .equals(ai.applicationInfo.packageName)) { 5994 continue; 5995 } 5996 if (!ri.activityInfo.name.equals(ai.name)) { 5997 continue; 5998 } 5999 6000 if (removeMatches) { 6001 pir.removeFilter(pa); 6002 changed = true; 6003 if (DEBUG_PREFERRED) { 6004 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6005 } 6006 break; 6007 } 6008 6009 // Okay we found a previously set preferred or last chosen app. 6010 // If the result set is different from when this 6011 // was created, we need to clear it and re-ask the 6012 // user their preference, if we're looking for an "always" type entry. 6013 if (always && !pa.mPref.sameSet(query)) { 6014 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6015 + intent + " type " + resolvedType); 6016 if (DEBUG_PREFERRED) { 6017 Slog.v(TAG, "Removing preferred activity since set changed " 6018 + pa.mPref.mComponent); 6019 } 6020 pir.removeFilter(pa); 6021 // Re-add the filter as a "last chosen" entry (!always) 6022 PreferredActivity lastChosen = new PreferredActivity( 6023 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6024 pir.addFilter(lastChosen); 6025 changed = true; 6026 return null; 6027 } 6028 6029 // Yay! Either the set matched or we're looking for the last chosen 6030 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6031 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6032 return ri; 6033 } 6034 } 6035 } finally { 6036 if (changed) { 6037 if (DEBUG_PREFERRED) { 6038 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6039 } 6040 scheduleWritePackageRestrictionsLocked(userId); 6041 } 6042 } 6043 } 6044 } 6045 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6046 return null; 6047 } 6048 6049 /* 6050 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6051 */ 6052 @Override 6053 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6054 int targetUserId) { 6055 mContext.enforceCallingOrSelfPermission( 6056 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6057 List<CrossProfileIntentFilter> matches = 6058 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6059 if (matches != null) { 6060 int size = matches.size(); 6061 for (int i = 0; i < size; i++) { 6062 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6063 } 6064 } 6065 if (hasWebURI(intent)) { 6066 // cross-profile app linking works only towards the parent. 6067 final UserInfo parent = getProfileParent(sourceUserId); 6068 synchronized(mPackages) { 6069 int flags = updateFlagsForResolve(0, parent.id, intent, false); 6070 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6071 intent, resolvedType, flags, sourceUserId, parent.id); 6072 return xpDomainInfo != null; 6073 } 6074 } 6075 return false; 6076 } 6077 6078 private UserInfo getProfileParent(int userId) { 6079 final long identity = Binder.clearCallingIdentity(); 6080 try { 6081 return sUserManager.getProfileParent(userId); 6082 } finally { 6083 Binder.restoreCallingIdentity(identity); 6084 } 6085 } 6086 6087 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6088 String resolvedType, int userId) { 6089 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6090 if (resolver != null) { 6091 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6092 } 6093 return null; 6094 } 6095 6096 @Override 6097 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6098 String resolvedType, int flags, int userId) { 6099 try { 6100 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6101 6102 return new ParceledListSlice<>( 6103 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6104 } finally { 6105 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6106 } 6107 } 6108 6109 /** 6110 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6111 * instant, returns {@code null}. 6112 */ 6113 private String getInstantAppPackageName(int callingUid) { 6114 final int appId = UserHandle.getAppId(callingUid); 6115 synchronized (mPackages) { 6116 final Object obj = mSettings.getUserIdLPr(appId); 6117 if (obj instanceof PackageSetting) { 6118 final PackageSetting ps = (PackageSetting) obj; 6119 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6120 return isInstantApp ? ps.pkg.packageName : null; 6121 } 6122 } 6123 return null; 6124 } 6125 6126 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6127 String resolvedType, int flags, int userId) { 6128 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6129 } 6130 6131 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6132 String resolvedType, int flags, int userId, boolean includeInstantApp) { 6133 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6134 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6135 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 6136 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6137 false /* requireFullPermission */, false /* checkShell */, 6138 "query intent activities"); 6139 ComponentName comp = intent.getComponent(); 6140 if (comp == null) { 6141 if (intent.getSelector() != null) { 6142 intent = intent.getSelector(); 6143 comp = intent.getComponent(); 6144 } 6145 } 6146 6147 if (comp != null) { 6148 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6149 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6150 if (ai != null) { 6151 // When specifying an explicit component, we prevent the activity from being 6152 // used when either 1) the calling package is normal and the activity is within 6153 // an ephemeral application or 2) the calling package is ephemeral and the 6154 // activity is not visible to ephemeral applications. 6155 final boolean matchInstantApp = 6156 (flags & PackageManager.MATCH_INSTANT) != 0; 6157 final boolean matchVisibleToInstantAppOnly = 6158 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6159 final boolean isCallerInstantApp = 6160 instantAppPkgName != null; 6161 final boolean isTargetSameInstantApp = 6162 comp.getPackageName().equals(instantAppPkgName); 6163 final boolean isTargetInstantApp = 6164 (ai.applicationInfo.privateFlags 6165 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6166 final boolean isTargetHiddenFromInstantApp = 6167 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6168 final boolean blockResolution = 6169 !isTargetSameInstantApp 6170 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6171 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6172 && isTargetHiddenFromInstantApp)); 6173 if (!blockResolution) { 6174 final ResolveInfo ri = new ResolveInfo(); 6175 ri.activityInfo = ai; 6176 list.add(ri); 6177 } 6178 } 6179 return applyPostResolutionFilter(list, instantAppPkgName); 6180 } 6181 6182 // reader 6183 boolean sortResult = false; 6184 boolean addEphemeral = false; 6185 List<ResolveInfo> result; 6186 final String pkgName = intent.getPackage(); 6187 synchronized (mPackages) { 6188 if (pkgName == null) { 6189 List<CrossProfileIntentFilter> matchingFilters = 6190 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6191 // Check for results that need to skip the current profile. 6192 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6193 resolvedType, flags, userId); 6194 if (xpResolveInfo != null) { 6195 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6196 xpResult.add(xpResolveInfo); 6197 return applyPostResolutionFilter( 6198 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6199 } 6200 6201 // Check for results in the current profile. 6202 result = filterIfNotSystemUser(mActivities.queryIntent( 6203 intent, resolvedType, flags, userId), userId); 6204 addEphemeral = 6205 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6206 6207 // Check for cross profile results. 6208 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6209 xpResolveInfo = queryCrossProfileIntents( 6210 matchingFilters, intent, resolvedType, flags, userId, 6211 hasNonNegativePriorityResult); 6212 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6213 boolean isVisibleToUser = filterIfNotSystemUser( 6214 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6215 if (isVisibleToUser) { 6216 result.add(xpResolveInfo); 6217 sortResult = true; 6218 } 6219 } 6220 if (hasWebURI(intent)) { 6221 CrossProfileDomainInfo xpDomainInfo = null; 6222 final UserInfo parent = getProfileParent(userId); 6223 if (parent != null) { 6224 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6225 flags, userId, parent.id); 6226 } 6227 if (xpDomainInfo != null) { 6228 if (xpResolveInfo != null) { 6229 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6230 // in the result. 6231 result.remove(xpResolveInfo); 6232 } 6233 if (result.size() == 0 && !addEphemeral) { 6234 // No result in current profile, but found candidate in parent user. 6235 // And we are not going to add emphemeral app, so we can return the 6236 // result straight away. 6237 result.add(xpDomainInfo.resolveInfo); 6238 return applyPostResolutionFilter(result, instantAppPkgName); 6239 } 6240 } else if (result.size() <= 1 && !addEphemeral) { 6241 // No result in parent user and <= 1 result in current profile, and we 6242 // are not going to add emphemeral app, so we can return the result without 6243 // further processing. 6244 return applyPostResolutionFilter(result, instantAppPkgName); 6245 } 6246 // We have more than one candidate (combining results from current and parent 6247 // profile), so we need filtering and sorting. 6248 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6249 intent, flags, result, xpDomainInfo, userId); 6250 sortResult = true; 6251 } 6252 } else { 6253 final PackageParser.Package pkg = mPackages.get(pkgName); 6254 if (pkg != null) { 6255 result = applyPostResolutionFilter(filterIfNotSystemUser( 6256 mActivities.queryIntentForPackage( 6257 intent, resolvedType, flags, pkg.activities, userId), 6258 userId), instantAppPkgName); 6259 } else { 6260 // the caller wants to resolve for a particular package; however, there 6261 // were no installed results, so, try to find an ephemeral result 6262 addEphemeral = isEphemeralAllowed( 6263 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6264 result = new ArrayList<ResolveInfo>(); 6265 } 6266 } 6267 } 6268 if (addEphemeral) { 6269 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6270 final EphemeralRequest requestObject = new EphemeralRequest( 6271 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6272 null /*callingPackage*/, userId); 6273 final AuxiliaryResolveInfo auxiliaryResponse = 6274 EphemeralResolver.doEphemeralResolutionPhaseOne( 6275 mContext, mInstantAppResolverConnection, requestObject); 6276 if (auxiliaryResponse != null) { 6277 if (DEBUG_EPHEMERAL) { 6278 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6279 } 6280 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6281 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6282 // make sure this resolver is the default 6283 ephemeralInstaller.isDefault = true; 6284 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6285 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6286 // add a non-generic filter 6287 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6288 ephemeralInstaller.filter.addDataPath( 6289 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6290 result.add(ephemeralInstaller); 6291 } 6292 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6293 } 6294 if (sortResult) { 6295 Collections.sort(result, mResolvePrioritySorter); 6296 } 6297 return applyPostResolutionFilter(result, instantAppPkgName); 6298 } 6299 6300 private static class CrossProfileDomainInfo { 6301 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6302 ResolveInfo resolveInfo; 6303 /* Best domain verification status of the activities found in the other profile */ 6304 int bestDomainVerificationStatus; 6305 } 6306 6307 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6308 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6309 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6310 sourceUserId)) { 6311 return null; 6312 } 6313 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6314 resolvedType, flags, parentUserId); 6315 6316 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6317 return null; 6318 } 6319 CrossProfileDomainInfo result = null; 6320 int size = resultTargetUser.size(); 6321 for (int i = 0; i < size; i++) { 6322 ResolveInfo riTargetUser = resultTargetUser.get(i); 6323 // Intent filter verification is only for filters that specify a host. So don't return 6324 // those that handle all web uris. 6325 if (riTargetUser.handleAllWebDataURI) { 6326 continue; 6327 } 6328 String packageName = riTargetUser.activityInfo.packageName; 6329 PackageSetting ps = mSettings.mPackages.get(packageName); 6330 if (ps == null) { 6331 continue; 6332 } 6333 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6334 int status = (int)(verificationState >> 32); 6335 if (result == null) { 6336 result = new CrossProfileDomainInfo(); 6337 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6338 sourceUserId, parentUserId); 6339 result.bestDomainVerificationStatus = status; 6340 } else { 6341 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6342 result.bestDomainVerificationStatus); 6343 } 6344 } 6345 // Don't consider matches with status NEVER across profiles. 6346 if (result != null && result.bestDomainVerificationStatus 6347 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6348 return null; 6349 } 6350 return result; 6351 } 6352 6353 /** 6354 * Verification statuses are ordered from the worse to the best, except for 6355 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6356 */ 6357 private int bestDomainVerificationStatus(int status1, int status2) { 6358 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6359 return status2; 6360 } 6361 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6362 return status1; 6363 } 6364 return (int) MathUtils.max(status1, status2); 6365 } 6366 6367 private boolean isUserEnabled(int userId) { 6368 long callingId = Binder.clearCallingIdentity(); 6369 try { 6370 UserInfo userInfo = sUserManager.getUserInfo(userId); 6371 return userInfo != null && userInfo.isEnabled(); 6372 } finally { 6373 Binder.restoreCallingIdentity(callingId); 6374 } 6375 } 6376 6377 /** 6378 * Filter out activities with systemUserOnly flag set, when current user is not System. 6379 * 6380 * @return filtered list 6381 */ 6382 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6383 if (userId == UserHandle.USER_SYSTEM) { 6384 return resolveInfos; 6385 } 6386 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6387 ResolveInfo info = resolveInfos.get(i); 6388 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6389 resolveInfos.remove(i); 6390 } 6391 } 6392 return resolveInfos; 6393 } 6394 6395 /** 6396 * Filters out ephemeral activities. 6397 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6398 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6399 * 6400 * @param resolveInfos The pre-filtered list of resolved activities 6401 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6402 * is performed. 6403 * @return A filtered list of resolved activities. 6404 */ 6405 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6406 String ephemeralPkgName) { 6407 // TODO: When adding on-demand split support for non-instant apps, remove this check 6408 // and always apply post filtering 6409 if (ephemeralPkgName == null) { 6410 return resolveInfos; 6411 } 6412 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6413 final ResolveInfo info = resolveInfos.get(i); 6414 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6415 // allow activities that are defined in the provided package 6416 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6417 if (info.activityInfo.splitName != null 6418 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6419 info.activityInfo.splitName)) { 6420 // requested activity is defined in a split that hasn't been installed yet. 6421 // add the installer to the resolve list 6422 if (DEBUG_EPHEMERAL) { 6423 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6424 } 6425 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6426 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6427 info.activityInfo.packageName, info.activityInfo.splitName, 6428 info.activityInfo.applicationInfo.versionCode); 6429 // make sure this resolver is the default 6430 installerInfo.isDefault = true; 6431 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6432 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6433 // add a non-generic filter 6434 installerInfo.filter = new IntentFilter(); 6435 // load resources from the correct package 6436 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6437 resolveInfos.set(i, installerInfo); 6438 } 6439 continue; 6440 } 6441 // allow activities that have been explicitly exposed to ephemeral apps 6442 if (!isEphemeralApp 6443 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6444 continue; 6445 } 6446 resolveInfos.remove(i); 6447 } 6448 return resolveInfos; 6449 } 6450 6451 /** 6452 * @param resolveInfos list of resolve infos in descending priority order 6453 * @return if the list contains a resolve info with non-negative priority 6454 */ 6455 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6456 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6457 } 6458 6459 private static boolean hasWebURI(Intent intent) { 6460 if (intent.getData() == null) { 6461 return false; 6462 } 6463 final String scheme = intent.getScheme(); 6464 if (TextUtils.isEmpty(scheme)) { 6465 return false; 6466 } 6467 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6468 } 6469 6470 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6471 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6472 int userId) { 6473 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6474 6475 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6476 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6477 candidates.size()); 6478 } 6479 6480 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6481 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6482 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6483 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6484 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6485 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6486 6487 synchronized (mPackages) { 6488 final int count = candidates.size(); 6489 // First, try to use linked apps. Partition the candidates into four lists: 6490 // one for the final results, one for the "do not use ever", one for "undefined status" 6491 // and finally one for "browser app type". 6492 for (int n=0; n<count; n++) { 6493 ResolveInfo info = candidates.get(n); 6494 String packageName = info.activityInfo.packageName; 6495 PackageSetting ps = mSettings.mPackages.get(packageName); 6496 if (ps != null) { 6497 // Add to the special match all list (Browser use case) 6498 if (info.handleAllWebDataURI) { 6499 matchAllList.add(info); 6500 continue; 6501 } 6502 // Try to get the status from User settings first 6503 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6504 int status = (int)(packedStatus >> 32); 6505 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6506 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6507 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6508 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6509 + " : linkgen=" + linkGeneration); 6510 } 6511 // Use link-enabled generation as preferredOrder, i.e. 6512 // prefer newly-enabled over earlier-enabled. 6513 info.preferredOrder = linkGeneration; 6514 alwaysList.add(info); 6515 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6516 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6517 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6518 } 6519 neverList.add(info); 6520 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6521 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6522 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6523 } 6524 alwaysAskList.add(info); 6525 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6526 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6527 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6528 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6529 } 6530 undefinedList.add(info); 6531 } 6532 } 6533 } 6534 6535 // We'll want to include browser possibilities in a few cases 6536 boolean includeBrowser = false; 6537 6538 // First try to add the "always" resolution(s) for the current user, if any 6539 if (alwaysList.size() > 0) { 6540 result.addAll(alwaysList); 6541 } else { 6542 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6543 result.addAll(undefinedList); 6544 // Maybe add one for the other profile. 6545 if (xpDomainInfo != null && ( 6546 xpDomainInfo.bestDomainVerificationStatus 6547 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6548 result.add(xpDomainInfo.resolveInfo); 6549 } 6550 includeBrowser = true; 6551 } 6552 6553 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6554 // If there were 'always' entries their preferred order has been set, so we also 6555 // back that off to make the alternatives equivalent 6556 if (alwaysAskList.size() > 0) { 6557 for (ResolveInfo i : result) { 6558 i.preferredOrder = 0; 6559 } 6560 result.addAll(alwaysAskList); 6561 includeBrowser = true; 6562 } 6563 6564 if (includeBrowser) { 6565 // Also add browsers (all of them or only the default one) 6566 if (DEBUG_DOMAIN_VERIFICATION) { 6567 Slog.v(TAG, " ...including browsers in candidate set"); 6568 } 6569 if ((matchFlags & MATCH_ALL) != 0) { 6570 result.addAll(matchAllList); 6571 } else { 6572 // Browser/generic handling case. If there's a default browser, go straight 6573 // to that (but only if there is no other higher-priority match). 6574 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6575 int maxMatchPrio = 0; 6576 ResolveInfo defaultBrowserMatch = null; 6577 final int numCandidates = matchAllList.size(); 6578 for (int n = 0; n < numCandidates; n++) { 6579 ResolveInfo info = matchAllList.get(n); 6580 // track the highest overall match priority... 6581 if (info.priority > maxMatchPrio) { 6582 maxMatchPrio = info.priority; 6583 } 6584 // ...and the highest-priority default browser match 6585 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6586 if (defaultBrowserMatch == null 6587 || (defaultBrowserMatch.priority < info.priority)) { 6588 if (debug) { 6589 Slog.v(TAG, "Considering default browser match " + info); 6590 } 6591 defaultBrowserMatch = info; 6592 } 6593 } 6594 } 6595 if (defaultBrowserMatch != null 6596 && defaultBrowserMatch.priority >= maxMatchPrio 6597 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6598 { 6599 if (debug) { 6600 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6601 } 6602 result.add(defaultBrowserMatch); 6603 } else { 6604 result.addAll(matchAllList); 6605 } 6606 } 6607 6608 // If there is nothing selected, add all candidates and remove the ones that the user 6609 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6610 if (result.size() == 0) { 6611 result.addAll(candidates); 6612 result.removeAll(neverList); 6613 } 6614 } 6615 } 6616 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6617 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6618 result.size()); 6619 for (ResolveInfo info : result) { 6620 Slog.v(TAG, " + " + info.activityInfo); 6621 } 6622 } 6623 return result; 6624 } 6625 6626 // Returns a packed value as a long: 6627 // 6628 // high 'int'-sized word: link status: undefined/ask/never/always. 6629 // low 'int'-sized word: relative priority among 'always' results. 6630 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6631 long result = ps.getDomainVerificationStatusForUser(userId); 6632 // if none available, get the master status 6633 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6634 if (ps.getIntentFilterVerificationInfo() != null) { 6635 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6636 } 6637 } 6638 return result; 6639 } 6640 6641 private ResolveInfo querySkipCurrentProfileIntents( 6642 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6643 int flags, int sourceUserId) { 6644 if (matchingFilters != null) { 6645 int size = matchingFilters.size(); 6646 for (int i = 0; i < size; i ++) { 6647 CrossProfileIntentFilter filter = matchingFilters.get(i); 6648 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6649 // Checking if there are activities in the target user that can handle the 6650 // intent. 6651 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6652 resolvedType, flags, sourceUserId); 6653 if (resolveInfo != null) { 6654 return resolveInfo; 6655 } 6656 } 6657 } 6658 } 6659 return null; 6660 } 6661 6662 // Return matching ResolveInfo in target user if any. 6663 private ResolveInfo queryCrossProfileIntents( 6664 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6665 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6666 if (matchingFilters != null) { 6667 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6668 // match the same intent. For performance reasons, it is better not to 6669 // run queryIntent twice for the same userId 6670 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6671 int size = matchingFilters.size(); 6672 for (int i = 0; i < size; i++) { 6673 CrossProfileIntentFilter filter = matchingFilters.get(i); 6674 int targetUserId = filter.getTargetUserId(); 6675 boolean skipCurrentProfile = 6676 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6677 boolean skipCurrentProfileIfNoMatchFound = 6678 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6679 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6680 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6681 // Checking if there are activities in the target user that can handle the 6682 // intent. 6683 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6684 resolvedType, flags, sourceUserId); 6685 if (resolveInfo != null) return resolveInfo; 6686 alreadyTriedUserIds.put(targetUserId, true); 6687 } 6688 } 6689 } 6690 return null; 6691 } 6692 6693 /** 6694 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6695 * will forward the intent to the filter's target user. 6696 * Otherwise, returns null. 6697 */ 6698 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6699 String resolvedType, int flags, int sourceUserId) { 6700 int targetUserId = filter.getTargetUserId(); 6701 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6702 resolvedType, flags, targetUserId); 6703 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6704 // If all the matches in the target profile are suspended, return null. 6705 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6706 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6707 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6708 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6709 targetUserId); 6710 } 6711 } 6712 } 6713 return null; 6714 } 6715 6716 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6717 int sourceUserId, int targetUserId) { 6718 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6719 long ident = Binder.clearCallingIdentity(); 6720 boolean targetIsProfile; 6721 try { 6722 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6723 } finally { 6724 Binder.restoreCallingIdentity(ident); 6725 } 6726 String className; 6727 if (targetIsProfile) { 6728 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6729 } else { 6730 className = FORWARD_INTENT_TO_PARENT; 6731 } 6732 ComponentName forwardingActivityComponentName = new ComponentName( 6733 mAndroidApplication.packageName, className); 6734 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6735 sourceUserId); 6736 if (!targetIsProfile) { 6737 forwardingActivityInfo.showUserIcon = targetUserId; 6738 forwardingResolveInfo.noResourceId = true; 6739 } 6740 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6741 forwardingResolveInfo.priority = 0; 6742 forwardingResolveInfo.preferredOrder = 0; 6743 forwardingResolveInfo.match = 0; 6744 forwardingResolveInfo.isDefault = true; 6745 forwardingResolveInfo.filter = filter; 6746 forwardingResolveInfo.targetUserId = targetUserId; 6747 return forwardingResolveInfo; 6748 } 6749 6750 @Override 6751 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6752 Intent[] specifics, String[] specificTypes, Intent intent, 6753 String resolvedType, int flags, int userId) { 6754 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6755 specificTypes, intent, resolvedType, flags, userId)); 6756 } 6757 6758 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6759 Intent[] specifics, String[] specificTypes, Intent intent, 6760 String resolvedType, int flags, int userId) { 6761 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6762 flags = updateFlagsForResolve(flags, userId, intent, false); 6763 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6764 false /* requireFullPermission */, false /* checkShell */, 6765 "query intent activity options"); 6766 final String resultsAction = intent.getAction(); 6767 6768 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6769 | PackageManager.GET_RESOLVED_FILTER, userId); 6770 6771 if (DEBUG_INTENT_MATCHING) { 6772 Log.v(TAG, "Query " + intent + ": " + results); 6773 } 6774 6775 int specificsPos = 0; 6776 int N; 6777 6778 // todo: note that the algorithm used here is O(N^2). This 6779 // isn't a problem in our current environment, but if we start running 6780 // into situations where we have more than 5 or 10 matches then this 6781 // should probably be changed to something smarter... 6782 6783 // First we go through and resolve each of the specific items 6784 // that were supplied, taking care of removing any corresponding 6785 // duplicate items in the generic resolve list. 6786 if (specifics != null) { 6787 for (int i=0; i<specifics.length; i++) { 6788 final Intent sintent = specifics[i]; 6789 if (sintent == null) { 6790 continue; 6791 } 6792 6793 if (DEBUG_INTENT_MATCHING) { 6794 Log.v(TAG, "Specific #" + i + ": " + sintent); 6795 } 6796 6797 String action = sintent.getAction(); 6798 if (resultsAction != null && resultsAction.equals(action)) { 6799 // If this action was explicitly requested, then don't 6800 // remove things that have it. 6801 action = null; 6802 } 6803 6804 ResolveInfo ri = null; 6805 ActivityInfo ai = null; 6806 6807 ComponentName comp = sintent.getComponent(); 6808 if (comp == null) { 6809 ri = resolveIntent( 6810 sintent, 6811 specificTypes != null ? specificTypes[i] : null, 6812 flags, userId); 6813 if (ri == null) { 6814 continue; 6815 } 6816 if (ri == mResolveInfo) { 6817 // ACK! Must do something better with this. 6818 } 6819 ai = ri.activityInfo; 6820 comp = new ComponentName(ai.applicationInfo.packageName, 6821 ai.name); 6822 } else { 6823 ai = getActivityInfo(comp, flags, userId); 6824 if (ai == null) { 6825 continue; 6826 } 6827 } 6828 6829 // Look for any generic query activities that are duplicates 6830 // of this specific one, and remove them from the results. 6831 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6832 N = results.size(); 6833 int j; 6834 for (j=specificsPos; j<N; j++) { 6835 ResolveInfo sri = results.get(j); 6836 if ((sri.activityInfo.name.equals(comp.getClassName()) 6837 && sri.activityInfo.applicationInfo.packageName.equals( 6838 comp.getPackageName())) 6839 || (action != null && sri.filter.matchAction(action))) { 6840 results.remove(j); 6841 if (DEBUG_INTENT_MATCHING) Log.v( 6842 TAG, "Removing duplicate item from " + j 6843 + " due to specific " + specificsPos); 6844 if (ri == null) { 6845 ri = sri; 6846 } 6847 j--; 6848 N--; 6849 } 6850 } 6851 6852 // Add this specific item to its proper place. 6853 if (ri == null) { 6854 ri = new ResolveInfo(); 6855 ri.activityInfo = ai; 6856 } 6857 results.add(specificsPos, ri); 6858 ri.specificIndex = i; 6859 specificsPos++; 6860 } 6861 } 6862 6863 // Now we go through the remaining generic results and remove any 6864 // duplicate actions that are found here. 6865 N = results.size(); 6866 for (int i=specificsPos; i<N-1; i++) { 6867 final ResolveInfo rii = results.get(i); 6868 if (rii.filter == null) { 6869 continue; 6870 } 6871 6872 // Iterate over all of the actions of this result's intent 6873 // filter... typically this should be just one. 6874 final Iterator<String> it = rii.filter.actionsIterator(); 6875 if (it == null) { 6876 continue; 6877 } 6878 while (it.hasNext()) { 6879 final String action = it.next(); 6880 if (resultsAction != null && resultsAction.equals(action)) { 6881 // If this action was explicitly requested, then don't 6882 // remove things that have it. 6883 continue; 6884 } 6885 for (int j=i+1; j<N; j++) { 6886 final ResolveInfo rij = results.get(j); 6887 if (rij.filter != null && rij.filter.hasAction(action)) { 6888 results.remove(j); 6889 if (DEBUG_INTENT_MATCHING) Log.v( 6890 TAG, "Removing duplicate item from " + j 6891 + " due to action " + action + " at " + i); 6892 j--; 6893 N--; 6894 } 6895 } 6896 } 6897 6898 // If the caller didn't request filter information, drop it now 6899 // so we don't have to marshall/unmarshall it. 6900 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6901 rii.filter = null; 6902 } 6903 } 6904 6905 // Filter out the caller activity if so requested. 6906 if (caller != null) { 6907 N = results.size(); 6908 for (int i=0; i<N; i++) { 6909 ActivityInfo ainfo = results.get(i).activityInfo; 6910 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6911 && caller.getClassName().equals(ainfo.name)) { 6912 results.remove(i); 6913 break; 6914 } 6915 } 6916 } 6917 6918 // If the caller didn't request filter information, 6919 // drop them now so we don't have to 6920 // marshall/unmarshall it. 6921 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6922 N = results.size(); 6923 for (int i=0; i<N; i++) { 6924 results.get(i).filter = null; 6925 } 6926 } 6927 6928 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6929 return results; 6930 } 6931 6932 @Override 6933 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6934 String resolvedType, int flags, int userId) { 6935 return new ParceledListSlice<>( 6936 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6937 } 6938 6939 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6940 String resolvedType, int flags, int userId) { 6941 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6942 flags = updateFlagsForResolve(flags, userId, intent, false); 6943 ComponentName comp = intent.getComponent(); 6944 if (comp == null) { 6945 if (intent.getSelector() != null) { 6946 intent = intent.getSelector(); 6947 comp = intent.getComponent(); 6948 } 6949 } 6950 if (comp != null) { 6951 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6952 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6953 if (ai != null) { 6954 ResolveInfo ri = new ResolveInfo(); 6955 ri.activityInfo = ai; 6956 list.add(ri); 6957 } 6958 return list; 6959 } 6960 6961 // reader 6962 synchronized (mPackages) { 6963 String pkgName = intent.getPackage(); 6964 if (pkgName == null) { 6965 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6966 } 6967 final PackageParser.Package pkg = mPackages.get(pkgName); 6968 if (pkg != null) { 6969 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6970 userId); 6971 } 6972 return Collections.emptyList(); 6973 } 6974 } 6975 6976 @Override 6977 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6978 if (!sUserManager.exists(userId)) return null; 6979 flags = updateFlagsForResolve(flags, userId, intent, false); 6980 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6981 if (query != null) { 6982 if (query.size() >= 1) { 6983 // If there is more than one service with the same priority, 6984 // just arbitrarily pick the first one. 6985 return query.get(0); 6986 } 6987 } 6988 return null; 6989 } 6990 6991 @Override 6992 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6993 String resolvedType, int flags, int userId) { 6994 return new ParceledListSlice<>( 6995 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6996 } 6997 6998 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6999 String resolvedType, int flags, int userId) { 7000 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7001 flags = updateFlagsForResolve(flags, userId, intent, false); 7002 ComponentName comp = intent.getComponent(); 7003 if (comp == null) { 7004 if (intent.getSelector() != null) { 7005 intent = intent.getSelector(); 7006 comp = intent.getComponent(); 7007 } 7008 } 7009 if (comp != null) { 7010 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7011 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7012 if (si != null) { 7013 final ResolveInfo ri = new ResolveInfo(); 7014 ri.serviceInfo = si; 7015 list.add(ri); 7016 } 7017 return list; 7018 } 7019 7020 // reader 7021 synchronized (mPackages) { 7022 String pkgName = intent.getPackage(); 7023 if (pkgName == null) { 7024 return mServices.queryIntent(intent, resolvedType, flags, userId); 7025 } 7026 final PackageParser.Package pkg = mPackages.get(pkgName); 7027 if (pkg != null) { 7028 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7029 userId); 7030 } 7031 return Collections.emptyList(); 7032 } 7033 } 7034 7035 @Override 7036 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7037 String resolvedType, int flags, int userId) { 7038 return new ParceledListSlice<>( 7039 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7040 } 7041 7042 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7043 Intent intent, String resolvedType, int flags, int userId) { 7044 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7045 flags = updateFlagsForResolve(flags, userId, intent, false); 7046 ComponentName comp = intent.getComponent(); 7047 if (comp == null) { 7048 if (intent.getSelector() != null) { 7049 intent = intent.getSelector(); 7050 comp = intent.getComponent(); 7051 } 7052 } 7053 if (comp != null) { 7054 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7055 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7056 if (pi != null) { 7057 final ResolveInfo ri = new ResolveInfo(); 7058 ri.providerInfo = pi; 7059 list.add(ri); 7060 } 7061 return list; 7062 } 7063 7064 // reader 7065 synchronized (mPackages) { 7066 String pkgName = intent.getPackage(); 7067 if (pkgName == null) { 7068 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7069 } 7070 final PackageParser.Package pkg = mPackages.get(pkgName); 7071 if (pkg != null) { 7072 return mProviders.queryIntentForPackage( 7073 intent, resolvedType, flags, pkg.providers, userId); 7074 } 7075 return Collections.emptyList(); 7076 } 7077 } 7078 7079 @Override 7080 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7081 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7082 flags = updateFlagsForPackage(flags, userId, null); 7083 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7084 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7085 true /* requireFullPermission */, false /* checkShell */, 7086 "get installed packages"); 7087 7088 // writer 7089 synchronized (mPackages) { 7090 ArrayList<PackageInfo> list; 7091 if (listUninstalled) { 7092 list = new ArrayList<>(mSettings.mPackages.size()); 7093 for (PackageSetting ps : mSettings.mPackages.values()) { 7094 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7095 continue; 7096 } 7097 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7098 if (pi != null) { 7099 list.add(pi); 7100 } 7101 } 7102 } else { 7103 list = new ArrayList<>(mPackages.size()); 7104 for (PackageParser.Package p : mPackages.values()) { 7105 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7106 Binder.getCallingUid(), userId)) { 7107 continue; 7108 } 7109 final PackageInfo pi = generatePackageInfo((PackageSetting) 7110 p.mExtras, flags, userId); 7111 if (pi != null) { 7112 list.add(pi); 7113 } 7114 } 7115 } 7116 7117 return new ParceledListSlice<>(list); 7118 } 7119 } 7120 7121 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7122 String[] permissions, boolean[] tmp, int flags, int userId) { 7123 int numMatch = 0; 7124 final PermissionsState permissionsState = ps.getPermissionsState(); 7125 for (int i=0; i<permissions.length; i++) { 7126 final String permission = permissions[i]; 7127 if (permissionsState.hasPermission(permission, userId)) { 7128 tmp[i] = true; 7129 numMatch++; 7130 } else { 7131 tmp[i] = false; 7132 } 7133 } 7134 if (numMatch == 0) { 7135 return; 7136 } 7137 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7138 7139 // The above might return null in cases of uninstalled apps or install-state 7140 // skew across users/profiles. 7141 if (pi != null) { 7142 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7143 if (numMatch == permissions.length) { 7144 pi.requestedPermissions = permissions; 7145 } else { 7146 pi.requestedPermissions = new String[numMatch]; 7147 numMatch = 0; 7148 for (int i=0; i<permissions.length; i++) { 7149 if (tmp[i]) { 7150 pi.requestedPermissions[numMatch] = permissions[i]; 7151 numMatch++; 7152 } 7153 } 7154 } 7155 } 7156 list.add(pi); 7157 } 7158 } 7159 7160 @Override 7161 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7162 String[] permissions, int flags, int userId) { 7163 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7164 flags = updateFlagsForPackage(flags, userId, permissions); 7165 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7166 true /* requireFullPermission */, false /* checkShell */, 7167 "get packages holding permissions"); 7168 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7169 7170 // writer 7171 synchronized (mPackages) { 7172 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7173 boolean[] tmpBools = new boolean[permissions.length]; 7174 if (listUninstalled) { 7175 for (PackageSetting ps : mSettings.mPackages.values()) { 7176 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7177 userId); 7178 } 7179 } else { 7180 for (PackageParser.Package pkg : mPackages.values()) { 7181 PackageSetting ps = (PackageSetting)pkg.mExtras; 7182 if (ps != null) { 7183 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7184 userId); 7185 } 7186 } 7187 } 7188 7189 return new ParceledListSlice<PackageInfo>(list); 7190 } 7191 } 7192 7193 @Override 7194 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7195 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7196 flags = updateFlagsForApplication(flags, userId, null); 7197 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7198 7199 // writer 7200 synchronized (mPackages) { 7201 ArrayList<ApplicationInfo> list; 7202 if (listUninstalled) { 7203 list = new ArrayList<>(mSettings.mPackages.size()); 7204 for (PackageSetting ps : mSettings.mPackages.values()) { 7205 ApplicationInfo ai; 7206 int effectiveFlags = flags; 7207 if (ps.isSystem()) { 7208 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7209 } 7210 if (ps.pkg != null) { 7211 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7212 continue; 7213 } 7214 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7215 ps.readUserState(userId), userId); 7216 if (ai != null) { 7217 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7218 } 7219 } else { 7220 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7221 // and already converts to externally visible package name 7222 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7223 Binder.getCallingUid(), effectiveFlags, userId); 7224 } 7225 if (ai != null) { 7226 list.add(ai); 7227 } 7228 } 7229 } else { 7230 list = new ArrayList<>(mPackages.size()); 7231 for (PackageParser.Package p : mPackages.values()) { 7232 if (p.mExtras != null) { 7233 PackageSetting ps = (PackageSetting) p.mExtras; 7234 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7235 continue; 7236 } 7237 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7238 ps.readUserState(userId), userId); 7239 if (ai != null) { 7240 ai.packageName = resolveExternalPackageNameLPr(p); 7241 list.add(ai); 7242 } 7243 } 7244 } 7245 } 7246 7247 return new ParceledListSlice<>(list); 7248 } 7249 } 7250 7251 @Override 7252 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7253 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7254 return null; 7255 } 7256 7257 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7258 "getEphemeralApplications"); 7259 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7260 true /* requireFullPermission */, false /* checkShell */, 7261 "getEphemeralApplications"); 7262 synchronized (mPackages) { 7263 List<InstantAppInfo> instantApps = mInstantAppRegistry 7264 .getInstantAppsLPr(userId); 7265 if (instantApps != null) { 7266 return new ParceledListSlice<>(instantApps); 7267 } 7268 } 7269 return null; 7270 } 7271 7272 @Override 7273 public boolean isInstantApp(String packageName, int userId) { 7274 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7275 true /* requireFullPermission */, false /* checkShell */, 7276 "isInstantApp"); 7277 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7278 return false; 7279 } 7280 7281 if (!isCallerSameApp(packageName)) { 7282 return false; 7283 } 7284 synchronized (mPackages) { 7285 final PackageSetting ps = mSettings.mPackages.get(packageName); 7286 if (ps != null) { 7287 return ps.getInstantApp(userId); 7288 } 7289 } 7290 return false; 7291 } 7292 7293 @Override 7294 public byte[] getInstantAppCookie(String packageName, int userId) { 7295 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7296 return null; 7297 } 7298 7299 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7300 true /* requireFullPermission */, false /* checkShell */, 7301 "getInstantAppCookie"); 7302 if (!isCallerSameApp(packageName)) { 7303 return null; 7304 } 7305 synchronized (mPackages) { 7306 return mInstantAppRegistry.getInstantAppCookieLPw( 7307 packageName, userId); 7308 } 7309 } 7310 7311 @Override 7312 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7313 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7314 return true; 7315 } 7316 7317 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7318 true /* requireFullPermission */, true /* checkShell */, 7319 "setInstantAppCookie"); 7320 if (!isCallerSameApp(packageName)) { 7321 return false; 7322 } 7323 synchronized (mPackages) { 7324 return mInstantAppRegistry.setInstantAppCookieLPw( 7325 packageName, cookie, userId); 7326 } 7327 } 7328 7329 @Override 7330 public Bitmap getInstantAppIcon(String packageName, int userId) { 7331 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7332 return null; 7333 } 7334 7335 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7336 "getInstantAppIcon"); 7337 7338 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7339 true /* requireFullPermission */, false /* checkShell */, 7340 "getInstantAppIcon"); 7341 7342 synchronized (mPackages) { 7343 return mInstantAppRegistry.getInstantAppIconLPw( 7344 packageName, userId); 7345 } 7346 } 7347 7348 private boolean isCallerSameApp(String packageName) { 7349 PackageParser.Package pkg = mPackages.get(packageName); 7350 return pkg != null 7351 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7352 } 7353 7354 @Override 7355 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7356 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7357 } 7358 7359 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7360 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7361 7362 // reader 7363 synchronized (mPackages) { 7364 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7365 final int userId = UserHandle.getCallingUserId(); 7366 while (i.hasNext()) { 7367 final PackageParser.Package p = i.next(); 7368 if (p.applicationInfo == null) continue; 7369 7370 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7371 && !p.applicationInfo.isDirectBootAware(); 7372 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7373 && p.applicationInfo.isDirectBootAware(); 7374 7375 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7376 && (!mSafeMode || isSystemApp(p)) 7377 && (matchesUnaware || matchesAware)) { 7378 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7379 if (ps != null) { 7380 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7381 ps.readUserState(userId), userId); 7382 if (ai != null) { 7383 finalList.add(ai); 7384 } 7385 } 7386 } 7387 } 7388 } 7389 7390 return finalList; 7391 } 7392 7393 @Override 7394 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7395 if (!sUserManager.exists(userId)) return null; 7396 flags = updateFlagsForComponent(flags, userId, name); 7397 // reader 7398 synchronized (mPackages) { 7399 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7400 PackageSetting ps = provider != null 7401 ? mSettings.mPackages.get(provider.owner.packageName) 7402 : null; 7403 return ps != null 7404 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7405 ? PackageParser.generateProviderInfo(provider, flags, 7406 ps.readUserState(userId), userId) 7407 : null; 7408 } 7409 } 7410 7411 /** 7412 * @deprecated 7413 */ 7414 @Deprecated 7415 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7416 // reader 7417 synchronized (mPackages) { 7418 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7419 .entrySet().iterator(); 7420 final int userId = UserHandle.getCallingUserId(); 7421 while (i.hasNext()) { 7422 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7423 PackageParser.Provider p = entry.getValue(); 7424 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7425 7426 if (ps != null && p.syncable 7427 && (!mSafeMode || (p.info.applicationInfo.flags 7428 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7429 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7430 ps.readUserState(userId), userId); 7431 if (info != null) { 7432 outNames.add(entry.getKey()); 7433 outInfo.add(info); 7434 } 7435 } 7436 } 7437 } 7438 } 7439 7440 @Override 7441 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7442 int uid, int flags) { 7443 final int userId = processName != null ? UserHandle.getUserId(uid) 7444 : UserHandle.getCallingUserId(); 7445 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7446 flags = updateFlagsForComponent(flags, userId, processName); 7447 7448 ArrayList<ProviderInfo> finalList = null; 7449 // reader 7450 synchronized (mPackages) { 7451 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7452 while (i.hasNext()) { 7453 final PackageParser.Provider p = i.next(); 7454 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7455 if (ps != null && p.info.authority != null 7456 && (processName == null 7457 || (p.info.processName.equals(processName) 7458 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7459 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7460 if (finalList == null) { 7461 finalList = new ArrayList<ProviderInfo>(3); 7462 } 7463 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7464 ps.readUserState(userId), userId); 7465 if (info != null) { 7466 finalList.add(info); 7467 } 7468 } 7469 } 7470 } 7471 7472 if (finalList != null) { 7473 Collections.sort(finalList, mProviderInitOrderSorter); 7474 return new ParceledListSlice<ProviderInfo>(finalList); 7475 } 7476 7477 return ParceledListSlice.emptyList(); 7478 } 7479 7480 @Override 7481 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7482 // reader 7483 synchronized (mPackages) { 7484 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7485 return PackageParser.generateInstrumentationInfo(i, flags); 7486 } 7487 } 7488 7489 @Override 7490 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7491 String targetPackage, int flags) { 7492 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7493 } 7494 7495 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7496 int flags) { 7497 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7498 7499 // reader 7500 synchronized (mPackages) { 7501 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7502 while (i.hasNext()) { 7503 final PackageParser.Instrumentation p = i.next(); 7504 if (targetPackage == null 7505 || targetPackage.equals(p.info.targetPackage)) { 7506 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7507 flags); 7508 if (ii != null) { 7509 finalList.add(ii); 7510 } 7511 } 7512 } 7513 } 7514 7515 return finalList; 7516 } 7517 7518 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 7519 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 7520 if (overlays == null) { 7521 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 7522 return; 7523 } 7524 for (PackageParser.Package opkg : overlays.values()) { 7525 // Not much to do if idmap fails: we already logged the error 7526 // and we certainly don't want to abort installation of pkg simply 7527 // because an overlay didn't fit properly. For these reasons, 7528 // ignore the return value of createIdmapForPackagePairLI. 7529 createIdmapForPackagePairLI(pkg, opkg); 7530 } 7531 } 7532 7533 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 7534 PackageParser.Package opkg) { 7535 if (!opkg.mTrustedOverlay) { 7536 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 7537 opkg.baseCodePath + ": overlay not trusted"); 7538 return false; 7539 } 7540 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 7541 if (overlaySet == null) { 7542 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 7543 opkg.baseCodePath + " but target package has no known overlays"); 7544 return false; 7545 } 7546 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7547 // TODO: generate idmap for split APKs 7548 try { 7549 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 7550 } catch (InstallerException e) { 7551 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 7552 + opkg.baseCodePath); 7553 return false; 7554 } 7555 PackageParser.Package[] overlayArray = 7556 overlaySet.values().toArray(new PackageParser.Package[0]); 7557 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7558 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7559 return p1.mOverlayPriority - p2.mOverlayPriority; 7560 } 7561 }; 7562 Arrays.sort(overlayArray, cmp); 7563 7564 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7565 int i = 0; 7566 for (PackageParser.Package p : overlayArray) { 7567 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7568 } 7569 return true; 7570 } 7571 7572 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7573 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7574 try { 7575 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7576 } finally { 7577 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7578 } 7579 } 7580 7581 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7582 final File[] files = dir.listFiles(); 7583 if (ArrayUtils.isEmpty(files)) { 7584 Log.d(TAG, "No files in app dir " + dir); 7585 return; 7586 } 7587 7588 if (DEBUG_PACKAGE_SCANNING) { 7589 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7590 + " flags=0x" + Integer.toHexString(parseFlags)); 7591 } 7592 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7593 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7594 7595 // Submit files for parsing in parallel 7596 int fileCount = 0; 7597 for (File file : files) { 7598 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7599 && !PackageInstallerService.isStageName(file.getName()); 7600 if (!isPackage) { 7601 // Ignore entries which are not packages 7602 continue; 7603 } 7604 parallelPackageParser.submit(file, parseFlags); 7605 fileCount++; 7606 } 7607 7608 // Process results one by one 7609 for (; fileCount > 0; fileCount--) { 7610 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7611 Throwable throwable = parseResult.throwable; 7612 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7613 7614 if (throwable == null) { 7615 // Static shared libraries have synthetic package names 7616 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7617 renameStaticSharedLibraryPackage(parseResult.pkg); 7618 } 7619 try { 7620 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7621 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7622 currentTime, null); 7623 } 7624 } catch (PackageManagerException e) { 7625 errorCode = e.error; 7626 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7627 } 7628 } else if (throwable instanceof PackageParser.PackageParserException) { 7629 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7630 throwable; 7631 errorCode = e.error; 7632 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7633 } else { 7634 throw new IllegalStateException("Unexpected exception occurred while parsing " 7635 + parseResult.scanFile, throwable); 7636 } 7637 7638 // Delete invalid userdata apps 7639 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7640 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7641 logCriticalInfo(Log.WARN, 7642 "Deleting invalid package at " + parseResult.scanFile); 7643 removeCodePathLI(parseResult.scanFile); 7644 } 7645 } 7646 parallelPackageParser.close(); 7647 } 7648 7649 private static File getSettingsProblemFile() { 7650 File dataDir = Environment.getDataDirectory(); 7651 File systemDir = new File(dataDir, "system"); 7652 File fname = new File(systemDir, "uiderrors.txt"); 7653 return fname; 7654 } 7655 7656 static void reportSettingsProblem(int priority, String msg) { 7657 logCriticalInfo(priority, msg); 7658 } 7659 7660 static void logCriticalInfo(int priority, String msg) { 7661 Slog.println(priority, TAG, msg); 7662 EventLogTags.writePmCriticalInfo(msg); 7663 try { 7664 File fname = getSettingsProblemFile(); 7665 FileOutputStream out = new FileOutputStream(fname, true); 7666 PrintWriter pw = new FastPrintWriter(out); 7667 SimpleDateFormat formatter = new SimpleDateFormat(); 7668 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7669 pw.println(dateString + ": " + msg); 7670 pw.close(); 7671 FileUtils.setPermissions( 7672 fname.toString(), 7673 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7674 -1, -1); 7675 } catch (java.io.IOException e) { 7676 } 7677 } 7678 7679 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7680 if (srcFile.isDirectory()) { 7681 final File baseFile = new File(pkg.baseCodePath); 7682 long maxModifiedTime = baseFile.lastModified(); 7683 if (pkg.splitCodePaths != null) { 7684 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7685 final File splitFile = new File(pkg.splitCodePaths[i]); 7686 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7687 } 7688 } 7689 return maxModifiedTime; 7690 } 7691 return srcFile.lastModified(); 7692 } 7693 7694 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7695 final int policyFlags) throws PackageManagerException { 7696 // When upgrading from pre-N MR1, verify the package time stamp using the package 7697 // directory and not the APK file. 7698 final long lastModifiedTime = mIsPreNMR1Upgrade 7699 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7700 if (ps != null 7701 && ps.codePath.equals(srcFile) 7702 && ps.timeStamp == lastModifiedTime 7703 && !isCompatSignatureUpdateNeeded(pkg) 7704 && !isRecoverSignatureUpdateNeeded(pkg)) { 7705 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7706 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7707 ArraySet<PublicKey> signingKs; 7708 synchronized (mPackages) { 7709 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7710 } 7711 if (ps.signatures.mSignatures != null 7712 && ps.signatures.mSignatures.length != 0 7713 && signingKs != null) { 7714 // Optimization: reuse the existing cached certificates 7715 // if the package appears to be unchanged. 7716 pkg.mSignatures = ps.signatures.mSignatures; 7717 pkg.mSigningKeys = signingKs; 7718 return; 7719 } 7720 7721 Slog.w(TAG, "PackageSetting for " + ps.name 7722 + " is missing signatures. Collecting certs again to recover them."); 7723 } else { 7724 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7725 } 7726 7727 try { 7728 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7729 PackageParser.collectCertificates(pkg, policyFlags); 7730 } catch (PackageParserException e) { 7731 throw PackageManagerException.from(e); 7732 } finally { 7733 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7734 } 7735 } 7736 7737 /** 7738 * Traces a package scan. 7739 * @see #scanPackageLI(File, int, int, long, UserHandle) 7740 */ 7741 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7742 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7743 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7744 try { 7745 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7746 } finally { 7747 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7748 } 7749 } 7750 7751 /** 7752 * Scans a package and returns the newly parsed package. 7753 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7754 */ 7755 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7756 long currentTime, UserHandle user) throws PackageManagerException { 7757 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7758 PackageParser pp = new PackageParser(); 7759 pp.setSeparateProcesses(mSeparateProcesses); 7760 pp.setOnlyCoreApps(mOnlyCore); 7761 pp.setDisplayMetrics(mMetrics); 7762 7763 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7764 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7765 } 7766 7767 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7768 final PackageParser.Package pkg; 7769 try { 7770 pkg = pp.parsePackage(scanFile, parseFlags); 7771 } catch (PackageParserException e) { 7772 throw PackageManagerException.from(e); 7773 } finally { 7774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7775 } 7776 7777 // Static shared libraries have synthetic package names 7778 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7779 renameStaticSharedLibraryPackage(pkg); 7780 } 7781 7782 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7783 } 7784 7785 /** 7786 * Scans a package and returns the newly parsed package. 7787 * @throws PackageManagerException on a parse error. 7788 */ 7789 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7790 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7791 throws PackageManagerException { 7792 // If the package has children and this is the first dive in the function 7793 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7794 // packages (parent and children) would be successfully scanned before the 7795 // actual scan since scanning mutates internal state and we want to atomically 7796 // install the package and its children. 7797 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7798 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7799 scanFlags |= SCAN_CHECK_ONLY; 7800 } 7801 } else { 7802 scanFlags &= ~SCAN_CHECK_ONLY; 7803 } 7804 7805 // Scan the parent 7806 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7807 scanFlags, currentTime, user); 7808 7809 // Scan the children 7810 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7811 for (int i = 0; i < childCount; i++) { 7812 PackageParser.Package childPackage = pkg.childPackages.get(i); 7813 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7814 currentTime, user); 7815 } 7816 7817 7818 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7819 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7820 } 7821 7822 return scannedPkg; 7823 } 7824 7825 /** 7826 * Scans a package and returns the newly parsed package. 7827 * @throws PackageManagerException on a parse error. 7828 */ 7829 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7830 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7831 throws PackageManagerException { 7832 PackageSetting ps = null; 7833 PackageSetting updatedPkg; 7834 // reader 7835 synchronized (mPackages) { 7836 // Look to see if we already know about this package. 7837 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7838 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7839 // This package has been renamed to its original name. Let's 7840 // use that. 7841 ps = mSettings.getPackageLPr(oldName); 7842 } 7843 // If there was no original package, see one for the real package name. 7844 if (ps == null) { 7845 ps = mSettings.getPackageLPr(pkg.packageName); 7846 } 7847 // Check to see if this package could be hiding/updating a system 7848 // package. Must look for it either under the original or real 7849 // package name depending on our state. 7850 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7851 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7852 7853 // If this is a package we don't know about on the system partition, we 7854 // may need to remove disabled child packages on the system partition 7855 // or may need to not add child packages if the parent apk is updated 7856 // on the data partition and no longer defines this child package. 7857 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7858 // If this is a parent package for an updated system app and this system 7859 // app got an OTA update which no longer defines some of the child packages 7860 // we have to prune them from the disabled system packages. 7861 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7862 if (disabledPs != null) { 7863 final int scannedChildCount = (pkg.childPackages != null) 7864 ? pkg.childPackages.size() : 0; 7865 final int disabledChildCount = disabledPs.childPackageNames != null 7866 ? disabledPs.childPackageNames.size() : 0; 7867 for (int i = 0; i < disabledChildCount; i++) { 7868 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7869 boolean disabledPackageAvailable = false; 7870 for (int j = 0; j < scannedChildCount; j++) { 7871 PackageParser.Package childPkg = pkg.childPackages.get(j); 7872 if (childPkg.packageName.equals(disabledChildPackageName)) { 7873 disabledPackageAvailable = true; 7874 break; 7875 } 7876 } 7877 if (!disabledPackageAvailable) { 7878 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7879 } 7880 } 7881 } 7882 } 7883 } 7884 7885 boolean updatedPkgBetter = false; 7886 // First check if this is a system package that may involve an update 7887 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7888 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7889 // it needs to drop FLAG_PRIVILEGED. 7890 if (locationIsPrivileged(scanFile)) { 7891 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7892 } else { 7893 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7894 } 7895 7896 if (ps != null && !ps.codePath.equals(scanFile)) { 7897 // The path has changed from what was last scanned... check the 7898 // version of the new path against what we have stored to determine 7899 // what to do. 7900 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7901 if (pkg.mVersionCode <= ps.versionCode) { 7902 // The system package has been updated and the code path does not match 7903 // Ignore entry. Skip it. 7904 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7905 + " ignored: updated version " + ps.versionCode 7906 + " better than this " + pkg.mVersionCode); 7907 if (!updatedPkg.codePath.equals(scanFile)) { 7908 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7909 + ps.name + " changing from " + updatedPkg.codePathString 7910 + " to " + scanFile); 7911 updatedPkg.codePath = scanFile; 7912 updatedPkg.codePathString = scanFile.toString(); 7913 updatedPkg.resourcePath = scanFile; 7914 updatedPkg.resourcePathString = scanFile.toString(); 7915 } 7916 updatedPkg.pkg = pkg; 7917 updatedPkg.versionCode = pkg.mVersionCode; 7918 7919 // Update the disabled system child packages to point to the package too. 7920 final int childCount = updatedPkg.childPackageNames != null 7921 ? updatedPkg.childPackageNames.size() : 0; 7922 for (int i = 0; i < childCount; i++) { 7923 String childPackageName = updatedPkg.childPackageNames.get(i); 7924 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7925 childPackageName); 7926 if (updatedChildPkg != null) { 7927 updatedChildPkg.pkg = pkg; 7928 updatedChildPkg.versionCode = pkg.mVersionCode; 7929 } 7930 } 7931 7932 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7933 + scanFile + " ignored: updated version " + ps.versionCode 7934 + " better than this " + pkg.mVersionCode); 7935 } else { 7936 // The current app on the system partition is better than 7937 // what we have updated to on the data partition; switch 7938 // back to the system partition version. 7939 // At this point, its safely assumed that package installation for 7940 // apps in system partition will go through. If not there won't be a working 7941 // version of the app 7942 // writer 7943 synchronized (mPackages) { 7944 // Just remove the loaded entries from package lists. 7945 mPackages.remove(ps.name); 7946 } 7947 7948 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7949 + " reverting from " + ps.codePathString 7950 + ": new version " + pkg.mVersionCode 7951 + " better than installed " + ps.versionCode); 7952 7953 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7954 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7955 synchronized (mInstallLock) { 7956 args.cleanUpResourcesLI(); 7957 } 7958 synchronized (mPackages) { 7959 mSettings.enableSystemPackageLPw(ps.name); 7960 } 7961 updatedPkgBetter = true; 7962 } 7963 } 7964 } 7965 7966 if (updatedPkg != null) { 7967 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7968 // initially 7969 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7970 7971 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7972 // flag set initially 7973 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7974 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7975 } 7976 } 7977 7978 // Verify certificates against what was last scanned 7979 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7980 7981 /* 7982 * A new system app appeared, but we already had a non-system one of the 7983 * same name installed earlier. 7984 */ 7985 boolean shouldHideSystemApp = false; 7986 if (updatedPkg == null && ps != null 7987 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7988 /* 7989 * Check to make sure the signatures match first. If they don't, 7990 * wipe the installed application and its data. 7991 */ 7992 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7993 != PackageManager.SIGNATURE_MATCH) { 7994 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7995 + " signatures don't match existing userdata copy; removing"); 7996 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7997 "scanPackageInternalLI")) { 7998 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7999 } 8000 ps = null; 8001 } else { 8002 /* 8003 * If the newly-added system app is an older version than the 8004 * already installed version, hide it. It will be scanned later 8005 * and re-added like an update. 8006 */ 8007 if (pkg.mVersionCode <= ps.versionCode) { 8008 shouldHideSystemApp = true; 8009 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8010 + " but new version " + pkg.mVersionCode + " better than installed " 8011 + ps.versionCode + "; hiding system"); 8012 } else { 8013 /* 8014 * The newly found system app is a newer version that the 8015 * one previously installed. Simply remove the 8016 * already-installed application and replace it with our own 8017 * while keeping the application data. 8018 */ 8019 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8020 + " reverting from " + ps.codePathString + ": new version " 8021 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8022 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8023 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8024 synchronized (mInstallLock) { 8025 args.cleanUpResourcesLI(); 8026 } 8027 } 8028 } 8029 } 8030 8031 // The apk is forward locked (not public) if its code and resources 8032 // are kept in different files. (except for app in either system or 8033 // vendor path). 8034 // TODO grab this value from PackageSettings 8035 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8036 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8037 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8038 } 8039 } 8040 8041 // TODO: extend to support forward-locked splits 8042 String resourcePath = null; 8043 String baseResourcePath = null; 8044 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8045 if (ps != null && ps.resourcePathString != null) { 8046 resourcePath = ps.resourcePathString; 8047 baseResourcePath = ps.resourcePathString; 8048 } else { 8049 // Should not happen at all. Just log an error. 8050 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8051 } 8052 } else { 8053 resourcePath = pkg.codePath; 8054 baseResourcePath = pkg.baseCodePath; 8055 } 8056 8057 // Set application objects path explicitly. 8058 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8059 pkg.setApplicationInfoCodePath(pkg.codePath); 8060 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8061 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8062 pkg.setApplicationInfoResourcePath(resourcePath); 8063 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8064 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8065 8066 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8067 if (ps != null && ps.getInstantApp(userId)) { 8068 scanFlags |= SCAN_AS_INSTANT_APP; 8069 } 8070 8071 // Note that we invoke the following method only if we are about to unpack an application 8072 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8073 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8074 8075 /* 8076 * If the system app should be overridden by a previously installed 8077 * data, hide the system app now and let the /data/app scan pick it up 8078 * again. 8079 */ 8080 if (shouldHideSystemApp) { 8081 synchronized (mPackages) { 8082 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8083 } 8084 } 8085 8086 return scannedPkg; 8087 } 8088 8089 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8090 // Derive the new package synthetic package name 8091 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8092 + pkg.staticSharedLibVersion); 8093 } 8094 8095 private static String fixProcessName(String defProcessName, 8096 String processName) { 8097 if (processName == null) { 8098 return defProcessName; 8099 } 8100 return processName; 8101 } 8102 8103 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8104 throws PackageManagerException { 8105 if (pkgSetting.signatures.mSignatures != null) { 8106 // Already existing package. Make sure signatures match 8107 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8108 == PackageManager.SIGNATURE_MATCH; 8109 if (!match) { 8110 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8111 == PackageManager.SIGNATURE_MATCH; 8112 } 8113 if (!match) { 8114 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8115 == PackageManager.SIGNATURE_MATCH; 8116 } 8117 if (!match) { 8118 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8119 + pkg.packageName + " signatures do not match the " 8120 + "previously installed version; ignoring!"); 8121 } 8122 } 8123 8124 // Check for shared user signatures 8125 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8126 // Already existing package. Make sure signatures match 8127 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8128 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8129 if (!match) { 8130 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8131 == PackageManager.SIGNATURE_MATCH; 8132 } 8133 if (!match) { 8134 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8135 == PackageManager.SIGNATURE_MATCH; 8136 } 8137 if (!match) { 8138 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8139 "Package " + pkg.packageName 8140 + " has no signatures that match those in shared user " 8141 + pkgSetting.sharedUser.name + "; ignoring!"); 8142 } 8143 } 8144 } 8145 8146 /** 8147 * Enforces that only the system UID or root's UID can call a method exposed 8148 * via Binder. 8149 * 8150 * @param message used as message if SecurityException is thrown 8151 * @throws SecurityException if the caller is not system or root 8152 */ 8153 private static final void enforceSystemOrRoot(String message) { 8154 final int uid = Binder.getCallingUid(); 8155 if (uid != Process.SYSTEM_UID && uid != 0) { 8156 throw new SecurityException(message); 8157 } 8158 } 8159 8160 @Override 8161 public void performFstrimIfNeeded() { 8162 enforceSystemOrRoot("Only the system can request fstrim"); 8163 8164 // Before everything else, see whether we need to fstrim. 8165 try { 8166 IStorageManager sm = PackageHelper.getStorageManager(); 8167 if (sm != null) { 8168 boolean doTrim = false; 8169 final long interval = android.provider.Settings.Global.getLong( 8170 mContext.getContentResolver(), 8171 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8172 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8173 if (interval > 0) { 8174 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8175 if (timeSinceLast > interval) { 8176 doTrim = true; 8177 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8178 + "; running immediately"); 8179 } 8180 } 8181 if (doTrim) { 8182 final boolean dexOptDialogShown; 8183 synchronized (mPackages) { 8184 dexOptDialogShown = mDexOptDialogShown; 8185 } 8186 if (!isFirstBoot() && dexOptDialogShown) { 8187 try { 8188 ActivityManager.getService().showBootMessage( 8189 mContext.getResources().getString( 8190 R.string.android_upgrading_fstrim), true); 8191 } catch (RemoteException e) { 8192 } 8193 } 8194 sm.runMaintenance(); 8195 } 8196 } else { 8197 Slog.e(TAG, "storageManager service unavailable!"); 8198 } 8199 } catch (RemoteException e) { 8200 // Can't happen; StorageManagerService is local 8201 } 8202 } 8203 8204 @Override 8205 public void updatePackagesIfNeeded() { 8206 enforceSystemOrRoot("Only the system can request package update"); 8207 8208 // We need to re-extract after an OTA. 8209 boolean causeUpgrade = isUpgrade(); 8210 8211 // First boot or factory reset. 8212 // Note: we also handle devices that are upgrading to N right now as if it is their 8213 // first boot, as they do not have profile data. 8214 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8215 8216 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8217 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8218 8219 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8220 return; 8221 } 8222 8223 List<PackageParser.Package> pkgs; 8224 synchronized (mPackages) { 8225 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8226 } 8227 8228 final long startTime = System.nanoTime(); 8229 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8230 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8231 8232 final int elapsedTimeSeconds = 8233 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8234 8235 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8236 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8237 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8238 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8239 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8240 } 8241 8242 /** 8243 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8244 * containing statistics about the invocation. The array consists of three elements, 8245 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8246 * and {@code numberOfPackagesFailed}. 8247 */ 8248 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8249 String compilerFilter) { 8250 8251 int numberOfPackagesVisited = 0; 8252 int numberOfPackagesOptimized = 0; 8253 int numberOfPackagesSkipped = 0; 8254 int numberOfPackagesFailed = 0; 8255 final int numberOfPackagesToDexopt = pkgs.size(); 8256 8257 for (PackageParser.Package pkg : pkgs) { 8258 numberOfPackagesVisited++; 8259 8260 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8261 if (DEBUG_DEXOPT) { 8262 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8263 } 8264 numberOfPackagesSkipped++; 8265 continue; 8266 } 8267 8268 if (DEBUG_DEXOPT) { 8269 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8270 numberOfPackagesToDexopt + ": " + pkg.packageName); 8271 } 8272 8273 if (showDialog) { 8274 try { 8275 ActivityManager.getService().showBootMessage( 8276 mContext.getResources().getString(R.string.android_upgrading_apk, 8277 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8278 } catch (RemoteException e) { 8279 } 8280 synchronized (mPackages) { 8281 mDexOptDialogShown = true; 8282 } 8283 } 8284 8285 // If the OTA updates a system app which was previously preopted to a non-preopted state 8286 // the app might end up being verified at runtime. That's because by default the apps 8287 // are verify-profile but for preopted apps there's no profile. 8288 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8289 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8290 // filter (by default interpret-only). 8291 // Note that at this stage unused apps are already filtered. 8292 if (isSystemApp(pkg) && 8293 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8294 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8295 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8296 } 8297 8298 // checkProfiles is false to avoid merging profiles during boot which 8299 // might interfere with background compilation (b/28612421). 8300 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8301 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8302 // trade-off worth doing to save boot time work. 8303 int dexOptStatus = performDexOptTraced(pkg.packageName, 8304 false /* checkProfiles */, 8305 compilerFilter, 8306 false /* force */); 8307 switch (dexOptStatus) { 8308 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8309 numberOfPackagesOptimized++; 8310 break; 8311 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8312 numberOfPackagesSkipped++; 8313 break; 8314 case PackageDexOptimizer.DEX_OPT_FAILED: 8315 numberOfPackagesFailed++; 8316 break; 8317 default: 8318 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8319 break; 8320 } 8321 } 8322 8323 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8324 numberOfPackagesFailed }; 8325 } 8326 8327 @Override 8328 public void notifyPackageUse(String packageName, int reason) { 8329 synchronized (mPackages) { 8330 PackageParser.Package p = mPackages.get(packageName); 8331 if (p == null) { 8332 return; 8333 } 8334 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8335 } 8336 } 8337 8338 @Override 8339 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8340 int userId = UserHandle.getCallingUserId(); 8341 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8342 if (ai == null) { 8343 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8344 + loadingPackageName + ", user=" + userId); 8345 return; 8346 } 8347 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8348 } 8349 8350 // TODO: this is not used nor needed. Delete it. 8351 @Override 8352 public boolean performDexOptIfNeeded(String packageName) { 8353 int dexOptStatus = performDexOptTraced(packageName, 8354 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8355 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8356 } 8357 8358 @Override 8359 public boolean performDexOpt(String packageName, 8360 boolean checkProfiles, int compileReason, boolean force) { 8361 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8362 getCompilerFilterForReason(compileReason), force); 8363 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8364 } 8365 8366 @Override 8367 public boolean performDexOptMode(String packageName, 8368 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8369 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8370 targetCompilerFilter, force); 8371 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8372 } 8373 8374 private int performDexOptTraced(String packageName, 8375 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8376 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8377 try { 8378 return performDexOptInternal(packageName, checkProfiles, 8379 targetCompilerFilter, force); 8380 } finally { 8381 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8382 } 8383 } 8384 8385 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8386 // if the package can now be considered up to date for the given filter. 8387 private int performDexOptInternal(String packageName, 8388 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8389 PackageParser.Package p; 8390 synchronized (mPackages) { 8391 p = mPackages.get(packageName); 8392 if (p == null) { 8393 // Package could not be found. Report failure. 8394 return PackageDexOptimizer.DEX_OPT_FAILED; 8395 } 8396 mPackageUsage.maybeWriteAsync(mPackages); 8397 mCompilerStats.maybeWriteAsync(); 8398 } 8399 long callingId = Binder.clearCallingIdentity(); 8400 try { 8401 synchronized (mInstallLock) { 8402 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8403 targetCompilerFilter, force); 8404 } 8405 } finally { 8406 Binder.restoreCallingIdentity(callingId); 8407 } 8408 } 8409 8410 public ArraySet<String> getOptimizablePackages() { 8411 ArraySet<String> pkgs = new ArraySet<String>(); 8412 synchronized (mPackages) { 8413 for (PackageParser.Package p : mPackages.values()) { 8414 if (PackageDexOptimizer.canOptimizePackage(p)) { 8415 pkgs.add(p.packageName); 8416 } 8417 } 8418 } 8419 return pkgs; 8420 } 8421 8422 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8423 boolean checkProfiles, String targetCompilerFilter, 8424 boolean force) { 8425 // Select the dex optimizer based on the force parameter. 8426 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8427 // allocate an object here. 8428 PackageDexOptimizer pdo = force 8429 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8430 : mPackageDexOptimizer; 8431 8432 // Optimize all dependencies first. Note: we ignore the return value and march on 8433 // on errors. 8434 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8435 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8436 if (!deps.isEmpty()) { 8437 for (PackageParser.Package depPackage : deps) { 8438 // TODO: Analyze and investigate if we (should) profile libraries. 8439 // Currently this will do a full compilation of the library by default. 8440 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8441 false /* checkProfiles */, 8442 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8443 getOrCreateCompilerPackageStats(depPackage)); 8444 } 8445 } 8446 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8447 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8448 } 8449 8450 // Performs dexopt on the used secondary dex files belonging to the given package. 8451 // Returns true if all dex files were process successfully (which could mean either dexopt or 8452 // skip). Returns false if any of the files caused errors. 8453 @Override 8454 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8455 boolean force) { 8456 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8457 } 8458 8459 /** 8460 * Reconcile the information we have about the secondary dex files belonging to 8461 * {@code packagName} and the actual dex files. For all dex files that were 8462 * deleted, update the internal records and delete the generated oat files. 8463 */ 8464 @Override 8465 public void reconcileSecondaryDexFiles(String packageName) { 8466 mDexManager.reconcileSecondaryDexFiles(packageName); 8467 } 8468 8469 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8470 // a reference there. 8471 /*package*/ DexManager getDexManager() { 8472 return mDexManager; 8473 } 8474 8475 /** 8476 * Execute the background dexopt job immediately. 8477 */ 8478 @Override 8479 public boolean runBackgroundDexoptJob() { 8480 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8481 } 8482 8483 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8484 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8485 || p.usesStaticLibraries != null) { 8486 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8487 Set<String> collectedNames = new HashSet<>(); 8488 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8489 8490 retValue.remove(p); 8491 8492 return retValue; 8493 } else { 8494 return Collections.emptyList(); 8495 } 8496 } 8497 8498 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8499 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8500 if (!collectedNames.contains(p.packageName)) { 8501 collectedNames.add(p.packageName); 8502 collected.add(p); 8503 8504 if (p.usesLibraries != null) { 8505 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8506 null, collected, collectedNames); 8507 } 8508 if (p.usesOptionalLibraries != null) { 8509 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8510 null, collected, collectedNames); 8511 } 8512 if (p.usesStaticLibraries != null) { 8513 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8514 p.usesStaticLibrariesVersions, collected, collectedNames); 8515 } 8516 } 8517 } 8518 8519 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8520 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8521 final int libNameCount = libs.size(); 8522 for (int i = 0; i < libNameCount; i++) { 8523 String libName = libs.get(i); 8524 int version = (versions != null && versions.length == libNameCount) 8525 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8526 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8527 if (libPkg != null) { 8528 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8529 } 8530 } 8531 } 8532 8533 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8534 synchronized (mPackages) { 8535 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8536 if (libEntry != null) { 8537 return mPackages.get(libEntry.apk); 8538 } 8539 return null; 8540 } 8541 } 8542 8543 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8544 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8545 if (versionedLib == null) { 8546 return null; 8547 } 8548 return versionedLib.get(version); 8549 } 8550 8551 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8552 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8553 pkg.staticSharedLibName); 8554 if (versionedLib == null) { 8555 return null; 8556 } 8557 int previousLibVersion = -1; 8558 final int versionCount = versionedLib.size(); 8559 for (int i = 0; i < versionCount; i++) { 8560 final int libVersion = versionedLib.keyAt(i); 8561 if (libVersion < pkg.staticSharedLibVersion) { 8562 previousLibVersion = Math.max(previousLibVersion, libVersion); 8563 } 8564 } 8565 if (previousLibVersion >= 0) { 8566 return versionedLib.get(previousLibVersion); 8567 } 8568 return null; 8569 } 8570 8571 public void shutdown() { 8572 mPackageUsage.writeNow(mPackages); 8573 mCompilerStats.writeNow(); 8574 } 8575 8576 @Override 8577 public void dumpProfiles(String packageName) { 8578 PackageParser.Package pkg; 8579 synchronized (mPackages) { 8580 pkg = mPackages.get(packageName); 8581 if (pkg == null) { 8582 throw new IllegalArgumentException("Unknown package: " + packageName); 8583 } 8584 } 8585 /* Only the shell, root, or the app user should be able to dump profiles. */ 8586 int callingUid = Binder.getCallingUid(); 8587 if (callingUid != Process.SHELL_UID && 8588 callingUid != Process.ROOT_UID && 8589 callingUid != pkg.applicationInfo.uid) { 8590 throw new SecurityException("dumpProfiles"); 8591 } 8592 8593 synchronized (mInstallLock) { 8594 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8595 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8596 try { 8597 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8598 String codePaths = TextUtils.join(";", allCodePaths); 8599 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8600 } catch (InstallerException e) { 8601 Slog.w(TAG, "Failed to dump profiles", e); 8602 } 8603 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8604 } 8605 } 8606 8607 @Override 8608 public void forceDexOpt(String packageName) { 8609 enforceSystemOrRoot("forceDexOpt"); 8610 8611 PackageParser.Package pkg; 8612 synchronized (mPackages) { 8613 pkg = mPackages.get(packageName); 8614 if (pkg == null) { 8615 throw new IllegalArgumentException("Unknown package: " + packageName); 8616 } 8617 } 8618 8619 synchronized (mInstallLock) { 8620 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8621 8622 // Whoever is calling forceDexOpt wants a fully compiled package. 8623 // Don't use profiles since that may cause compilation to be skipped. 8624 final int res = performDexOptInternalWithDependenciesLI(pkg, 8625 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8626 true /* force */); 8627 8628 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8629 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8630 throw new IllegalStateException("Failed to dexopt: " + res); 8631 } 8632 } 8633 } 8634 8635 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8636 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8637 Slog.w(TAG, "Unable to update from " + oldPkg.name 8638 + " to " + newPkg.packageName 8639 + ": old package not in system partition"); 8640 return false; 8641 } else if (mPackages.get(oldPkg.name) != null) { 8642 Slog.w(TAG, "Unable to update from " + oldPkg.name 8643 + " to " + newPkg.packageName 8644 + ": old package still exists"); 8645 return false; 8646 } 8647 return true; 8648 } 8649 8650 void removeCodePathLI(File codePath) { 8651 if (codePath.isDirectory()) { 8652 try { 8653 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8654 } catch (InstallerException e) { 8655 Slog.w(TAG, "Failed to remove code path", e); 8656 } 8657 } else { 8658 codePath.delete(); 8659 } 8660 } 8661 8662 private int[] resolveUserIds(int userId) { 8663 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8664 } 8665 8666 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8667 if (pkg == null) { 8668 Slog.wtf(TAG, "Package was null!", new Throwable()); 8669 return; 8670 } 8671 clearAppDataLeafLIF(pkg, userId, flags); 8672 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8673 for (int i = 0; i < childCount; i++) { 8674 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8675 } 8676 } 8677 8678 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8679 final PackageSetting ps; 8680 synchronized (mPackages) { 8681 ps = mSettings.mPackages.get(pkg.packageName); 8682 } 8683 for (int realUserId : resolveUserIds(userId)) { 8684 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8685 try { 8686 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8687 ceDataInode); 8688 } catch (InstallerException e) { 8689 Slog.w(TAG, String.valueOf(e)); 8690 } 8691 } 8692 } 8693 8694 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8695 if (pkg == null) { 8696 Slog.wtf(TAG, "Package was null!", new Throwable()); 8697 return; 8698 } 8699 destroyAppDataLeafLIF(pkg, userId, flags); 8700 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8701 for (int i = 0; i < childCount; i++) { 8702 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8703 } 8704 } 8705 8706 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8707 final PackageSetting ps; 8708 synchronized (mPackages) { 8709 ps = mSettings.mPackages.get(pkg.packageName); 8710 } 8711 for (int realUserId : resolveUserIds(userId)) { 8712 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8713 try { 8714 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8715 ceDataInode); 8716 } catch (InstallerException e) { 8717 Slog.w(TAG, String.valueOf(e)); 8718 } 8719 } 8720 } 8721 8722 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8723 if (pkg == null) { 8724 Slog.wtf(TAG, "Package was null!", new Throwable()); 8725 return; 8726 } 8727 destroyAppProfilesLeafLIF(pkg); 8728 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8729 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8730 for (int i = 0; i < childCount; i++) { 8731 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8732 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8733 true /* removeBaseMarker */); 8734 } 8735 } 8736 8737 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8738 boolean removeBaseMarker) { 8739 if (pkg.isForwardLocked()) { 8740 return; 8741 } 8742 8743 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8744 try { 8745 path = PackageManagerServiceUtils.realpath(new File(path)); 8746 } catch (IOException e) { 8747 // TODO: Should we return early here ? 8748 Slog.w(TAG, "Failed to get canonical path", e); 8749 continue; 8750 } 8751 8752 final String useMarker = path.replace('/', '@'); 8753 for (int realUserId : resolveUserIds(userId)) { 8754 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8755 if (removeBaseMarker) { 8756 File foreignUseMark = new File(profileDir, useMarker); 8757 if (foreignUseMark.exists()) { 8758 if (!foreignUseMark.delete()) { 8759 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8760 + pkg.packageName); 8761 } 8762 } 8763 } 8764 8765 File[] markers = profileDir.listFiles(); 8766 if (markers != null) { 8767 final String searchString = "@" + pkg.packageName + "@"; 8768 // We also delete all markers that contain the package name we're 8769 // uninstalling. These are associated with secondary dex-files belonging 8770 // to the package. Reconstructing the path of these dex files is messy 8771 // in general. 8772 for (File marker : markers) { 8773 if (marker.getName().indexOf(searchString) > 0) { 8774 if (!marker.delete()) { 8775 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8776 + pkg.packageName); 8777 } 8778 } 8779 } 8780 } 8781 } 8782 } 8783 } 8784 8785 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8786 try { 8787 mInstaller.destroyAppProfiles(pkg.packageName); 8788 } catch (InstallerException e) { 8789 Slog.w(TAG, String.valueOf(e)); 8790 } 8791 } 8792 8793 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8794 if (pkg == null) { 8795 Slog.wtf(TAG, "Package was null!", new Throwable()); 8796 return; 8797 } 8798 clearAppProfilesLeafLIF(pkg); 8799 // We don't remove the base foreign use marker when clearing profiles because 8800 // we will rename it when the app is updated. Unlike the actual profile contents, 8801 // the foreign use marker is good across installs. 8802 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8803 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8804 for (int i = 0; i < childCount; i++) { 8805 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8806 } 8807 } 8808 8809 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8810 try { 8811 mInstaller.clearAppProfiles(pkg.packageName); 8812 } catch (InstallerException e) { 8813 Slog.w(TAG, String.valueOf(e)); 8814 } 8815 } 8816 8817 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8818 long lastUpdateTime) { 8819 // Set parent install/update time 8820 PackageSetting ps = (PackageSetting) pkg.mExtras; 8821 if (ps != null) { 8822 ps.firstInstallTime = firstInstallTime; 8823 ps.lastUpdateTime = lastUpdateTime; 8824 } 8825 // Set children install/update time 8826 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8827 for (int i = 0; i < childCount; i++) { 8828 PackageParser.Package childPkg = pkg.childPackages.get(i); 8829 ps = (PackageSetting) childPkg.mExtras; 8830 if (ps != null) { 8831 ps.firstInstallTime = firstInstallTime; 8832 ps.lastUpdateTime = lastUpdateTime; 8833 } 8834 } 8835 } 8836 8837 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8838 PackageParser.Package changingLib) { 8839 if (file.path != null) { 8840 usesLibraryFiles.add(file.path); 8841 return; 8842 } 8843 PackageParser.Package p = mPackages.get(file.apk); 8844 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8845 // If we are doing this while in the middle of updating a library apk, 8846 // then we need to make sure to use that new apk for determining the 8847 // dependencies here. (We haven't yet finished committing the new apk 8848 // to the package manager state.) 8849 if (p == null || p.packageName.equals(changingLib.packageName)) { 8850 p = changingLib; 8851 } 8852 } 8853 if (p != null) { 8854 usesLibraryFiles.addAll(p.getAllCodePaths()); 8855 } 8856 } 8857 8858 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8859 PackageParser.Package changingLib) throws PackageManagerException { 8860 if (pkg == null) { 8861 return; 8862 } 8863 ArraySet<String> usesLibraryFiles = null; 8864 if (pkg.usesLibraries != null) { 8865 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8866 null, null, pkg.packageName, changingLib, true, null); 8867 } 8868 if (pkg.usesStaticLibraries != null) { 8869 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8870 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8871 pkg.packageName, changingLib, true, usesLibraryFiles); 8872 } 8873 if (pkg.usesOptionalLibraries != null) { 8874 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8875 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8876 } 8877 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8878 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8879 } else { 8880 pkg.usesLibraryFiles = null; 8881 } 8882 } 8883 8884 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8885 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8886 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8887 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8888 throws PackageManagerException { 8889 final int libCount = requestedLibraries.size(); 8890 for (int i = 0; i < libCount; i++) { 8891 final String libName = requestedLibraries.get(i); 8892 final int libVersion = requiredVersions != null ? requiredVersions[i] 8893 : SharedLibraryInfo.VERSION_UNDEFINED; 8894 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8895 if (libEntry == null) { 8896 if (required) { 8897 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8898 "Package " + packageName + " requires unavailable shared library " 8899 + libName + "; failing!"); 8900 } else { 8901 Slog.w(TAG, "Package " + packageName 8902 + " desires unavailable shared library " 8903 + libName + "; ignoring!"); 8904 } 8905 } else { 8906 if (requiredVersions != null && requiredCertDigests != null) { 8907 if (libEntry.info.getVersion() != requiredVersions[i]) { 8908 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8909 "Package " + packageName + " requires unavailable static shared" 8910 + " library " + libName + " version " 8911 + libEntry.info.getVersion() + "; failing!"); 8912 } 8913 8914 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8915 if (libPkg == null) { 8916 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8917 "Package " + packageName + " requires unavailable static shared" 8918 + " library; failing!"); 8919 } 8920 8921 String expectedCertDigest = requiredCertDigests[i]; 8922 String libCertDigest = PackageUtils.computeCertSha256Digest( 8923 libPkg.mSignatures[0]); 8924 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8925 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8926 "Package " + packageName + " requires differently signed" + 8927 " static shared library; failing!"); 8928 } 8929 } 8930 8931 if (outUsedLibraries == null) { 8932 outUsedLibraries = new ArraySet<>(); 8933 } 8934 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8935 } 8936 } 8937 return outUsedLibraries; 8938 } 8939 8940 private static boolean hasString(List<String> list, List<String> which) { 8941 if (list == null) { 8942 return false; 8943 } 8944 for (int i=list.size()-1; i>=0; i--) { 8945 for (int j=which.size()-1; j>=0; j--) { 8946 if (which.get(j).equals(list.get(i))) { 8947 return true; 8948 } 8949 } 8950 } 8951 return false; 8952 } 8953 8954 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8955 PackageParser.Package changingPkg) { 8956 ArrayList<PackageParser.Package> res = null; 8957 for (PackageParser.Package pkg : mPackages.values()) { 8958 if (changingPkg != null 8959 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8960 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8961 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8962 changingPkg.staticSharedLibName)) { 8963 return null; 8964 } 8965 if (res == null) { 8966 res = new ArrayList<>(); 8967 } 8968 res.add(pkg); 8969 try { 8970 updateSharedLibrariesLPr(pkg, changingPkg); 8971 } catch (PackageManagerException e) { 8972 // If a system app update or an app and a required lib missing we 8973 // delete the package and for updated system apps keep the data as 8974 // it is better for the user to reinstall than to be in an limbo 8975 // state. Also libs disappearing under an app should never happen 8976 // - just in case. 8977 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8978 final int flags = pkg.isUpdatedSystemApp() 8979 ? PackageManager.DELETE_KEEP_DATA : 0; 8980 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8981 flags , null, true, null); 8982 } 8983 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8984 } 8985 } 8986 return res; 8987 } 8988 8989 /** 8990 * Derive the value of the {@code cpuAbiOverride} based on the provided 8991 * value and an optional stored value from the package settings. 8992 */ 8993 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8994 String cpuAbiOverride = null; 8995 8996 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8997 cpuAbiOverride = null; 8998 } else if (abiOverride != null) { 8999 cpuAbiOverride = abiOverride; 9000 } else if (settings != null) { 9001 cpuAbiOverride = settings.cpuAbiOverrideString; 9002 } 9003 9004 return cpuAbiOverride; 9005 } 9006 9007 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9008 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9009 throws PackageManagerException { 9010 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9011 // If the package has children and this is the first dive in the function 9012 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9013 // whether all packages (parent and children) would be successfully scanned 9014 // before the actual scan since scanning mutates internal state and we want 9015 // to atomically install the package and its children. 9016 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9017 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9018 scanFlags |= SCAN_CHECK_ONLY; 9019 } 9020 } else { 9021 scanFlags &= ~SCAN_CHECK_ONLY; 9022 } 9023 9024 final PackageParser.Package scannedPkg; 9025 try { 9026 // Scan the parent 9027 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9028 // Scan the children 9029 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9030 for (int i = 0; i < childCount; i++) { 9031 PackageParser.Package childPkg = pkg.childPackages.get(i); 9032 scanPackageLI(childPkg, policyFlags, 9033 scanFlags, currentTime, user); 9034 } 9035 } finally { 9036 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9037 } 9038 9039 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9040 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9041 } 9042 9043 return scannedPkg; 9044 } 9045 9046 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9047 int scanFlags, long currentTime, @Nullable UserHandle user) 9048 throws PackageManagerException { 9049 boolean success = false; 9050 try { 9051 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9052 currentTime, user); 9053 success = true; 9054 return res; 9055 } finally { 9056 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9057 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9058 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9059 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9060 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9061 } 9062 } 9063 } 9064 9065 /** 9066 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9067 */ 9068 private static boolean apkHasCode(String fileName) { 9069 StrictJarFile jarFile = null; 9070 try { 9071 jarFile = new StrictJarFile(fileName, 9072 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9073 return jarFile.findEntry("classes.dex") != null; 9074 } catch (IOException ignore) { 9075 } finally { 9076 try { 9077 if (jarFile != null) { 9078 jarFile.close(); 9079 } 9080 } catch (IOException ignore) {} 9081 } 9082 return false; 9083 } 9084 9085 /** 9086 * Enforces code policy for the package. This ensures that if an APK has 9087 * declared hasCode="true" in its manifest that the APK actually contains 9088 * code. 9089 * 9090 * @throws PackageManagerException If bytecode could not be found when it should exist 9091 */ 9092 private static void assertCodePolicy(PackageParser.Package pkg) 9093 throws PackageManagerException { 9094 final boolean shouldHaveCode = 9095 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9096 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9097 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9098 "Package " + pkg.baseCodePath + " code is missing"); 9099 } 9100 9101 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9102 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9103 final boolean splitShouldHaveCode = 9104 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9105 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9106 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9107 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9108 } 9109 } 9110 } 9111 } 9112 9113 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9114 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9115 throws PackageManagerException { 9116 if (DEBUG_PACKAGE_SCANNING) { 9117 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9118 Log.d(TAG, "Scanning package " + pkg.packageName); 9119 } 9120 9121 applyPolicy(pkg, policyFlags); 9122 9123 assertPackageIsValid(pkg, policyFlags, scanFlags); 9124 9125 // Initialize package source and resource directories 9126 final File scanFile = new File(pkg.codePath); 9127 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9128 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9129 9130 SharedUserSetting suid = null; 9131 PackageSetting pkgSetting = null; 9132 9133 // Getting the package setting may have a side-effect, so if we 9134 // are only checking if scan would succeed, stash a copy of the 9135 // old setting to restore at the end. 9136 PackageSetting nonMutatedPs = null; 9137 9138 // We keep references to the derived CPU Abis from settings in oder to reuse 9139 // them in the case where we're not upgrading or booting for the first time. 9140 String primaryCpuAbiFromSettings = null; 9141 String secondaryCpuAbiFromSettings = null; 9142 9143 // writer 9144 synchronized (mPackages) { 9145 if (pkg.mSharedUserId != null) { 9146 // SIDE EFFECTS; may potentially allocate a new shared user 9147 suid = mSettings.getSharedUserLPw( 9148 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9149 if (DEBUG_PACKAGE_SCANNING) { 9150 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9151 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9152 + "): packages=" + suid.packages); 9153 } 9154 } 9155 9156 // Check if we are renaming from an original package name. 9157 PackageSetting origPackage = null; 9158 String realName = null; 9159 if (pkg.mOriginalPackages != null) { 9160 // This package may need to be renamed to a previously 9161 // installed name. Let's check on that... 9162 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9163 if (pkg.mOriginalPackages.contains(renamed)) { 9164 // This package had originally been installed as the 9165 // original name, and we have already taken care of 9166 // transitioning to the new one. Just update the new 9167 // one to continue using the old name. 9168 realName = pkg.mRealPackage; 9169 if (!pkg.packageName.equals(renamed)) { 9170 // Callers into this function may have already taken 9171 // care of renaming the package; only do it here if 9172 // it is not already done. 9173 pkg.setPackageName(renamed); 9174 } 9175 } else { 9176 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9177 if ((origPackage = mSettings.getPackageLPr( 9178 pkg.mOriginalPackages.get(i))) != null) { 9179 // We do have the package already installed under its 9180 // original name... should we use it? 9181 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9182 // New package is not compatible with original. 9183 origPackage = null; 9184 continue; 9185 } else if (origPackage.sharedUser != null) { 9186 // Make sure uid is compatible between packages. 9187 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9188 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9189 + " to " + pkg.packageName + ": old uid " 9190 + origPackage.sharedUser.name 9191 + " differs from " + pkg.mSharedUserId); 9192 origPackage = null; 9193 continue; 9194 } 9195 // TODO: Add case when shared user id is added [b/28144775] 9196 } else { 9197 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9198 + pkg.packageName + " to old name " + origPackage.name); 9199 } 9200 break; 9201 } 9202 } 9203 } 9204 } 9205 9206 if (mTransferedPackages.contains(pkg.packageName)) { 9207 Slog.w(TAG, "Package " + pkg.packageName 9208 + " was transferred to another, but its .apk remains"); 9209 } 9210 9211 // See comments in nonMutatedPs declaration 9212 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9213 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9214 if (foundPs != null) { 9215 nonMutatedPs = new PackageSetting(foundPs); 9216 } 9217 } 9218 9219 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9220 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9221 if (foundPs != null) { 9222 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9223 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9224 } 9225 } 9226 9227 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9228 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9229 PackageManagerService.reportSettingsProblem(Log.WARN, 9230 "Package " + pkg.packageName + " shared user changed from " 9231 + (pkgSetting.sharedUser != null 9232 ? pkgSetting.sharedUser.name : "<nothing>") 9233 + " to " 9234 + (suid != null ? suid.name : "<nothing>") 9235 + "; replacing with new"); 9236 pkgSetting = null; 9237 } 9238 final PackageSetting oldPkgSetting = 9239 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9240 final PackageSetting disabledPkgSetting = 9241 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9242 9243 String[] usesStaticLibraries = null; 9244 if (pkg.usesStaticLibraries != null) { 9245 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9246 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9247 } 9248 9249 if (pkgSetting == null) { 9250 final String parentPackageName = (pkg.parentPackage != null) 9251 ? pkg.parentPackage.packageName : null; 9252 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9253 // REMOVE SharedUserSetting from method; update in a separate call 9254 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9255 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9256 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9257 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9258 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9259 true /*allowInstall*/, instantApp, parentPackageName, 9260 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9261 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9262 // SIDE EFFECTS; updates system state; move elsewhere 9263 if (origPackage != null) { 9264 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9265 } 9266 mSettings.addUserToSettingLPw(pkgSetting); 9267 } else { 9268 // REMOVE SharedUserSetting from method; update in a separate call. 9269 // 9270 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9271 // secondaryCpuAbi are not known at this point so we always update them 9272 // to null here, only to reset them at a later point. 9273 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9274 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9275 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9276 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9277 UserManagerService.getInstance(), usesStaticLibraries, 9278 pkg.usesStaticLibrariesVersions); 9279 } 9280 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9281 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9282 9283 // SIDE EFFECTS; modifies system state; move elsewhere 9284 if (pkgSetting.origPackage != null) { 9285 // If we are first transitioning from an original package, 9286 // fix up the new package's name now. We need to do this after 9287 // looking up the package under its new name, so getPackageLP 9288 // can take care of fiddling things correctly. 9289 pkg.setPackageName(origPackage.name); 9290 9291 // File a report about this. 9292 String msg = "New package " + pkgSetting.realName 9293 + " renamed to replace old package " + pkgSetting.name; 9294 reportSettingsProblem(Log.WARN, msg); 9295 9296 // Make a note of it. 9297 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9298 mTransferedPackages.add(origPackage.name); 9299 } 9300 9301 // No longer need to retain this. 9302 pkgSetting.origPackage = null; 9303 } 9304 9305 // SIDE EFFECTS; modifies system state; move elsewhere 9306 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9307 // Make a note of it. 9308 mTransferedPackages.add(pkg.packageName); 9309 } 9310 9311 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9312 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9313 } 9314 9315 if ((scanFlags & SCAN_BOOTING) == 0 9316 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9317 // Check all shared libraries and map to their actual file path. 9318 // We only do this here for apps not on a system dir, because those 9319 // are the only ones that can fail an install due to this. We 9320 // will take care of the system apps by updating all of their 9321 // library paths after the scan is done. Also during the initial 9322 // scan don't update any libs as we do this wholesale after all 9323 // apps are scanned to avoid dependency based scanning. 9324 updateSharedLibrariesLPr(pkg, null); 9325 } 9326 9327 if (mFoundPolicyFile) { 9328 SELinuxMMAC.assignSeInfoValue(pkg); 9329 } 9330 pkg.applicationInfo.uid = pkgSetting.appId; 9331 pkg.mExtras = pkgSetting; 9332 9333 9334 // Static shared libs have same package with different versions where 9335 // we internally use a synthetic package name to allow multiple versions 9336 // of the same package, therefore we need to compare signatures against 9337 // the package setting for the latest library version. 9338 PackageSetting signatureCheckPs = pkgSetting; 9339 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9340 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9341 if (libraryEntry != null) { 9342 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9343 } 9344 } 9345 9346 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9347 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9348 // We just determined the app is signed correctly, so bring 9349 // over the latest parsed certs. 9350 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9351 } else { 9352 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9353 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9354 "Package " + pkg.packageName + " upgrade keys do not match the " 9355 + "previously installed version"); 9356 } else { 9357 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9358 String msg = "System package " + pkg.packageName 9359 + " signature changed; retaining data."; 9360 reportSettingsProblem(Log.WARN, msg); 9361 } 9362 } 9363 } else { 9364 try { 9365 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9366 verifySignaturesLP(signatureCheckPs, pkg); 9367 // We just determined the app is signed correctly, so bring 9368 // over the latest parsed certs. 9369 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9370 } catch (PackageManagerException e) { 9371 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9372 throw e; 9373 } 9374 // The signature has changed, but this package is in the system 9375 // image... let's recover! 9376 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9377 // However... if this package is part of a shared user, but it 9378 // doesn't match the signature of the shared user, let's fail. 9379 // What this means is that you can't change the signatures 9380 // associated with an overall shared user, which doesn't seem all 9381 // that unreasonable. 9382 if (signatureCheckPs.sharedUser != null) { 9383 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9384 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9385 throw new PackageManagerException( 9386 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9387 "Signature mismatch for shared user: " 9388 + pkgSetting.sharedUser); 9389 } 9390 } 9391 // File a report about this. 9392 String msg = "System package " + pkg.packageName 9393 + " signature changed; retaining data."; 9394 reportSettingsProblem(Log.WARN, msg); 9395 } 9396 } 9397 9398 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9399 // This package wants to adopt ownership of permissions from 9400 // another package. 9401 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9402 final String origName = pkg.mAdoptPermissions.get(i); 9403 final PackageSetting orig = mSettings.getPackageLPr(origName); 9404 if (orig != null) { 9405 if (verifyPackageUpdateLPr(orig, pkg)) { 9406 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9407 + pkg.packageName); 9408 // SIDE EFFECTS; updates permissions system state; move elsewhere 9409 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9410 } 9411 } 9412 } 9413 } 9414 } 9415 9416 pkg.applicationInfo.processName = fixProcessName( 9417 pkg.applicationInfo.packageName, 9418 pkg.applicationInfo.processName); 9419 9420 if (pkg != mPlatformPackage) { 9421 // Get all of our default paths setup 9422 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9423 } 9424 9425 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9426 9427 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9428 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9429 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9430 derivePackageAbi( 9431 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9433 9434 // Some system apps still use directory structure for native libraries 9435 // in which case we might end up not detecting abi solely based on apk 9436 // structure. Try to detect abi based on directory structure. 9437 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9438 pkg.applicationInfo.primaryCpuAbi == null) { 9439 setBundledAppAbisAndRoots(pkg, pkgSetting); 9440 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9441 } 9442 } else { 9443 // This is not a first boot or an upgrade, don't bother deriving the 9444 // ABI during the scan. Instead, trust the value that was stored in the 9445 // package setting. 9446 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9447 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9448 9449 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9450 9451 if (DEBUG_ABI_SELECTION) { 9452 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9453 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9454 pkg.applicationInfo.secondaryCpuAbi); 9455 } 9456 } 9457 } else { 9458 if ((scanFlags & SCAN_MOVE) != 0) { 9459 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9460 // but we already have this packages package info in the PackageSetting. We just 9461 // use that and derive the native library path based on the new codepath. 9462 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9463 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9464 } 9465 9466 // Set native library paths again. For moves, the path will be updated based on the 9467 // ABIs we've determined above. For non-moves, the path will be updated based on the 9468 // ABIs we determined during compilation, but the path will depend on the final 9469 // package path (after the rename away from the stage path). 9470 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9471 } 9472 9473 // This is a special case for the "system" package, where the ABI is 9474 // dictated by the zygote configuration (and init.rc). We should keep track 9475 // of this ABI so that we can deal with "normal" applications that run under 9476 // the same UID correctly. 9477 if (mPlatformPackage == pkg) { 9478 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9479 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9480 } 9481 9482 // If there's a mismatch between the abi-override in the package setting 9483 // and the abiOverride specified for the install. Warn about this because we 9484 // would've already compiled the app without taking the package setting into 9485 // account. 9486 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9487 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9488 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9489 " for package " + pkg.packageName); 9490 } 9491 } 9492 9493 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9494 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9495 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9496 9497 // Copy the derived override back to the parsed package, so that we can 9498 // update the package settings accordingly. 9499 pkg.cpuAbiOverride = cpuAbiOverride; 9500 9501 if (DEBUG_ABI_SELECTION) { 9502 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9503 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9504 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9505 } 9506 9507 // Push the derived path down into PackageSettings so we know what to 9508 // clean up at uninstall time. 9509 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9510 9511 if (DEBUG_ABI_SELECTION) { 9512 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9513 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9514 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9515 } 9516 9517 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9518 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9519 // We don't do this here during boot because we can do it all 9520 // at once after scanning all existing packages. 9521 // 9522 // We also do this *before* we perform dexopt on this package, so that 9523 // we can avoid redundant dexopts, and also to make sure we've got the 9524 // code and package path correct. 9525 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9526 } 9527 9528 if (mFactoryTest && pkg.requestedPermissions.contains( 9529 android.Manifest.permission.FACTORY_TEST)) { 9530 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9531 } 9532 9533 if (isSystemApp(pkg)) { 9534 pkgSetting.isOrphaned = true; 9535 } 9536 9537 // Take care of first install / last update times. 9538 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9539 if (currentTime != 0) { 9540 if (pkgSetting.firstInstallTime == 0) { 9541 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9542 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9543 pkgSetting.lastUpdateTime = currentTime; 9544 } 9545 } else if (pkgSetting.firstInstallTime == 0) { 9546 // We need *something*. Take time time stamp of the file. 9547 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9548 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9549 if (scanFileTime != pkgSetting.timeStamp) { 9550 // A package on the system image has changed; consider this 9551 // to be an update. 9552 pkgSetting.lastUpdateTime = scanFileTime; 9553 } 9554 } 9555 pkgSetting.setTimeStamp(scanFileTime); 9556 9557 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9558 if (nonMutatedPs != null) { 9559 synchronized (mPackages) { 9560 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9561 } 9562 } 9563 } else { 9564 final int userId = user == null ? 0 : user.getIdentifier(); 9565 // Modify state for the given package setting 9566 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9567 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9568 if (pkgSetting.getInstantApp(userId)) { 9569 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9570 } 9571 } 9572 return pkg; 9573 } 9574 9575 /** 9576 * Applies policy to the parsed package based upon the given policy flags. 9577 * Ensures the package is in a good state. 9578 * <p> 9579 * Implementation detail: This method must NOT have any side effect. It would 9580 * ideally be static, but, it requires locks to read system state. 9581 */ 9582 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9583 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9584 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9585 if (pkg.applicationInfo.isDirectBootAware()) { 9586 // we're direct boot aware; set for all components 9587 for (PackageParser.Service s : pkg.services) { 9588 s.info.encryptionAware = s.info.directBootAware = true; 9589 } 9590 for (PackageParser.Provider p : pkg.providers) { 9591 p.info.encryptionAware = p.info.directBootAware = true; 9592 } 9593 for (PackageParser.Activity a : pkg.activities) { 9594 a.info.encryptionAware = a.info.directBootAware = true; 9595 } 9596 for (PackageParser.Activity r : pkg.receivers) { 9597 r.info.encryptionAware = r.info.directBootAware = true; 9598 } 9599 } 9600 } else { 9601 // Only allow system apps to be flagged as core apps. 9602 pkg.coreApp = false; 9603 // clear flags not applicable to regular apps 9604 pkg.applicationInfo.privateFlags &= 9605 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9606 pkg.applicationInfo.privateFlags &= 9607 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9608 } 9609 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9610 9611 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9612 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9613 } 9614 9615 if (!isSystemApp(pkg)) { 9616 // Only system apps can use these features. 9617 pkg.mOriginalPackages = null; 9618 pkg.mRealPackage = null; 9619 pkg.mAdoptPermissions = null; 9620 } 9621 } 9622 9623 /** 9624 * Asserts the parsed package is valid according to the given policy. If the 9625 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9626 * <p> 9627 * Implementation detail: This method must NOT have any side effects. It would 9628 * ideally be static, but, it requires locks to read system state. 9629 * 9630 * @throws PackageManagerException If the package fails any of the validation checks 9631 */ 9632 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9633 throws PackageManagerException { 9634 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9635 assertCodePolicy(pkg); 9636 } 9637 9638 if (pkg.applicationInfo.getCodePath() == null || 9639 pkg.applicationInfo.getResourcePath() == null) { 9640 // Bail out. The resource and code paths haven't been set. 9641 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9642 "Code and resource paths haven't been set correctly"); 9643 } 9644 9645 // Make sure we're not adding any bogus keyset info 9646 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9647 ksms.assertScannedPackageValid(pkg); 9648 9649 synchronized (mPackages) { 9650 // The special "android" package can only be defined once 9651 if (pkg.packageName.equals("android")) { 9652 if (mAndroidApplication != null) { 9653 Slog.w(TAG, "*************************************************"); 9654 Slog.w(TAG, "Core android package being redefined. Skipping."); 9655 Slog.w(TAG, " codePath=" + pkg.codePath); 9656 Slog.w(TAG, "*************************************************"); 9657 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9658 "Core android package being redefined. Skipping."); 9659 } 9660 } 9661 9662 // A package name must be unique; don't allow duplicates 9663 if (mPackages.containsKey(pkg.packageName)) { 9664 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9665 "Application package " + pkg.packageName 9666 + " already installed. Skipping duplicate."); 9667 } 9668 9669 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9670 // Static libs have a synthetic package name containing the version 9671 // but we still want the base name to be unique. 9672 if (mPackages.containsKey(pkg.manifestPackageName)) { 9673 throw new PackageManagerException( 9674 "Duplicate static shared lib provider package"); 9675 } 9676 9677 // Static shared libraries should have at least O target SDK 9678 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9679 throw new PackageManagerException( 9680 "Packages declaring static-shared libs must target O SDK or higher"); 9681 } 9682 9683 // Package declaring static a shared lib cannot be instant apps 9684 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9685 throw new PackageManagerException( 9686 "Packages declaring static-shared libs cannot be instant apps"); 9687 } 9688 9689 // Package declaring static a shared lib cannot be renamed since the package 9690 // name is synthetic and apps can't code around package manager internals. 9691 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9692 throw new PackageManagerException( 9693 "Packages declaring static-shared libs cannot be renamed"); 9694 } 9695 9696 // Package declaring static a shared lib cannot declare child packages 9697 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9698 throw new PackageManagerException( 9699 "Packages declaring static-shared libs cannot have child packages"); 9700 } 9701 9702 // Package declaring static a shared lib cannot declare dynamic libs 9703 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9704 throw new PackageManagerException( 9705 "Packages declaring static-shared libs cannot declare dynamic libs"); 9706 } 9707 9708 // Package declaring static a shared lib cannot declare shared users 9709 if (pkg.mSharedUserId != null) { 9710 throw new PackageManagerException( 9711 "Packages declaring static-shared libs cannot declare shared users"); 9712 } 9713 9714 // Static shared libs cannot declare activities 9715 if (!pkg.activities.isEmpty()) { 9716 throw new PackageManagerException( 9717 "Static shared libs cannot declare activities"); 9718 } 9719 9720 // Static shared libs cannot declare services 9721 if (!pkg.services.isEmpty()) { 9722 throw new PackageManagerException( 9723 "Static shared libs cannot declare services"); 9724 } 9725 9726 // Static shared libs cannot declare providers 9727 if (!pkg.providers.isEmpty()) { 9728 throw new PackageManagerException( 9729 "Static shared libs cannot declare content providers"); 9730 } 9731 9732 // Static shared libs cannot declare receivers 9733 if (!pkg.receivers.isEmpty()) { 9734 throw new PackageManagerException( 9735 "Static shared libs cannot declare broadcast receivers"); 9736 } 9737 9738 // Static shared libs cannot declare permission groups 9739 if (!pkg.permissionGroups.isEmpty()) { 9740 throw new PackageManagerException( 9741 "Static shared libs cannot declare permission groups"); 9742 } 9743 9744 // Static shared libs cannot declare permissions 9745 if (!pkg.permissions.isEmpty()) { 9746 throw new PackageManagerException( 9747 "Static shared libs cannot declare permissions"); 9748 } 9749 9750 // Static shared libs cannot declare protected broadcasts 9751 if (pkg.protectedBroadcasts != null) { 9752 throw new PackageManagerException( 9753 "Static shared libs cannot declare protected broadcasts"); 9754 } 9755 9756 // Static shared libs cannot be overlay targets 9757 if (pkg.mOverlayTarget != null) { 9758 throw new PackageManagerException( 9759 "Static shared libs cannot be overlay targets"); 9760 } 9761 9762 // The version codes must be ordered as lib versions 9763 int minVersionCode = Integer.MIN_VALUE; 9764 int maxVersionCode = Integer.MAX_VALUE; 9765 9766 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9767 pkg.staticSharedLibName); 9768 if (versionedLib != null) { 9769 final int versionCount = versionedLib.size(); 9770 for (int i = 0; i < versionCount; i++) { 9771 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9772 // TODO: We will change version code to long, so in the new API it is long 9773 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9774 .getVersionCode(); 9775 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9776 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9777 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9778 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9779 } else { 9780 minVersionCode = maxVersionCode = libVersionCode; 9781 break; 9782 } 9783 } 9784 } 9785 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9786 throw new PackageManagerException("Static shared" 9787 + " lib version codes must be ordered as lib versions"); 9788 } 9789 } 9790 9791 // Only privileged apps and updated privileged apps can add child packages. 9792 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9793 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9794 throw new PackageManagerException("Only privileged apps can add child " 9795 + "packages. Ignoring package " + pkg.packageName); 9796 } 9797 final int childCount = pkg.childPackages.size(); 9798 for (int i = 0; i < childCount; i++) { 9799 PackageParser.Package childPkg = pkg.childPackages.get(i); 9800 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9801 childPkg.packageName)) { 9802 throw new PackageManagerException("Can't override child of " 9803 + "another disabled app. Ignoring package " + pkg.packageName); 9804 } 9805 } 9806 } 9807 9808 // If we're only installing presumed-existing packages, require that the 9809 // scanned APK is both already known and at the path previously established 9810 // for it. Previously unknown packages we pick up normally, but if we have an 9811 // a priori expectation about this package's install presence, enforce it. 9812 // With a singular exception for new system packages. When an OTA contains 9813 // a new system package, we allow the codepath to change from a system location 9814 // to the user-installed location. If we don't allow this change, any newer, 9815 // user-installed version of the application will be ignored. 9816 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9817 if (mExpectingBetter.containsKey(pkg.packageName)) { 9818 logCriticalInfo(Log.WARN, 9819 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9820 } else { 9821 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9822 if (known != null) { 9823 if (DEBUG_PACKAGE_SCANNING) { 9824 Log.d(TAG, "Examining " + pkg.codePath 9825 + " and requiring known paths " + known.codePathString 9826 + " & " + known.resourcePathString); 9827 } 9828 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9829 || !pkg.applicationInfo.getResourcePath().equals( 9830 known.resourcePathString)) { 9831 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9832 "Application package " + pkg.packageName 9833 + " found at " + pkg.applicationInfo.getCodePath() 9834 + " but expected at " + known.codePathString 9835 + "; ignoring."); 9836 } 9837 } 9838 } 9839 } 9840 9841 // Verify that this new package doesn't have any content providers 9842 // that conflict with existing packages. Only do this if the 9843 // package isn't already installed, since we don't want to break 9844 // things that are installed. 9845 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9846 final int N = pkg.providers.size(); 9847 int i; 9848 for (i=0; i<N; i++) { 9849 PackageParser.Provider p = pkg.providers.get(i); 9850 if (p.info.authority != null) { 9851 String names[] = p.info.authority.split(";"); 9852 for (int j = 0; j < names.length; j++) { 9853 if (mProvidersByAuthority.containsKey(names[j])) { 9854 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9855 final String otherPackageName = 9856 ((other != null && other.getComponentName() != null) ? 9857 other.getComponentName().getPackageName() : "?"); 9858 throw new PackageManagerException( 9859 INSTALL_FAILED_CONFLICTING_PROVIDER, 9860 "Can't install because provider name " + names[j] 9861 + " (in package " + pkg.applicationInfo.packageName 9862 + ") is already used by " + otherPackageName); 9863 } 9864 } 9865 } 9866 } 9867 } 9868 } 9869 } 9870 9871 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9872 int type, String declaringPackageName, int declaringVersionCode) { 9873 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9874 if (versionedLib == null) { 9875 versionedLib = new SparseArray<>(); 9876 mSharedLibraries.put(name, versionedLib); 9877 if (type == SharedLibraryInfo.TYPE_STATIC) { 9878 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9879 } 9880 } else if (versionedLib.indexOfKey(version) >= 0) { 9881 return false; 9882 } 9883 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9884 version, type, declaringPackageName, declaringVersionCode); 9885 versionedLib.put(version, libEntry); 9886 return true; 9887 } 9888 9889 private boolean removeSharedLibraryLPw(String name, int version) { 9890 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9891 if (versionedLib == null) { 9892 return false; 9893 } 9894 final int libIdx = versionedLib.indexOfKey(version); 9895 if (libIdx < 0) { 9896 return false; 9897 } 9898 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9899 versionedLib.remove(version); 9900 if (versionedLib.size() <= 0) { 9901 mSharedLibraries.remove(name); 9902 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9903 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9904 .getPackageName()); 9905 } 9906 } 9907 return true; 9908 } 9909 9910 /** 9911 * Adds a scanned package to the system. When this method is finished, the package will 9912 * be available for query, resolution, etc... 9913 */ 9914 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9915 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9916 final String pkgName = pkg.packageName; 9917 if (mCustomResolverComponentName != null && 9918 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9919 setUpCustomResolverActivity(pkg); 9920 } 9921 9922 if (pkg.packageName.equals("android")) { 9923 synchronized (mPackages) { 9924 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9925 // Set up information for our fall-back user intent resolution activity. 9926 mPlatformPackage = pkg; 9927 pkg.mVersionCode = mSdkVersion; 9928 mAndroidApplication = pkg.applicationInfo; 9929 if (!mResolverReplaced) { 9930 mResolveActivity.applicationInfo = mAndroidApplication; 9931 mResolveActivity.name = ResolverActivity.class.getName(); 9932 mResolveActivity.packageName = mAndroidApplication.packageName; 9933 mResolveActivity.processName = "system:ui"; 9934 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9935 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9936 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9937 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9938 mResolveActivity.exported = true; 9939 mResolveActivity.enabled = true; 9940 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9941 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9942 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9943 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9944 | ActivityInfo.CONFIG_ORIENTATION 9945 | ActivityInfo.CONFIG_KEYBOARD 9946 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9947 mResolveInfo.activityInfo = mResolveActivity; 9948 mResolveInfo.priority = 0; 9949 mResolveInfo.preferredOrder = 0; 9950 mResolveInfo.match = 0; 9951 mResolveComponentName = new ComponentName( 9952 mAndroidApplication.packageName, mResolveActivity.name); 9953 } 9954 } 9955 } 9956 } 9957 9958 ArrayList<PackageParser.Package> clientLibPkgs = null; 9959 // writer 9960 synchronized (mPackages) { 9961 boolean hasStaticSharedLibs = false; 9962 9963 // Any app can add new static shared libraries 9964 if (pkg.staticSharedLibName != null) { 9965 // Static shared libs don't allow renaming as they have synthetic package 9966 // names to allow install of multiple versions, so use name from manifest. 9967 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9968 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9969 pkg.manifestPackageName, pkg.mVersionCode)) { 9970 hasStaticSharedLibs = true; 9971 } else { 9972 Slog.w(TAG, "Package " + pkg.packageName + " library " 9973 + pkg.staticSharedLibName + " already exists; skipping"); 9974 } 9975 // Static shared libs cannot be updated once installed since they 9976 // use synthetic package name which includes the version code, so 9977 // not need to update other packages's shared lib dependencies. 9978 } 9979 9980 if (!hasStaticSharedLibs 9981 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9982 // Only system apps can add new dynamic shared libraries. 9983 if (pkg.libraryNames != null) { 9984 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9985 String name = pkg.libraryNames.get(i); 9986 boolean allowed = false; 9987 if (pkg.isUpdatedSystemApp()) { 9988 // New library entries can only be added through the 9989 // system image. This is important to get rid of a lot 9990 // of nasty edge cases: for example if we allowed a non- 9991 // system update of the app to add a library, then uninstalling 9992 // the update would make the library go away, and assumptions 9993 // we made such as through app install filtering would now 9994 // have allowed apps on the device which aren't compatible 9995 // with it. Better to just have the restriction here, be 9996 // conservative, and create many fewer cases that can negatively 9997 // impact the user experience. 9998 final PackageSetting sysPs = mSettings 9999 .getDisabledSystemPkgLPr(pkg.packageName); 10000 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10001 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10002 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10003 allowed = true; 10004 break; 10005 } 10006 } 10007 } 10008 } else { 10009 allowed = true; 10010 } 10011 if (allowed) { 10012 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10013 SharedLibraryInfo.VERSION_UNDEFINED, 10014 SharedLibraryInfo.TYPE_DYNAMIC, 10015 pkg.packageName, pkg.mVersionCode)) { 10016 Slog.w(TAG, "Package " + pkg.packageName + " library " 10017 + name + " already exists; skipping"); 10018 } 10019 } else { 10020 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10021 + name + " that is not declared on system image; skipping"); 10022 } 10023 } 10024 10025 if ((scanFlags & SCAN_BOOTING) == 0) { 10026 // If we are not booting, we need to update any applications 10027 // that are clients of our shared library. If we are booting, 10028 // this will all be done once the scan is complete. 10029 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10030 } 10031 } 10032 } 10033 } 10034 10035 if ((scanFlags & SCAN_BOOTING) != 0) { 10036 // No apps can run during boot scan, so they don't need to be frozen 10037 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10038 // Caller asked to not kill app, so it's probably not frozen 10039 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10040 // Caller asked us to ignore frozen check for some reason; they 10041 // probably didn't know the package name 10042 } else { 10043 // We're doing major surgery on this package, so it better be frozen 10044 // right now to keep it from launching 10045 checkPackageFrozen(pkgName); 10046 } 10047 10048 // Also need to kill any apps that are dependent on the library. 10049 if (clientLibPkgs != null) { 10050 for (int i=0; i<clientLibPkgs.size(); i++) { 10051 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10052 killApplication(clientPkg.applicationInfo.packageName, 10053 clientPkg.applicationInfo.uid, "update lib"); 10054 } 10055 } 10056 10057 // writer 10058 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10059 10060 boolean createIdmapFailed = false; 10061 synchronized (mPackages) { 10062 // We don't expect installation to fail beyond this point 10063 10064 if (pkgSetting.pkg != null) { 10065 // Note that |user| might be null during the initial boot scan. If a codePath 10066 // for an app has changed during a boot scan, it's due to an app update that's 10067 // part of the system partition and marker changes must be applied to all users. 10068 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 10069 final int[] userIds = resolveUserIds(userId); 10070 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 10071 } 10072 10073 // Add the new setting to mSettings 10074 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10075 // Add the new setting to mPackages 10076 mPackages.put(pkg.applicationInfo.packageName, pkg); 10077 // Make sure we don't accidentally delete its data. 10078 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10079 while (iter.hasNext()) { 10080 PackageCleanItem item = iter.next(); 10081 if (pkgName.equals(item.packageName)) { 10082 iter.remove(); 10083 } 10084 } 10085 10086 // Add the package's KeySets to the global KeySetManagerService 10087 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10088 ksms.addScannedPackageLPw(pkg); 10089 10090 int N = pkg.providers.size(); 10091 StringBuilder r = null; 10092 int i; 10093 for (i=0; i<N; i++) { 10094 PackageParser.Provider p = pkg.providers.get(i); 10095 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10096 p.info.processName); 10097 mProviders.addProvider(p); 10098 p.syncable = p.info.isSyncable; 10099 if (p.info.authority != null) { 10100 String names[] = p.info.authority.split(";"); 10101 p.info.authority = null; 10102 for (int j = 0; j < names.length; j++) { 10103 if (j == 1 && p.syncable) { 10104 // We only want the first authority for a provider to possibly be 10105 // syncable, so if we already added this provider using a different 10106 // authority clear the syncable flag. We copy the provider before 10107 // changing it because the mProviders object contains a reference 10108 // to a provider that we don't want to change. 10109 // Only do this for the second authority since the resulting provider 10110 // object can be the same for all future authorities for this provider. 10111 p = new PackageParser.Provider(p); 10112 p.syncable = false; 10113 } 10114 if (!mProvidersByAuthority.containsKey(names[j])) { 10115 mProvidersByAuthority.put(names[j], p); 10116 if (p.info.authority == null) { 10117 p.info.authority = names[j]; 10118 } else { 10119 p.info.authority = p.info.authority + ";" + names[j]; 10120 } 10121 if (DEBUG_PACKAGE_SCANNING) { 10122 if (chatty) 10123 Log.d(TAG, "Registered content provider: " + names[j] 10124 + ", className = " + p.info.name + ", isSyncable = " 10125 + p.info.isSyncable); 10126 } 10127 } else { 10128 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10129 Slog.w(TAG, "Skipping provider name " + names[j] + 10130 " (in package " + pkg.applicationInfo.packageName + 10131 "): name already used by " 10132 + ((other != null && other.getComponentName() != null) 10133 ? other.getComponentName().getPackageName() : "?")); 10134 } 10135 } 10136 } 10137 if (chatty) { 10138 if (r == null) { 10139 r = new StringBuilder(256); 10140 } else { 10141 r.append(' '); 10142 } 10143 r.append(p.info.name); 10144 } 10145 } 10146 if (r != null) { 10147 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10148 } 10149 10150 N = pkg.services.size(); 10151 r = null; 10152 for (i=0; i<N; i++) { 10153 PackageParser.Service s = pkg.services.get(i); 10154 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10155 s.info.processName); 10156 mServices.addService(s); 10157 if (chatty) { 10158 if (r == null) { 10159 r = new StringBuilder(256); 10160 } else { 10161 r.append(' '); 10162 } 10163 r.append(s.info.name); 10164 } 10165 } 10166 if (r != null) { 10167 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10168 } 10169 10170 N = pkg.receivers.size(); 10171 r = null; 10172 for (i=0; i<N; i++) { 10173 PackageParser.Activity a = pkg.receivers.get(i); 10174 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10175 a.info.processName); 10176 mReceivers.addActivity(a, "receiver"); 10177 if (chatty) { 10178 if (r == null) { 10179 r = new StringBuilder(256); 10180 } else { 10181 r.append(' '); 10182 } 10183 r.append(a.info.name); 10184 } 10185 } 10186 if (r != null) { 10187 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10188 } 10189 10190 N = pkg.activities.size(); 10191 r = null; 10192 for (i=0; i<N; i++) { 10193 PackageParser.Activity a = pkg.activities.get(i); 10194 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10195 a.info.processName); 10196 mActivities.addActivity(a, "activity"); 10197 if (chatty) { 10198 if (r == null) { 10199 r = new StringBuilder(256); 10200 } else { 10201 r.append(' '); 10202 } 10203 r.append(a.info.name); 10204 } 10205 } 10206 if (r != null) { 10207 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10208 } 10209 10210 N = pkg.permissionGroups.size(); 10211 r = null; 10212 for (i=0; i<N; i++) { 10213 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10214 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10215 final String curPackageName = cur == null ? null : cur.info.packageName; 10216 // Dont allow ephemeral apps to define new permission groups. 10217 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10218 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10219 + pg.info.packageName 10220 + " ignored: instant apps cannot define new permission groups."); 10221 continue; 10222 } 10223 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10224 if (cur == null || isPackageUpdate) { 10225 mPermissionGroups.put(pg.info.name, pg); 10226 if (chatty) { 10227 if (r == null) { 10228 r = new StringBuilder(256); 10229 } else { 10230 r.append(' '); 10231 } 10232 if (isPackageUpdate) { 10233 r.append("UPD:"); 10234 } 10235 r.append(pg.info.name); 10236 } 10237 } else { 10238 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10239 + pg.info.packageName + " ignored: original from " 10240 + cur.info.packageName); 10241 if (chatty) { 10242 if (r == null) { 10243 r = new StringBuilder(256); 10244 } else { 10245 r.append(' '); 10246 } 10247 r.append("DUP:"); 10248 r.append(pg.info.name); 10249 } 10250 } 10251 } 10252 if (r != null) { 10253 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10254 } 10255 10256 N = pkg.permissions.size(); 10257 r = null; 10258 for (i=0; i<N; i++) { 10259 PackageParser.Permission p = pkg.permissions.get(i); 10260 10261 // Dont allow ephemeral apps to define new permissions. 10262 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10263 Slog.w(TAG, "Permission " + p.info.name + " from package " 10264 + p.info.packageName 10265 + " ignored: instant apps cannot define new permissions."); 10266 continue; 10267 } 10268 10269 // Assume by default that we did not install this permission into the system. 10270 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10271 10272 // Now that permission groups have a special meaning, we ignore permission 10273 // groups for legacy apps to prevent unexpected behavior. In particular, 10274 // permissions for one app being granted to someone just becase they happen 10275 // to be in a group defined by another app (before this had no implications). 10276 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10277 p.group = mPermissionGroups.get(p.info.group); 10278 // Warn for a permission in an unknown group. 10279 if (p.info.group != null && p.group == null) { 10280 Slog.w(TAG, "Permission " + p.info.name + " from package " 10281 + p.info.packageName + " in an unknown group " + p.info.group); 10282 } 10283 } 10284 10285 ArrayMap<String, BasePermission> permissionMap = 10286 p.tree ? mSettings.mPermissionTrees 10287 : mSettings.mPermissions; 10288 BasePermission bp = permissionMap.get(p.info.name); 10289 10290 // Allow system apps to redefine non-system permissions 10291 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10292 final boolean currentOwnerIsSystem = (bp.perm != null 10293 && isSystemApp(bp.perm.owner)); 10294 if (isSystemApp(p.owner)) { 10295 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10296 // It's a built-in permission and no owner, take ownership now 10297 bp.packageSetting = pkgSetting; 10298 bp.perm = p; 10299 bp.uid = pkg.applicationInfo.uid; 10300 bp.sourcePackage = p.info.packageName; 10301 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10302 } else if (!currentOwnerIsSystem) { 10303 String msg = "New decl " + p.owner + " of permission " 10304 + p.info.name + " is system; overriding " + bp.sourcePackage; 10305 reportSettingsProblem(Log.WARN, msg); 10306 bp = null; 10307 } 10308 } 10309 } 10310 10311 if (bp == null) { 10312 bp = new BasePermission(p.info.name, p.info.packageName, 10313 BasePermission.TYPE_NORMAL); 10314 permissionMap.put(p.info.name, bp); 10315 } 10316 10317 if (bp.perm == null) { 10318 if (bp.sourcePackage == null 10319 || bp.sourcePackage.equals(p.info.packageName)) { 10320 BasePermission tree = findPermissionTreeLP(p.info.name); 10321 if (tree == null 10322 || tree.sourcePackage.equals(p.info.packageName)) { 10323 bp.packageSetting = pkgSetting; 10324 bp.perm = p; 10325 bp.uid = pkg.applicationInfo.uid; 10326 bp.sourcePackage = p.info.packageName; 10327 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10328 if (chatty) { 10329 if (r == null) { 10330 r = new StringBuilder(256); 10331 } else { 10332 r.append(' '); 10333 } 10334 r.append(p.info.name); 10335 } 10336 } else { 10337 Slog.w(TAG, "Permission " + p.info.name + " from package " 10338 + p.info.packageName + " ignored: base tree " 10339 + tree.name + " is from package " 10340 + tree.sourcePackage); 10341 } 10342 } else { 10343 Slog.w(TAG, "Permission " + p.info.name + " from package " 10344 + p.info.packageName + " ignored: original from " 10345 + bp.sourcePackage); 10346 } 10347 } else if (chatty) { 10348 if (r == null) { 10349 r = new StringBuilder(256); 10350 } else { 10351 r.append(' '); 10352 } 10353 r.append("DUP:"); 10354 r.append(p.info.name); 10355 } 10356 if (bp.perm == p) { 10357 bp.protectionLevel = p.info.protectionLevel; 10358 } 10359 } 10360 10361 if (r != null) { 10362 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10363 } 10364 10365 N = pkg.instrumentation.size(); 10366 r = null; 10367 for (i=0; i<N; i++) { 10368 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10369 a.info.packageName = pkg.applicationInfo.packageName; 10370 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10371 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10372 a.info.splitNames = pkg.splitNames; 10373 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10374 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10375 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10376 a.info.dataDir = pkg.applicationInfo.dataDir; 10377 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10378 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10379 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10380 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10381 mInstrumentation.put(a.getComponentName(), a); 10382 if (chatty) { 10383 if (r == null) { 10384 r = new StringBuilder(256); 10385 } else { 10386 r.append(' '); 10387 } 10388 r.append(a.info.name); 10389 } 10390 } 10391 if (r != null) { 10392 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10393 } 10394 10395 if (pkg.protectedBroadcasts != null) { 10396 N = pkg.protectedBroadcasts.size(); 10397 for (i=0; i<N; i++) { 10398 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10399 } 10400 } 10401 10402 // Create idmap files for pairs of (packages, overlay packages). 10403 // Note: "android", ie framework-res.apk, is handled by native layers. 10404 if (pkg.mOverlayTarget != null) { 10405 // This is an overlay package. 10406 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 10407 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 10408 mOverlays.put(pkg.mOverlayTarget, 10409 new ArrayMap<String, PackageParser.Package>()); 10410 } 10411 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 10412 map.put(pkg.packageName, pkg); 10413 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 10414 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 10415 createIdmapFailed = true; 10416 } 10417 } 10418 } else if (mOverlays.containsKey(pkg.packageName) && 10419 !pkg.packageName.equals("android")) { 10420 // This is a regular package, with one or more known overlay packages. 10421 createIdmapsForPackageLI(pkg); 10422 } 10423 } 10424 10425 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10426 10427 if (createIdmapFailed) { 10428 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10429 "scanPackageLI failed to createIdmap"); 10430 } 10431 } 10432 10433 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10434 PackageParser.Package update, int[] userIds) { 10435 if (existing.applicationInfo == null || update.applicationInfo == null) { 10436 // This isn't due to an app installation. 10437 return; 10438 } 10439 10440 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10441 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10442 10443 // The codePath hasn't changed, so there's nothing for us to do. 10444 if (Objects.equals(oldCodePath, newCodePath)) { 10445 return; 10446 } 10447 10448 File canonicalNewCodePath; 10449 try { 10450 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10451 } catch (IOException e) { 10452 Slog.w(TAG, "Failed to get canonical path.", e); 10453 return; 10454 } 10455 10456 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10457 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10458 // that the last component of the path (i.e, the name) doesn't need canonicalization 10459 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10460 // but may change in the future. Hopefully this function won't exist at that point. 10461 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10462 oldCodePath.getName()); 10463 10464 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10465 // with "@". 10466 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10467 if (!oldMarkerPrefix.endsWith("@")) { 10468 oldMarkerPrefix += "@"; 10469 } 10470 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10471 if (!newMarkerPrefix.endsWith("@")) { 10472 newMarkerPrefix += "@"; 10473 } 10474 10475 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10476 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10477 for (String updatedPath : updatedPaths) { 10478 String updatedPathName = new File(updatedPath).getName(); 10479 markerSuffixes.add(updatedPathName.replace('/', '@')); 10480 } 10481 10482 for (int userId : userIds) { 10483 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10484 10485 for (String markerSuffix : markerSuffixes) { 10486 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10487 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10488 if (oldForeignUseMark.exists()) { 10489 try { 10490 Os.rename(oldForeignUseMark.getAbsolutePath(), 10491 newForeignUseMark.getAbsolutePath()); 10492 } catch (ErrnoException e) { 10493 Slog.w(TAG, "Failed to rename foreign use marker", e); 10494 oldForeignUseMark.delete(); 10495 } 10496 } 10497 } 10498 } 10499 } 10500 10501 /** 10502 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10503 * is derived purely on the basis of the contents of {@code scanFile} and 10504 * {@code cpuAbiOverride}. 10505 * 10506 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10507 */ 10508 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10509 String cpuAbiOverride, boolean extractLibs, 10510 File appLib32InstallDir) 10511 throws PackageManagerException { 10512 // Give ourselves some initial paths; we'll come back for another 10513 // pass once we've determined ABI below. 10514 setNativeLibraryPaths(pkg, appLib32InstallDir); 10515 10516 // We would never need to extract libs for forward-locked and external packages, 10517 // since the container service will do it for us. We shouldn't attempt to 10518 // extract libs from system app when it was not updated. 10519 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10520 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10521 extractLibs = false; 10522 } 10523 10524 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10525 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10526 10527 NativeLibraryHelper.Handle handle = null; 10528 try { 10529 handle = NativeLibraryHelper.Handle.create(pkg); 10530 // TODO(multiArch): This can be null for apps that didn't go through the 10531 // usual installation process. We can calculate it again, like we 10532 // do during install time. 10533 // 10534 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10535 // unnecessary. 10536 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10537 10538 // Null out the abis so that they can be recalculated. 10539 pkg.applicationInfo.primaryCpuAbi = null; 10540 pkg.applicationInfo.secondaryCpuAbi = null; 10541 if (isMultiArch(pkg.applicationInfo)) { 10542 // Warn if we've set an abiOverride for multi-lib packages.. 10543 // By definition, we need to copy both 32 and 64 bit libraries for 10544 // such packages. 10545 if (pkg.cpuAbiOverride != null 10546 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10547 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10548 } 10549 10550 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10551 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10552 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10553 if (extractLibs) { 10554 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10555 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10556 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10557 useIsaSpecificSubdirs); 10558 } else { 10559 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10560 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10561 } 10562 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10563 } 10564 10565 maybeThrowExceptionForMultiArchCopy( 10566 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10567 10568 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10569 if (extractLibs) { 10570 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10571 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10572 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10573 useIsaSpecificSubdirs); 10574 } else { 10575 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10576 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10577 } 10578 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10579 } 10580 10581 maybeThrowExceptionForMultiArchCopy( 10582 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10583 10584 if (abi64 >= 0) { 10585 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10586 } 10587 10588 if (abi32 >= 0) { 10589 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10590 if (abi64 >= 0) { 10591 if (pkg.use32bitAbi) { 10592 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10593 pkg.applicationInfo.primaryCpuAbi = abi; 10594 } else { 10595 pkg.applicationInfo.secondaryCpuAbi = abi; 10596 } 10597 } else { 10598 pkg.applicationInfo.primaryCpuAbi = abi; 10599 } 10600 } 10601 10602 } else { 10603 String[] abiList = (cpuAbiOverride != null) ? 10604 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10605 10606 // Enable gross and lame hacks for apps that are built with old 10607 // SDK tools. We must scan their APKs for renderscript bitcode and 10608 // not launch them if it's present. Don't bother checking on devices 10609 // that don't have 64 bit support. 10610 boolean needsRenderScriptOverride = false; 10611 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10612 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10613 abiList = Build.SUPPORTED_32_BIT_ABIS; 10614 needsRenderScriptOverride = true; 10615 } 10616 10617 final int copyRet; 10618 if (extractLibs) { 10619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10620 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10621 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10622 } else { 10623 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10624 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10625 } 10626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10627 10628 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10629 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10630 "Error unpackaging native libs for app, errorCode=" + copyRet); 10631 } 10632 10633 if (copyRet >= 0) { 10634 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10635 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10636 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10637 } else if (needsRenderScriptOverride) { 10638 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10639 } 10640 } 10641 } catch (IOException ioe) { 10642 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10643 } finally { 10644 IoUtils.closeQuietly(handle); 10645 } 10646 10647 // Now that we've calculated the ABIs and determined if it's an internal app, 10648 // we will go ahead and populate the nativeLibraryPath. 10649 setNativeLibraryPaths(pkg, appLib32InstallDir); 10650 } 10651 10652 /** 10653 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10654 * i.e, so that all packages can be run inside a single process if required. 10655 * 10656 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10657 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10658 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10659 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10660 * updating a package that belongs to a shared user. 10661 * 10662 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10663 * adds unnecessary complexity. 10664 */ 10665 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10666 PackageParser.Package scannedPackage) { 10667 String requiredInstructionSet = null; 10668 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10669 requiredInstructionSet = VMRuntime.getInstructionSet( 10670 scannedPackage.applicationInfo.primaryCpuAbi); 10671 } 10672 10673 PackageSetting requirer = null; 10674 for (PackageSetting ps : packagesForUser) { 10675 // If packagesForUser contains scannedPackage, we skip it. This will happen 10676 // when scannedPackage is an update of an existing package. Without this check, 10677 // we will never be able to change the ABI of any package belonging to a shared 10678 // user, even if it's compatible with other packages. 10679 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10680 if (ps.primaryCpuAbiString == null) { 10681 continue; 10682 } 10683 10684 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10685 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10686 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10687 // this but there's not much we can do. 10688 String errorMessage = "Instruction set mismatch, " 10689 + ((requirer == null) ? "[caller]" : requirer) 10690 + " requires " + requiredInstructionSet + " whereas " + ps 10691 + " requires " + instructionSet; 10692 Slog.w(TAG, errorMessage); 10693 } 10694 10695 if (requiredInstructionSet == null) { 10696 requiredInstructionSet = instructionSet; 10697 requirer = ps; 10698 } 10699 } 10700 } 10701 10702 if (requiredInstructionSet != null) { 10703 String adjustedAbi; 10704 if (requirer != null) { 10705 // requirer != null implies that either scannedPackage was null or that scannedPackage 10706 // did not require an ABI, in which case we have to adjust scannedPackage to match 10707 // the ABI of the set (which is the same as requirer's ABI) 10708 adjustedAbi = requirer.primaryCpuAbiString; 10709 if (scannedPackage != null) { 10710 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10711 } 10712 } else { 10713 // requirer == null implies that we're updating all ABIs in the set to 10714 // match scannedPackage. 10715 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10716 } 10717 10718 for (PackageSetting ps : packagesForUser) { 10719 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10720 if (ps.primaryCpuAbiString != null) { 10721 continue; 10722 } 10723 10724 ps.primaryCpuAbiString = adjustedAbi; 10725 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10726 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10727 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10728 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10729 + " (requirer=" 10730 + (requirer == null ? "null" : requirer.pkg.packageName) 10731 + ", scannedPackage=" 10732 + (scannedPackage != null ? scannedPackage.packageName : "null") 10733 + ")"); 10734 try { 10735 mInstaller.rmdex(ps.codePathString, 10736 getDexCodeInstructionSet(getPreferredInstructionSet())); 10737 } catch (InstallerException ignored) { 10738 } 10739 } 10740 } 10741 } 10742 } 10743 } 10744 10745 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10746 synchronized (mPackages) { 10747 mResolverReplaced = true; 10748 // Set up information for custom user intent resolution activity. 10749 mResolveActivity.applicationInfo = pkg.applicationInfo; 10750 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10751 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10752 mResolveActivity.processName = pkg.applicationInfo.packageName; 10753 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10754 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10755 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10756 mResolveActivity.theme = 0; 10757 mResolveActivity.exported = true; 10758 mResolveActivity.enabled = true; 10759 mResolveInfo.activityInfo = mResolveActivity; 10760 mResolveInfo.priority = 0; 10761 mResolveInfo.preferredOrder = 0; 10762 mResolveInfo.match = 0; 10763 mResolveComponentName = mCustomResolverComponentName; 10764 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10765 mResolveComponentName); 10766 } 10767 } 10768 10769 private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) { 10770 if (installerComponent == null) { 10771 if (DEBUG_EPHEMERAL) { 10772 Slog.d(TAG, "Clear ephemeral installer activity"); 10773 } 10774 mInstantAppInstallerActivity.applicationInfo = null; 10775 return; 10776 } 10777 10778 if (DEBUG_EPHEMERAL) { 10779 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10780 } 10781 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10782 // Set up information for ephemeral installer activity 10783 mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo; 10784 mInstantAppInstallerActivity.name = installerComponent.getClassName(); 10785 mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName; 10786 mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName; 10787 mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10788 mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10789 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10790 mInstantAppInstallerActivity.theme = 0; 10791 mInstantAppInstallerActivity.exported = true; 10792 mInstantAppInstallerActivity.enabled = true; 10793 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10794 mInstantAppInstallerInfo.priority = 0; 10795 mInstantAppInstallerInfo.preferredOrder = 1; 10796 mInstantAppInstallerInfo.isDefault = true; 10797 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10798 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10799 } 10800 10801 private static String calculateBundledApkRoot(final String codePathString) { 10802 final File codePath = new File(codePathString); 10803 final File codeRoot; 10804 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10805 codeRoot = Environment.getRootDirectory(); 10806 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10807 codeRoot = Environment.getOemDirectory(); 10808 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10809 codeRoot = Environment.getVendorDirectory(); 10810 } else { 10811 // Unrecognized code path; take its top real segment as the apk root: 10812 // e.g. /something/app/blah.apk => /something 10813 try { 10814 File f = codePath.getCanonicalFile(); 10815 File parent = f.getParentFile(); // non-null because codePath is a file 10816 File tmp; 10817 while ((tmp = parent.getParentFile()) != null) { 10818 f = parent; 10819 parent = tmp; 10820 } 10821 codeRoot = f; 10822 Slog.w(TAG, "Unrecognized code path " 10823 + codePath + " - using " + codeRoot); 10824 } catch (IOException e) { 10825 // Can't canonicalize the code path -- shenanigans? 10826 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10827 return Environment.getRootDirectory().getPath(); 10828 } 10829 } 10830 return codeRoot.getPath(); 10831 } 10832 10833 /** 10834 * Derive and set the location of native libraries for the given package, 10835 * which varies depending on where and how the package was installed. 10836 */ 10837 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10838 final ApplicationInfo info = pkg.applicationInfo; 10839 final String codePath = pkg.codePath; 10840 final File codeFile = new File(codePath); 10841 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10842 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10843 10844 info.nativeLibraryRootDir = null; 10845 info.nativeLibraryRootRequiresIsa = false; 10846 info.nativeLibraryDir = null; 10847 info.secondaryNativeLibraryDir = null; 10848 10849 if (isApkFile(codeFile)) { 10850 // Monolithic install 10851 if (bundledApp) { 10852 // If "/system/lib64/apkname" exists, assume that is the per-package 10853 // native library directory to use; otherwise use "/system/lib/apkname". 10854 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10855 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10856 getPrimaryInstructionSet(info)); 10857 10858 // This is a bundled system app so choose the path based on the ABI. 10859 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10860 // is just the default path. 10861 final String apkName = deriveCodePathName(codePath); 10862 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10863 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10864 apkName).getAbsolutePath(); 10865 10866 if (info.secondaryCpuAbi != null) { 10867 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10868 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10869 secondaryLibDir, apkName).getAbsolutePath(); 10870 } 10871 } else if (asecApp) { 10872 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10873 .getAbsolutePath(); 10874 } else { 10875 final String apkName = deriveCodePathName(codePath); 10876 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10877 .getAbsolutePath(); 10878 } 10879 10880 info.nativeLibraryRootRequiresIsa = false; 10881 info.nativeLibraryDir = info.nativeLibraryRootDir; 10882 } else { 10883 // Cluster install 10884 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10885 info.nativeLibraryRootRequiresIsa = true; 10886 10887 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10888 getPrimaryInstructionSet(info)).getAbsolutePath(); 10889 10890 if (info.secondaryCpuAbi != null) { 10891 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10892 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10893 } 10894 } 10895 } 10896 10897 /** 10898 * Calculate the abis and roots for a bundled app. These can uniquely 10899 * be determined from the contents of the system partition, i.e whether 10900 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10901 * of this information, and instead assume that the system was built 10902 * sensibly. 10903 */ 10904 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10905 PackageSetting pkgSetting) { 10906 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10907 10908 // If "/system/lib64/apkname" exists, assume that is the per-package 10909 // native library directory to use; otherwise use "/system/lib/apkname". 10910 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10911 setBundledAppAbi(pkg, apkRoot, apkName); 10912 // pkgSetting might be null during rescan following uninstall of updates 10913 // to a bundled app, so accommodate that possibility. The settings in 10914 // that case will be established later from the parsed package. 10915 // 10916 // If the settings aren't null, sync them up with what we've just derived. 10917 // note that apkRoot isn't stored in the package settings. 10918 if (pkgSetting != null) { 10919 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10920 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10921 } 10922 } 10923 10924 /** 10925 * Deduces the ABI of a bundled app and sets the relevant fields on the 10926 * parsed pkg object. 10927 * 10928 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10929 * under which system libraries are installed. 10930 * @param apkName the name of the installed package. 10931 */ 10932 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10933 final File codeFile = new File(pkg.codePath); 10934 10935 final boolean has64BitLibs; 10936 final boolean has32BitLibs; 10937 if (isApkFile(codeFile)) { 10938 // Monolithic install 10939 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10940 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10941 } else { 10942 // Cluster install 10943 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10944 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10945 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10946 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10947 has64BitLibs = (new File(rootDir, isa)).exists(); 10948 } else { 10949 has64BitLibs = false; 10950 } 10951 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10952 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10953 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10954 has32BitLibs = (new File(rootDir, isa)).exists(); 10955 } else { 10956 has32BitLibs = false; 10957 } 10958 } 10959 10960 if (has64BitLibs && !has32BitLibs) { 10961 // The package has 64 bit libs, but not 32 bit libs. Its primary 10962 // ABI should be 64 bit. We can safely assume here that the bundled 10963 // native libraries correspond to the most preferred ABI in the list. 10964 10965 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10966 pkg.applicationInfo.secondaryCpuAbi = null; 10967 } else if (has32BitLibs && !has64BitLibs) { 10968 // The package has 32 bit libs but not 64 bit libs. Its primary 10969 // ABI should be 32 bit. 10970 10971 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10972 pkg.applicationInfo.secondaryCpuAbi = null; 10973 } else if (has32BitLibs && has64BitLibs) { 10974 // The application has both 64 and 32 bit bundled libraries. We check 10975 // here that the app declares multiArch support, and warn if it doesn't. 10976 // 10977 // We will be lenient here and record both ABIs. The primary will be the 10978 // ABI that's higher on the list, i.e, a device that's configured to prefer 10979 // 64 bit apps will see a 64 bit primary ABI, 10980 10981 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10982 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10983 } 10984 10985 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10986 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10987 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10988 } else { 10989 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10990 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10991 } 10992 } else { 10993 pkg.applicationInfo.primaryCpuAbi = null; 10994 pkg.applicationInfo.secondaryCpuAbi = null; 10995 } 10996 } 10997 10998 private void killApplication(String pkgName, int appId, String reason) { 10999 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11000 } 11001 11002 private void killApplication(String pkgName, int appId, int userId, String reason) { 11003 // Request the ActivityManager to kill the process(only for existing packages) 11004 // so that we do not end up in a confused state while the user is still using the older 11005 // version of the application while the new one gets installed. 11006 final long token = Binder.clearCallingIdentity(); 11007 try { 11008 IActivityManager am = ActivityManager.getService(); 11009 if (am != null) { 11010 try { 11011 am.killApplication(pkgName, appId, userId, reason); 11012 } catch (RemoteException e) { 11013 } 11014 } 11015 } finally { 11016 Binder.restoreCallingIdentity(token); 11017 } 11018 } 11019 11020 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11021 // Remove the parent package setting 11022 PackageSetting ps = (PackageSetting) pkg.mExtras; 11023 if (ps != null) { 11024 removePackageLI(ps, chatty); 11025 } 11026 // Remove the child package setting 11027 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11028 for (int i = 0; i < childCount; i++) { 11029 PackageParser.Package childPkg = pkg.childPackages.get(i); 11030 ps = (PackageSetting) childPkg.mExtras; 11031 if (ps != null) { 11032 removePackageLI(ps, chatty); 11033 } 11034 } 11035 } 11036 11037 void removePackageLI(PackageSetting ps, boolean chatty) { 11038 if (DEBUG_INSTALL) { 11039 if (chatty) 11040 Log.d(TAG, "Removing package " + ps.name); 11041 } 11042 11043 // writer 11044 synchronized (mPackages) { 11045 mPackages.remove(ps.name); 11046 final PackageParser.Package pkg = ps.pkg; 11047 if (pkg != null) { 11048 cleanPackageDataStructuresLILPw(pkg, chatty); 11049 } 11050 } 11051 } 11052 11053 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11054 if (DEBUG_INSTALL) { 11055 if (chatty) 11056 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11057 } 11058 11059 // writer 11060 synchronized (mPackages) { 11061 // Remove the parent package 11062 mPackages.remove(pkg.applicationInfo.packageName); 11063 cleanPackageDataStructuresLILPw(pkg, chatty); 11064 11065 // Remove the child packages 11066 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11067 for (int i = 0; i < childCount; i++) { 11068 PackageParser.Package childPkg = pkg.childPackages.get(i); 11069 mPackages.remove(childPkg.applicationInfo.packageName); 11070 cleanPackageDataStructuresLILPw(childPkg, chatty); 11071 } 11072 } 11073 } 11074 11075 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11076 int N = pkg.providers.size(); 11077 StringBuilder r = null; 11078 int i; 11079 for (i=0; i<N; i++) { 11080 PackageParser.Provider p = pkg.providers.get(i); 11081 mProviders.removeProvider(p); 11082 if (p.info.authority == null) { 11083 11084 /* There was another ContentProvider with this authority when 11085 * this app was installed so this authority is null, 11086 * Ignore it as we don't have to unregister the provider. 11087 */ 11088 continue; 11089 } 11090 String names[] = p.info.authority.split(";"); 11091 for (int j = 0; j < names.length; j++) { 11092 if (mProvidersByAuthority.get(names[j]) == p) { 11093 mProvidersByAuthority.remove(names[j]); 11094 if (DEBUG_REMOVE) { 11095 if (chatty) 11096 Log.d(TAG, "Unregistered content provider: " + names[j] 11097 + ", className = " + p.info.name + ", isSyncable = " 11098 + p.info.isSyncable); 11099 } 11100 } 11101 } 11102 if (DEBUG_REMOVE && chatty) { 11103 if (r == null) { 11104 r = new StringBuilder(256); 11105 } else { 11106 r.append(' '); 11107 } 11108 r.append(p.info.name); 11109 } 11110 } 11111 if (r != null) { 11112 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11113 } 11114 11115 N = pkg.services.size(); 11116 r = null; 11117 for (i=0; i<N; i++) { 11118 PackageParser.Service s = pkg.services.get(i); 11119 mServices.removeService(s); 11120 if (chatty) { 11121 if (r == null) { 11122 r = new StringBuilder(256); 11123 } else { 11124 r.append(' '); 11125 } 11126 r.append(s.info.name); 11127 } 11128 } 11129 if (r != null) { 11130 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11131 } 11132 11133 N = pkg.receivers.size(); 11134 r = null; 11135 for (i=0; i<N; i++) { 11136 PackageParser.Activity a = pkg.receivers.get(i); 11137 mReceivers.removeActivity(a, "receiver"); 11138 if (DEBUG_REMOVE && chatty) { 11139 if (r == null) { 11140 r = new StringBuilder(256); 11141 } else { 11142 r.append(' '); 11143 } 11144 r.append(a.info.name); 11145 } 11146 } 11147 if (r != null) { 11148 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11149 } 11150 11151 N = pkg.activities.size(); 11152 r = null; 11153 for (i=0; i<N; i++) { 11154 PackageParser.Activity a = pkg.activities.get(i); 11155 mActivities.removeActivity(a, "activity"); 11156 if (DEBUG_REMOVE && chatty) { 11157 if (r == null) { 11158 r = new StringBuilder(256); 11159 } else { 11160 r.append(' '); 11161 } 11162 r.append(a.info.name); 11163 } 11164 } 11165 if (r != null) { 11166 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11167 } 11168 11169 N = pkg.permissions.size(); 11170 r = null; 11171 for (i=0; i<N; i++) { 11172 PackageParser.Permission p = pkg.permissions.get(i); 11173 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11174 if (bp == null) { 11175 bp = mSettings.mPermissionTrees.get(p.info.name); 11176 } 11177 if (bp != null && bp.perm == p) { 11178 bp.perm = null; 11179 if (DEBUG_REMOVE && chatty) { 11180 if (r == null) { 11181 r = new StringBuilder(256); 11182 } else { 11183 r.append(' '); 11184 } 11185 r.append(p.info.name); 11186 } 11187 } 11188 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11189 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11190 if (appOpPkgs != null) { 11191 appOpPkgs.remove(pkg.packageName); 11192 } 11193 } 11194 } 11195 if (r != null) { 11196 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11197 } 11198 11199 N = pkg.requestedPermissions.size(); 11200 r = null; 11201 for (i=0; i<N; i++) { 11202 String perm = pkg.requestedPermissions.get(i); 11203 BasePermission bp = mSettings.mPermissions.get(perm); 11204 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11205 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11206 if (appOpPkgs != null) { 11207 appOpPkgs.remove(pkg.packageName); 11208 if (appOpPkgs.isEmpty()) { 11209 mAppOpPermissionPackages.remove(perm); 11210 } 11211 } 11212 } 11213 } 11214 if (r != null) { 11215 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11216 } 11217 11218 N = pkg.instrumentation.size(); 11219 r = null; 11220 for (i=0; i<N; i++) { 11221 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11222 mInstrumentation.remove(a.getComponentName()); 11223 if (DEBUG_REMOVE && chatty) { 11224 if (r == null) { 11225 r = new StringBuilder(256); 11226 } else { 11227 r.append(' '); 11228 } 11229 r.append(a.info.name); 11230 } 11231 } 11232 if (r != null) { 11233 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11234 } 11235 11236 r = null; 11237 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11238 // Only system apps can hold shared libraries. 11239 if (pkg.libraryNames != null) { 11240 for (i = 0; i < pkg.libraryNames.size(); i++) { 11241 String name = pkg.libraryNames.get(i); 11242 if (removeSharedLibraryLPw(name, 0)) { 11243 if (DEBUG_REMOVE && chatty) { 11244 if (r == null) { 11245 r = new StringBuilder(256); 11246 } else { 11247 r.append(' '); 11248 } 11249 r.append(name); 11250 } 11251 } 11252 } 11253 } 11254 } 11255 11256 r = null; 11257 11258 // Any package can hold static shared libraries. 11259 if (pkg.staticSharedLibName != null) { 11260 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11261 if (DEBUG_REMOVE && chatty) { 11262 if (r == null) { 11263 r = new StringBuilder(256); 11264 } else { 11265 r.append(' '); 11266 } 11267 r.append(pkg.staticSharedLibName); 11268 } 11269 } 11270 } 11271 11272 if (r != null) { 11273 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11274 } 11275 } 11276 11277 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11278 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11279 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11280 return true; 11281 } 11282 } 11283 return false; 11284 } 11285 11286 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11287 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11288 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11289 11290 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11291 // Update the parent permissions 11292 updatePermissionsLPw(pkg.packageName, pkg, flags); 11293 // Update the child permissions 11294 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11295 for (int i = 0; i < childCount; i++) { 11296 PackageParser.Package childPkg = pkg.childPackages.get(i); 11297 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11298 } 11299 } 11300 11301 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11302 int flags) { 11303 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11304 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11305 } 11306 11307 private void updatePermissionsLPw(String changingPkg, 11308 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11309 // Make sure there are no dangling permission trees. 11310 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11311 while (it.hasNext()) { 11312 final BasePermission bp = it.next(); 11313 if (bp.packageSetting == null) { 11314 // We may not yet have parsed the package, so just see if 11315 // we still know about its settings. 11316 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11317 } 11318 if (bp.packageSetting == null) { 11319 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11320 + " from package " + bp.sourcePackage); 11321 it.remove(); 11322 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11323 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11324 Slog.i(TAG, "Removing old permission tree: " + bp.name 11325 + " from package " + bp.sourcePackage); 11326 flags |= UPDATE_PERMISSIONS_ALL; 11327 it.remove(); 11328 } 11329 } 11330 } 11331 11332 // Make sure all dynamic permissions have been assigned to a package, 11333 // and make sure there are no dangling permissions. 11334 it = mSettings.mPermissions.values().iterator(); 11335 while (it.hasNext()) { 11336 final BasePermission bp = it.next(); 11337 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11338 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11339 + bp.name + " pkg=" + bp.sourcePackage 11340 + " info=" + bp.pendingInfo); 11341 if (bp.packageSetting == null && bp.pendingInfo != null) { 11342 final BasePermission tree = findPermissionTreeLP(bp.name); 11343 if (tree != null && tree.perm != null) { 11344 bp.packageSetting = tree.packageSetting; 11345 bp.perm = new PackageParser.Permission(tree.perm.owner, 11346 new PermissionInfo(bp.pendingInfo)); 11347 bp.perm.info.packageName = tree.perm.info.packageName; 11348 bp.perm.info.name = bp.name; 11349 bp.uid = tree.uid; 11350 } 11351 } 11352 } 11353 if (bp.packageSetting == null) { 11354 // We may not yet have parsed the package, so just see if 11355 // we still know about its settings. 11356 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11357 } 11358 if (bp.packageSetting == null) { 11359 Slog.w(TAG, "Removing dangling permission: " + bp.name 11360 + " from package " + bp.sourcePackage); 11361 it.remove(); 11362 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11363 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11364 Slog.i(TAG, "Removing old permission: " + bp.name 11365 + " from package " + bp.sourcePackage); 11366 flags |= UPDATE_PERMISSIONS_ALL; 11367 it.remove(); 11368 } 11369 } 11370 } 11371 11372 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11373 // Now update the permissions for all packages, in particular 11374 // replace the granted permissions of the system packages. 11375 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11376 for (PackageParser.Package pkg : mPackages.values()) { 11377 if (pkg != pkgInfo) { 11378 // Only replace for packages on requested volume 11379 final String volumeUuid = getVolumeUuidForPackage(pkg); 11380 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11381 && Objects.equals(replaceVolumeUuid, volumeUuid); 11382 grantPermissionsLPw(pkg, replace, changingPkg); 11383 } 11384 } 11385 } 11386 11387 if (pkgInfo != null) { 11388 // Only replace for packages on requested volume 11389 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11390 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11391 && Objects.equals(replaceVolumeUuid, volumeUuid); 11392 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11393 } 11394 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11395 } 11396 11397 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11398 String packageOfInterest) { 11399 // IMPORTANT: There are two types of permissions: install and runtime. 11400 // Install time permissions are granted when the app is installed to 11401 // all device users and users added in the future. Runtime permissions 11402 // are granted at runtime explicitly to specific users. Normal and signature 11403 // protected permissions are install time permissions. Dangerous permissions 11404 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11405 // otherwise they are runtime permissions. This function does not manage 11406 // runtime permissions except for the case an app targeting Lollipop MR1 11407 // being upgraded to target a newer SDK, in which case dangerous permissions 11408 // are transformed from install time to runtime ones. 11409 11410 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11411 if (ps == null) { 11412 return; 11413 } 11414 11415 PermissionsState permissionsState = ps.getPermissionsState(); 11416 PermissionsState origPermissions = permissionsState; 11417 11418 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11419 11420 boolean runtimePermissionsRevoked = false; 11421 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11422 11423 boolean changedInstallPermission = false; 11424 11425 if (replace) { 11426 ps.installPermissionsFixed = false; 11427 if (!ps.isSharedUser()) { 11428 origPermissions = new PermissionsState(permissionsState); 11429 permissionsState.reset(); 11430 } else { 11431 // We need to know only about runtime permission changes since the 11432 // calling code always writes the install permissions state but 11433 // the runtime ones are written only if changed. The only cases of 11434 // changed runtime permissions here are promotion of an install to 11435 // runtime and revocation of a runtime from a shared user. 11436 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11437 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11438 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11439 runtimePermissionsRevoked = true; 11440 } 11441 } 11442 } 11443 11444 permissionsState.setGlobalGids(mGlobalGids); 11445 11446 final int N = pkg.requestedPermissions.size(); 11447 for (int i=0; i<N; i++) { 11448 final String name = pkg.requestedPermissions.get(i); 11449 final BasePermission bp = mSettings.mPermissions.get(name); 11450 11451 if (DEBUG_INSTALL) { 11452 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11453 } 11454 11455 if (bp == null || bp.packageSetting == null) { 11456 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11457 Slog.w(TAG, "Unknown permission " + name 11458 + " in package " + pkg.packageName); 11459 } 11460 continue; 11461 } 11462 11463 11464 // Limit ephemeral apps to ephemeral allowed permissions. 11465 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11466 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11467 + pkg.packageName); 11468 continue; 11469 } 11470 11471 final String perm = bp.name; 11472 boolean allowedSig = false; 11473 int grant = GRANT_DENIED; 11474 11475 // Keep track of app op permissions. 11476 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11477 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11478 if (pkgs == null) { 11479 pkgs = new ArraySet<>(); 11480 mAppOpPermissionPackages.put(bp.name, pkgs); 11481 } 11482 pkgs.add(pkg.packageName); 11483 } 11484 11485 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11486 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11487 >= Build.VERSION_CODES.M; 11488 switch (level) { 11489 case PermissionInfo.PROTECTION_NORMAL: { 11490 // For all apps normal permissions are install time ones. 11491 grant = GRANT_INSTALL; 11492 } break; 11493 11494 case PermissionInfo.PROTECTION_DANGEROUS: { 11495 // If a permission review is required for legacy apps we represent 11496 // their permissions as always granted runtime ones since we need 11497 // to keep the review required permission flag per user while an 11498 // install permission's state is shared across all users. 11499 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11500 // For legacy apps dangerous permissions are install time ones. 11501 grant = GRANT_INSTALL; 11502 } else if (origPermissions.hasInstallPermission(bp.name)) { 11503 // For legacy apps that became modern, install becomes runtime. 11504 grant = GRANT_UPGRADE; 11505 } else if (mPromoteSystemApps 11506 && isSystemApp(ps) 11507 && mExistingSystemPackages.contains(ps.name)) { 11508 // For legacy system apps, install becomes runtime. 11509 // We cannot check hasInstallPermission() for system apps since those 11510 // permissions were granted implicitly and not persisted pre-M. 11511 grant = GRANT_UPGRADE; 11512 } else { 11513 // For modern apps keep runtime permissions unchanged. 11514 grant = GRANT_RUNTIME; 11515 } 11516 } break; 11517 11518 case PermissionInfo.PROTECTION_SIGNATURE: { 11519 // For all apps signature permissions are install time ones. 11520 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11521 if (allowedSig) { 11522 grant = GRANT_INSTALL; 11523 } 11524 } break; 11525 } 11526 11527 if (DEBUG_INSTALL) { 11528 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11529 } 11530 11531 if (grant != GRANT_DENIED) { 11532 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11533 // If this is an existing, non-system package, then 11534 // we can't add any new permissions to it. 11535 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11536 // Except... if this is a permission that was added 11537 // to the platform (note: need to only do this when 11538 // updating the platform). 11539 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11540 grant = GRANT_DENIED; 11541 } 11542 } 11543 } 11544 11545 switch (grant) { 11546 case GRANT_INSTALL: { 11547 // Revoke this as runtime permission to handle the case of 11548 // a runtime permission being downgraded to an install one. 11549 // Also in permission review mode we keep dangerous permissions 11550 // for legacy apps 11551 for (int userId : UserManagerService.getInstance().getUserIds()) { 11552 if (origPermissions.getRuntimePermissionState( 11553 bp.name, userId) != null) { 11554 // Revoke the runtime permission and clear the flags. 11555 origPermissions.revokeRuntimePermission(bp, userId); 11556 origPermissions.updatePermissionFlags(bp, userId, 11557 PackageManager.MASK_PERMISSION_FLAGS, 0); 11558 // If we revoked a permission permission, we have to write. 11559 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11560 changedRuntimePermissionUserIds, userId); 11561 } 11562 } 11563 // Grant an install permission. 11564 if (permissionsState.grantInstallPermission(bp) != 11565 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11566 changedInstallPermission = true; 11567 } 11568 } break; 11569 11570 case GRANT_RUNTIME: { 11571 // Grant previously granted runtime permissions. 11572 for (int userId : UserManagerService.getInstance().getUserIds()) { 11573 PermissionState permissionState = origPermissions 11574 .getRuntimePermissionState(bp.name, userId); 11575 int flags = permissionState != null 11576 ? permissionState.getFlags() : 0; 11577 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11578 // Don't propagate the permission in a permission review mode if 11579 // the former was revoked, i.e. marked to not propagate on upgrade. 11580 // Note that in a permission review mode install permissions are 11581 // represented as constantly granted runtime ones since we need to 11582 // keep a per user state associated with the permission. Also the 11583 // revoke on upgrade flag is no longer applicable and is reset. 11584 final boolean revokeOnUpgrade = (flags & PackageManager 11585 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11586 if (revokeOnUpgrade) { 11587 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11588 // Since we changed the flags, we have to write. 11589 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11590 changedRuntimePermissionUserIds, userId); 11591 } 11592 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11593 if (permissionsState.grantRuntimePermission(bp, userId) == 11594 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11595 // If we cannot put the permission as it was, 11596 // we have to write. 11597 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11598 changedRuntimePermissionUserIds, userId); 11599 } 11600 } 11601 11602 // If the app supports runtime permissions no need for a review. 11603 if (mPermissionReviewRequired 11604 && appSupportsRuntimePermissions 11605 && (flags & PackageManager 11606 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11607 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11608 // Since we changed the flags, we have to write. 11609 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11610 changedRuntimePermissionUserIds, userId); 11611 } 11612 } else if (mPermissionReviewRequired 11613 && !appSupportsRuntimePermissions) { 11614 // For legacy apps that need a permission review, every new 11615 // runtime permission is granted but it is pending a review. 11616 // We also need to review only platform defined runtime 11617 // permissions as these are the only ones the platform knows 11618 // how to disable the API to simulate revocation as legacy 11619 // apps don't expect to run with revoked permissions. 11620 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11621 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11622 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11623 // We changed the flags, hence have to write. 11624 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11625 changedRuntimePermissionUserIds, userId); 11626 } 11627 } 11628 if (permissionsState.grantRuntimePermission(bp, userId) 11629 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11630 // We changed the permission, hence have to write. 11631 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11632 changedRuntimePermissionUserIds, userId); 11633 } 11634 } 11635 // Propagate the permission flags. 11636 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11637 } 11638 } break; 11639 11640 case GRANT_UPGRADE: { 11641 // Grant runtime permissions for a previously held install permission. 11642 PermissionState permissionState = origPermissions 11643 .getInstallPermissionState(bp.name); 11644 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11645 11646 if (origPermissions.revokeInstallPermission(bp) 11647 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11648 // We will be transferring the permission flags, so clear them. 11649 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11650 PackageManager.MASK_PERMISSION_FLAGS, 0); 11651 changedInstallPermission = true; 11652 } 11653 11654 // If the permission is not to be promoted to runtime we ignore it and 11655 // also its other flags as they are not applicable to install permissions. 11656 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11657 for (int userId : currentUserIds) { 11658 if (permissionsState.grantRuntimePermission(bp, userId) != 11659 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11660 // Transfer the permission flags. 11661 permissionsState.updatePermissionFlags(bp, userId, 11662 flags, flags); 11663 // If we granted the permission, we have to write. 11664 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11665 changedRuntimePermissionUserIds, userId); 11666 } 11667 } 11668 } 11669 } break; 11670 11671 default: { 11672 if (packageOfInterest == null 11673 || packageOfInterest.equals(pkg.packageName)) { 11674 Slog.w(TAG, "Not granting permission " + perm 11675 + " to package " + pkg.packageName 11676 + " because it was previously installed without"); 11677 } 11678 } break; 11679 } 11680 } else { 11681 if (permissionsState.revokeInstallPermission(bp) != 11682 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11683 // Also drop the permission flags. 11684 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11685 PackageManager.MASK_PERMISSION_FLAGS, 0); 11686 changedInstallPermission = true; 11687 Slog.i(TAG, "Un-granting permission " + perm 11688 + " from package " + pkg.packageName 11689 + " (protectionLevel=" + bp.protectionLevel 11690 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11691 + ")"); 11692 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11693 // Don't print warning for app op permissions, since it is fine for them 11694 // not to be granted, there is a UI for the user to decide. 11695 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11696 Slog.w(TAG, "Not granting permission " + perm 11697 + " to package " + pkg.packageName 11698 + " (protectionLevel=" + bp.protectionLevel 11699 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11700 + ")"); 11701 } 11702 } 11703 } 11704 } 11705 11706 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11707 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11708 // This is the first that we have heard about this package, so the 11709 // permissions we have now selected are fixed until explicitly 11710 // changed. 11711 ps.installPermissionsFixed = true; 11712 } 11713 11714 // Persist the runtime permissions state for users with changes. If permissions 11715 // were revoked because no app in the shared user declares them we have to 11716 // write synchronously to avoid losing runtime permissions state. 11717 for (int userId : changedRuntimePermissionUserIds) { 11718 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11719 } 11720 } 11721 11722 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11723 boolean allowed = false; 11724 final int NP = PackageParser.NEW_PERMISSIONS.length; 11725 for (int ip=0; ip<NP; ip++) { 11726 final PackageParser.NewPermissionInfo npi 11727 = PackageParser.NEW_PERMISSIONS[ip]; 11728 if (npi.name.equals(perm) 11729 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11730 allowed = true; 11731 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11732 + pkg.packageName); 11733 break; 11734 } 11735 } 11736 return allowed; 11737 } 11738 11739 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11740 BasePermission bp, PermissionsState origPermissions) { 11741 boolean privilegedPermission = (bp.protectionLevel 11742 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11743 boolean privappPermissionsDisable = 11744 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11745 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11746 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11747 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11748 && !platformPackage && platformPermission) { 11749 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11750 .getPrivAppPermissions(pkg.packageName); 11751 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11752 if (!whitelisted) { 11753 Slog.w(TAG, "Privileged permission " + perm + " for package " 11754 + pkg.packageName + " - not in privapp-permissions whitelist"); 11755 if (!mSystemReady) { 11756 if (mPrivappPermissionsViolations == null) { 11757 mPrivappPermissionsViolations = new ArraySet<>(); 11758 } 11759 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11760 } 11761 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11762 return false; 11763 } 11764 } 11765 } 11766 boolean allowed = (compareSignatures( 11767 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11768 == PackageManager.SIGNATURE_MATCH) 11769 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11770 == PackageManager.SIGNATURE_MATCH); 11771 if (!allowed && privilegedPermission) { 11772 if (isSystemApp(pkg)) { 11773 // For updated system applications, a system permission 11774 // is granted only if it had been defined by the original application. 11775 if (pkg.isUpdatedSystemApp()) { 11776 final PackageSetting sysPs = mSettings 11777 .getDisabledSystemPkgLPr(pkg.packageName); 11778 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11779 // If the original was granted this permission, we take 11780 // that grant decision as read and propagate it to the 11781 // update. 11782 if (sysPs.isPrivileged()) { 11783 allowed = true; 11784 } 11785 } else { 11786 // The system apk may have been updated with an older 11787 // version of the one on the data partition, but which 11788 // granted a new system permission that it didn't have 11789 // before. In this case we do want to allow the app to 11790 // now get the new permission if the ancestral apk is 11791 // privileged to get it. 11792 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11793 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11794 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11795 allowed = true; 11796 break; 11797 } 11798 } 11799 } 11800 // Also if a privileged parent package on the system image or any of 11801 // its children requested a privileged permission, the updated child 11802 // packages can also get the permission. 11803 if (pkg.parentPackage != null) { 11804 final PackageSetting disabledSysParentPs = mSettings 11805 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11806 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11807 && disabledSysParentPs.isPrivileged()) { 11808 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11809 allowed = true; 11810 } else if (disabledSysParentPs.pkg.childPackages != null) { 11811 final int count = disabledSysParentPs.pkg.childPackages.size(); 11812 for (int i = 0; i < count; i++) { 11813 PackageParser.Package disabledSysChildPkg = 11814 disabledSysParentPs.pkg.childPackages.get(i); 11815 if (isPackageRequestingPermission(disabledSysChildPkg, 11816 perm)) { 11817 allowed = true; 11818 break; 11819 } 11820 } 11821 } 11822 } 11823 } 11824 } 11825 } else { 11826 allowed = isPrivilegedApp(pkg); 11827 } 11828 } 11829 } 11830 if (!allowed) { 11831 if (!allowed && (bp.protectionLevel 11832 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11833 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11834 // If this was a previously normal/dangerous permission that got moved 11835 // to a system permission as part of the runtime permission redesign, then 11836 // we still want to blindly grant it to old apps. 11837 allowed = true; 11838 } 11839 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11840 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11841 // If this permission is to be granted to the system installer and 11842 // this app is an installer, then it gets the permission. 11843 allowed = true; 11844 } 11845 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11846 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11847 // If this permission is to be granted to the system verifier and 11848 // this app is a verifier, then it gets the permission. 11849 allowed = true; 11850 } 11851 if (!allowed && (bp.protectionLevel 11852 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11853 && isSystemApp(pkg)) { 11854 // Any pre-installed system app is allowed to get this permission. 11855 allowed = true; 11856 } 11857 if (!allowed && (bp.protectionLevel 11858 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11859 // For development permissions, a development permission 11860 // is granted only if it was already granted. 11861 allowed = origPermissions.hasInstallPermission(perm); 11862 } 11863 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11864 && pkg.packageName.equals(mSetupWizardPackage)) { 11865 // If this permission is to be granted to the system setup wizard and 11866 // this app is a setup wizard, then it gets the permission. 11867 allowed = true; 11868 } 11869 } 11870 return allowed; 11871 } 11872 11873 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11874 final int permCount = pkg.requestedPermissions.size(); 11875 for (int j = 0; j < permCount; j++) { 11876 String requestedPermission = pkg.requestedPermissions.get(j); 11877 if (permission.equals(requestedPermission)) { 11878 return true; 11879 } 11880 } 11881 return false; 11882 } 11883 11884 final class ActivityIntentResolver 11885 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11886 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11887 boolean defaultOnly, int userId) { 11888 if (!sUserManager.exists(userId)) return null; 11889 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11890 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11891 } 11892 11893 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11894 int userId) { 11895 if (!sUserManager.exists(userId)) return null; 11896 mFlags = flags; 11897 return super.queryIntent(intent, resolvedType, 11898 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11899 userId); 11900 } 11901 11902 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11903 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11904 if (!sUserManager.exists(userId)) return null; 11905 if (packageActivities == null) { 11906 return null; 11907 } 11908 mFlags = flags; 11909 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11910 final int N = packageActivities.size(); 11911 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11912 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11913 11914 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11915 for (int i = 0; i < N; ++i) { 11916 intentFilters = packageActivities.get(i).intents; 11917 if (intentFilters != null && intentFilters.size() > 0) { 11918 PackageParser.ActivityIntentInfo[] array = 11919 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11920 intentFilters.toArray(array); 11921 listCut.add(array); 11922 } 11923 } 11924 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11925 } 11926 11927 /** 11928 * Finds a privileged activity that matches the specified activity names. 11929 */ 11930 private PackageParser.Activity findMatchingActivity( 11931 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11932 for (PackageParser.Activity sysActivity : activityList) { 11933 if (sysActivity.info.name.equals(activityInfo.name)) { 11934 return sysActivity; 11935 } 11936 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11937 return sysActivity; 11938 } 11939 if (sysActivity.info.targetActivity != null) { 11940 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11941 return sysActivity; 11942 } 11943 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11944 return sysActivity; 11945 } 11946 } 11947 } 11948 return null; 11949 } 11950 11951 public class IterGenerator<E> { 11952 public Iterator<E> generate(ActivityIntentInfo info) { 11953 return null; 11954 } 11955 } 11956 11957 public class ActionIterGenerator extends IterGenerator<String> { 11958 @Override 11959 public Iterator<String> generate(ActivityIntentInfo info) { 11960 return info.actionsIterator(); 11961 } 11962 } 11963 11964 public class CategoriesIterGenerator extends IterGenerator<String> { 11965 @Override 11966 public Iterator<String> generate(ActivityIntentInfo info) { 11967 return info.categoriesIterator(); 11968 } 11969 } 11970 11971 public class SchemesIterGenerator extends IterGenerator<String> { 11972 @Override 11973 public Iterator<String> generate(ActivityIntentInfo info) { 11974 return info.schemesIterator(); 11975 } 11976 } 11977 11978 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11979 @Override 11980 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11981 return info.authoritiesIterator(); 11982 } 11983 } 11984 11985 /** 11986 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11987 * MODIFIED. Do not pass in a list that should not be changed. 11988 */ 11989 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11990 IterGenerator<T> generator, Iterator<T> searchIterator) { 11991 // loop through the set of actions; every one must be found in the intent filter 11992 while (searchIterator.hasNext()) { 11993 // we must have at least one filter in the list to consider a match 11994 if (intentList.size() == 0) { 11995 break; 11996 } 11997 11998 final T searchAction = searchIterator.next(); 11999 12000 // loop through the set of intent filters 12001 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12002 while (intentIter.hasNext()) { 12003 final ActivityIntentInfo intentInfo = intentIter.next(); 12004 boolean selectionFound = false; 12005 12006 // loop through the intent filter's selection criteria; at least one 12007 // of them must match the searched criteria 12008 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12009 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12010 final T intentSelection = intentSelectionIter.next(); 12011 if (intentSelection != null && intentSelection.equals(searchAction)) { 12012 selectionFound = true; 12013 break; 12014 } 12015 } 12016 12017 // the selection criteria wasn't found in this filter's set; this filter 12018 // is not a potential match 12019 if (!selectionFound) { 12020 intentIter.remove(); 12021 } 12022 } 12023 } 12024 } 12025 12026 private boolean isProtectedAction(ActivityIntentInfo filter) { 12027 final Iterator<String> actionsIter = filter.actionsIterator(); 12028 while (actionsIter != null && actionsIter.hasNext()) { 12029 final String filterAction = actionsIter.next(); 12030 if (PROTECTED_ACTIONS.contains(filterAction)) { 12031 return true; 12032 } 12033 } 12034 return false; 12035 } 12036 12037 /** 12038 * Adjusts the priority of the given intent filter according to policy. 12039 * <p> 12040 * <ul> 12041 * <li>The priority for non privileged applications is capped to '0'</li> 12042 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12043 * <li>The priority for unbundled updates to privileged applications is capped to the 12044 * priority defined on the system partition</li> 12045 * </ul> 12046 * <p> 12047 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12048 * allowed to obtain any priority on any action. 12049 */ 12050 private void adjustPriority( 12051 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12052 // nothing to do; priority is fine as-is 12053 if (intent.getPriority() <= 0) { 12054 return; 12055 } 12056 12057 final ActivityInfo activityInfo = intent.activity.info; 12058 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12059 12060 final boolean privilegedApp = 12061 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12062 if (!privilegedApp) { 12063 // non-privileged applications can never define a priority >0 12064 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12065 + " package: " + applicationInfo.packageName 12066 + " activity: " + intent.activity.className 12067 + " origPrio: " + intent.getPriority()); 12068 intent.setPriority(0); 12069 return; 12070 } 12071 12072 if (systemActivities == null) { 12073 // the system package is not disabled; we're parsing the system partition 12074 if (isProtectedAction(intent)) { 12075 if (mDeferProtectedFilters) { 12076 // We can't deal with these just yet. No component should ever obtain a 12077 // >0 priority for a protected actions, with ONE exception -- the setup 12078 // wizard. The setup wizard, however, cannot be known until we're able to 12079 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12080 // until all intent filters have been processed. Chicken, meet egg. 12081 // Let the filter temporarily have a high priority and rectify the 12082 // priorities after all system packages have been scanned. 12083 mProtectedFilters.add(intent); 12084 if (DEBUG_FILTERS) { 12085 Slog.i(TAG, "Protected action; save for later;" 12086 + " package: " + applicationInfo.packageName 12087 + " activity: " + intent.activity.className 12088 + " origPrio: " + intent.getPriority()); 12089 } 12090 return; 12091 } else { 12092 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12093 Slog.i(TAG, "No setup wizard;" 12094 + " All protected intents capped to priority 0"); 12095 } 12096 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12097 if (DEBUG_FILTERS) { 12098 Slog.i(TAG, "Found setup wizard;" 12099 + " allow priority " + intent.getPriority() + ";" 12100 + " package: " + intent.activity.info.packageName 12101 + " activity: " + intent.activity.className 12102 + " priority: " + intent.getPriority()); 12103 } 12104 // setup wizard gets whatever it wants 12105 return; 12106 } 12107 Slog.w(TAG, "Protected action; cap priority to 0;" 12108 + " package: " + intent.activity.info.packageName 12109 + " activity: " + intent.activity.className 12110 + " origPrio: " + intent.getPriority()); 12111 intent.setPriority(0); 12112 return; 12113 } 12114 } 12115 // privileged apps on the system image get whatever priority they request 12116 return; 12117 } 12118 12119 // privileged app unbundled update ... try to find the same activity 12120 final PackageParser.Activity foundActivity = 12121 findMatchingActivity(systemActivities, activityInfo); 12122 if (foundActivity == null) { 12123 // this is a new activity; it cannot obtain >0 priority 12124 if (DEBUG_FILTERS) { 12125 Slog.i(TAG, "New activity; cap priority to 0;" 12126 + " package: " + applicationInfo.packageName 12127 + " activity: " + intent.activity.className 12128 + " origPrio: " + intent.getPriority()); 12129 } 12130 intent.setPriority(0); 12131 return; 12132 } 12133 12134 // found activity, now check for filter equivalence 12135 12136 // a shallow copy is enough; we modify the list, not its contents 12137 final List<ActivityIntentInfo> intentListCopy = 12138 new ArrayList<>(foundActivity.intents); 12139 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12140 12141 // find matching action subsets 12142 final Iterator<String> actionsIterator = intent.actionsIterator(); 12143 if (actionsIterator != null) { 12144 getIntentListSubset( 12145 intentListCopy, new ActionIterGenerator(), actionsIterator); 12146 if (intentListCopy.size() == 0) { 12147 // no more intents to match; we're not equivalent 12148 if (DEBUG_FILTERS) { 12149 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12150 + " package: " + applicationInfo.packageName 12151 + " activity: " + intent.activity.className 12152 + " origPrio: " + intent.getPriority()); 12153 } 12154 intent.setPriority(0); 12155 return; 12156 } 12157 } 12158 12159 // find matching category subsets 12160 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12161 if (categoriesIterator != null) { 12162 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12163 categoriesIterator); 12164 if (intentListCopy.size() == 0) { 12165 // no more intents to match; we're not equivalent 12166 if (DEBUG_FILTERS) { 12167 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12168 + " package: " + applicationInfo.packageName 12169 + " activity: " + intent.activity.className 12170 + " origPrio: " + intent.getPriority()); 12171 } 12172 intent.setPriority(0); 12173 return; 12174 } 12175 } 12176 12177 // find matching schemes subsets 12178 final Iterator<String> schemesIterator = intent.schemesIterator(); 12179 if (schemesIterator != null) { 12180 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12181 schemesIterator); 12182 if (intentListCopy.size() == 0) { 12183 // no more intents to match; we're not equivalent 12184 if (DEBUG_FILTERS) { 12185 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12186 + " package: " + applicationInfo.packageName 12187 + " activity: " + intent.activity.className 12188 + " origPrio: " + intent.getPriority()); 12189 } 12190 intent.setPriority(0); 12191 return; 12192 } 12193 } 12194 12195 // find matching authorities subsets 12196 final Iterator<IntentFilter.AuthorityEntry> 12197 authoritiesIterator = intent.authoritiesIterator(); 12198 if (authoritiesIterator != null) { 12199 getIntentListSubset(intentListCopy, 12200 new AuthoritiesIterGenerator(), 12201 authoritiesIterator); 12202 if (intentListCopy.size() == 0) { 12203 // no more intents to match; we're not equivalent 12204 if (DEBUG_FILTERS) { 12205 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12206 + " package: " + applicationInfo.packageName 12207 + " activity: " + intent.activity.className 12208 + " origPrio: " + intent.getPriority()); 12209 } 12210 intent.setPriority(0); 12211 return; 12212 } 12213 } 12214 12215 // we found matching filter(s); app gets the max priority of all intents 12216 int cappedPriority = 0; 12217 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12218 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12219 } 12220 if (intent.getPriority() > cappedPriority) { 12221 if (DEBUG_FILTERS) { 12222 Slog.i(TAG, "Found matching filter(s);" 12223 + " cap priority to " + cappedPriority + ";" 12224 + " package: " + applicationInfo.packageName 12225 + " activity: " + intent.activity.className 12226 + " origPrio: " + intent.getPriority()); 12227 } 12228 intent.setPriority(cappedPriority); 12229 return; 12230 } 12231 // all this for nothing; the requested priority was <= what was on the system 12232 } 12233 12234 public final void addActivity(PackageParser.Activity a, String type) { 12235 mActivities.put(a.getComponentName(), a); 12236 if (DEBUG_SHOW_INFO) 12237 Log.v( 12238 TAG, " " + type + " " + 12239 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12240 if (DEBUG_SHOW_INFO) 12241 Log.v(TAG, " Class=" + a.info.name); 12242 final int NI = a.intents.size(); 12243 for (int j=0; j<NI; j++) { 12244 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12245 if ("activity".equals(type)) { 12246 final PackageSetting ps = 12247 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12248 final List<PackageParser.Activity> systemActivities = 12249 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12250 adjustPriority(systemActivities, intent); 12251 } 12252 if (DEBUG_SHOW_INFO) { 12253 Log.v(TAG, " IntentFilter:"); 12254 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12255 } 12256 if (!intent.debugCheck()) { 12257 Log.w(TAG, "==> For Activity " + a.info.name); 12258 } 12259 addFilter(intent); 12260 } 12261 } 12262 12263 public final void removeActivity(PackageParser.Activity a, String type) { 12264 mActivities.remove(a.getComponentName()); 12265 if (DEBUG_SHOW_INFO) { 12266 Log.v(TAG, " " + type + " " 12267 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12268 : a.info.name) + ":"); 12269 Log.v(TAG, " Class=" + a.info.name); 12270 } 12271 final int NI = a.intents.size(); 12272 for (int j=0; j<NI; j++) { 12273 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12274 if (DEBUG_SHOW_INFO) { 12275 Log.v(TAG, " IntentFilter:"); 12276 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12277 } 12278 removeFilter(intent); 12279 } 12280 } 12281 12282 @Override 12283 protected boolean allowFilterResult( 12284 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12285 ActivityInfo filterAi = filter.activity.info; 12286 for (int i=dest.size()-1; i>=0; i--) { 12287 ActivityInfo destAi = dest.get(i).activityInfo; 12288 if (destAi.name == filterAi.name 12289 && destAi.packageName == filterAi.packageName) { 12290 return false; 12291 } 12292 } 12293 return true; 12294 } 12295 12296 @Override 12297 protected ActivityIntentInfo[] newArray(int size) { 12298 return new ActivityIntentInfo[size]; 12299 } 12300 12301 @Override 12302 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12303 if (!sUserManager.exists(userId)) return true; 12304 PackageParser.Package p = filter.activity.owner; 12305 if (p != null) { 12306 PackageSetting ps = (PackageSetting)p.mExtras; 12307 if (ps != null) { 12308 // System apps are never considered stopped for purposes of 12309 // filtering, because there may be no way for the user to 12310 // actually re-launch them. 12311 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12312 && ps.getStopped(userId); 12313 } 12314 } 12315 return false; 12316 } 12317 12318 @Override 12319 protected boolean isPackageForFilter(String packageName, 12320 PackageParser.ActivityIntentInfo info) { 12321 return packageName.equals(info.activity.owner.packageName); 12322 } 12323 12324 @Override 12325 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12326 int match, int userId) { 12327 if (!sUserManager.exists(userId)) return null; 12328 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12329 return null; 12330 } 12331 final PackageParser.Activity activity = info.activity; 12332 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12333 if (ps == null) { 12334 return null; 12335 } 12336 final PackageUserState userState = ps.readUserState(userId); 12337 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12338 userState, userId); 12339 if (ai == null) { 12340 return null; 12341 } 12342 final boolean matchVisibleToInstantApp = 12343 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12344 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12345 // throw out filters that aren't visible to ephemeral apps 12346 if (matchVisibleToInstantApp 12347 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12348 return null; 12349 } 12350 // throw out ephemeral filters if we're not explicitly requesting them 12351 if (!isInstantApp && userState.instantApp) { 12352 return null; 12353 } 12354 final ResolveInfo res = new ResolveInfo(); 12355 res.activityInfo = ai; 12356 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12357 res.filter = info; 12358 } 12359 if (info != null) { 12360 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12361 } 12362 res.priority = info.getPriority(); 12363 res.preferredOrder = activity.owner.mPreferredOrder; 12364 //System.out.println("Result: " + res.activityInfo.className + 12365 // " = " + res.priority); 12366 res.match = match; 12367 res.isDefault = info.hasDefault; 12368 res.labelRes = info.labelRes; 12369 res.nonLocalizedLabel = info.nonLocalizedLabel; 12370 if (userNeedsBadging(userId)) { 12371 res.noResourceId = true; 12372 } else { 12373 res.icon = info.icon; 12374 } 12375 res.iconResourceId = info.icon; 12376 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12377 return res; 12378 } 12379 12380 @Override 12381 protected void sortResults(List<ResolveInfo> results) { 12382 Collections.sort(results, mResolvePrioritySorter); 12383 } 12384 12385 @Override 12386 protected void dumpFilter(PrintWriter out, String prefix, 12387 PackageParser.ActivityIntentInfo filter) { 12388 out.print(prefix); out.print( 12389 Integer.toHexString(System.identityHashCode(filter.activity))); 12390 out.print(' '); 12391 filter.activity.printComponentShortName(out); 12392 out.print(" filter "); 12393 out.println(Integer.toHexString(System.identityHashCode(filter))); 12394 } 12395 12396 @Override 12397 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12398 return filter.activity; 12399 } 12400 12401 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12402 PackageParser.Activity activity = (PackageParser.Activity)label; 12403 out.print(prefix); out.print( 12404 Integer.toHexString(System.identityHashCode(activity))); 12405 out.print(' '); 12406 activity.printComponentShortName(out); 12407 if (count > 1) { 12408 out.print(" ("); out.print(count); out.print(" filters)"); 12409 } 12410 out.println(); 12411 } 12412 12413 // Keys are String (activity class name), values are Activity. 12414 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12415 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12416 private int mFlags; 12417 } 12418 12419 private final class ServiceIntentResolver 12420 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12421 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12422 boolean defaultOnly, int userId) { 12423 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12424 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12425 } 12426 12427 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12428 int userId) { 12429 if (!sUserManager.exists(userId)) return null; 12430 mFlags = flags; 12431 return super.queryIntent(intent, resolvedType, 12432 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12433 userId); 12434 } 12435 12436 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12437 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12438 if (!sUserManager.exists(userId)) return null; 12439 if (packageServices == null) { 12440 return null; 12441 } 12442 mFlags = flags; 12443 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12444 final int N = packageServices.size(); 12445 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12446 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12447 12448 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12449 for (int i = 0; i < N; ++i) { 12450 intentFilters = packageServices.get(i).intents; 12451 if (intentFilters != null && intentFilters.size() > 0) { 12452 PackageParser.ServiceIntentInfo[] array = 12453 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12454 intentFilters.toArray(array); 12455 listCut.add(array); 12456 } 12457 } 12458 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12459 } 12460 12461 public final void addService(PackageParser.Service s) { 12462 mServices.put(s.getComponentName(), s); 12463 if (DEBUG_SHOW_INFO) { 12464 Log.v(TAG, " " 12465 + (s.info.nonLocalizedLabel != null 12466 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12467 Log.v(TAG, " Class=" + s.info.name); 12468 } 12469 final int NI = s.intents.size(); 12470 int j; 12471 for (j=0; j<NI; j++) { 12472 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12473 if (DEBUG_SHOW_INFO) { 12474 Log.v(TAG, " IntentFilter:"); 12475 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12476 } 12477 if (!intent.debugCheck()) { 12478 Log.w(TAG, "==> For Service " + s.info.name); 12479 } 12480 addFilter(intent); 12481 } 12482 } 12483 12484 public final void removeService(PackageParser.Service s) { 12485 mServices.remove(s.getComponentName()); 12486 if (DEBUG_SHOW_INFO) { 12487 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12488 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12489 Log.v(TAG, " Class=" + s.info.name); 12490 } 12491 final int NI = s.intents.size(); 12492 int j; 12493 for (j=0; j<NI; j++) { 12494 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12495 if (DEBUG_SHOW_INFO) { 12496 Log.v(TAG, " IntentFilter:"); 12497 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12498 } 12499 removeFilter(intent); 12500 } 12501 } 12502 12503 @Override 12504 protected boolean allowFilterResult( 12505 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12506 ServiceInfo filterSi = filter.service.info; 12507 for (int i=dest.size()-1; i>=0; i--) { 12508 ServiceInfo destAi = dest.get(i).serviceInfo; 12509 if (destAi.name == filterSi.name 12510 && destAi.packageName == filterSi.packageName) { 12511 return false; 12512 } 12513 } 12514 return true; 12515 } 12516 12517 @Override 12518 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12519 return new PackageParser.ServiceIntentInfo[size]; 12520 } 12521 12522 @Override 12523 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12524 if (!sUserManager.exists(userId)) return true; 12525 PackageParser.Package p = filter.service.owner; 12526 if (p != null) { 12527 PackageSetting ps = (PackageSetting)p.mExtras; 12528 if (ps != null) { 12529 // System apps are never considered stopped for purposes of 12530 // filtering, because there may be no way for the user to 12531 // actually re-launch them. 12532 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12533 && ps.getStopped(userId); 12534 } 12535 } 12536 return false; 12537 } 12538 12539 @Override 12540 protected boolean isPackageForFilter(String packageName, 12541 PackageParser.ServiceIntentInfo info) { 12542 return packageName.equals(info.service.owner.packageName); 12543 } 12544 12545 @Override 12546 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12547 int match, int userId) { 12548 if (!sUserManager.exists(userId)) return null; 12549 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12550 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12551 return null; 12552 } 12553 final PackageParser.Service service = info.service; 12554 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12555 if (ps == null) { 12556 return null; 12557 } 12558 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12559 ps.readUserState(userId), userId); 12560 if (si == null) { 12561 return null; 12562 } 12563 final ResolveInfo res = new ResolveInfo(); 12564 res.serviceInfo = si; 12565 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12566 res.filter = filter; 12567 } 12568 res.priority = info.getPriority(); 12569 res.preferredOrder = service.owner.mPreferredOrder; 12570 res.match = match; 12571 res.isDefault = info.hasDefault; 12572 res.labelRes = info.labelRes; 12573 res.nonLocalizedLabel = info.nonLocalizedLabel; 12574 res.icon = info.icon; 12575 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12576 return res; 12577 } 12578 12579 @Override 12580 protected void sortResults(List<ResolveInfo> results) { 12581 Collections.sort(results, mResolvePrioritySorter); 12582 } 12583 12584 @Override 12585 protected void dumpFilter(PrintWriter out, String prefix, 12586 PackageParser.ServiceIntentInfo filter) { 12587 out.print(prefix); out.print( 12588 Integer.toHexString(System.identityHashCode(filter.service))); 12589 out.print(' '); 12590 filter.service.printComponentShortName(out); 12591 out.print(" filter "); 12592 out.println(Integer.toHexString(System.identityHashCode(filter))); 12593 } 12594 12595 @Override 12596 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12597 return filter.service; 12598 } 12599 12600 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12601 PackageParser.Service service = (PackageParser.Service)label; 12602 out.print(prefix); out.print( 12603 Integer.toHexString(System.identityHashCode(service))); 12604 out.print(' '); 12605 service.printComponentShortName(out); 12606 if (count > 1) { 12607 out.print(" ("); out.print(count); out.print(" filters)"); 12608 } 12609 out.println(); 12610 } 12611 12612// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12613// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12614// final List<ResolveInfo> retList = Lists.newArrayList(); 12615// while (i.hasNext()) { 12616// final ResolveInfo resolveInfo = (ResolveInfo) i; 12617// if (isEnabledLP(resolveInfo.serviceInfo)) { 12618// retList.add(resolveInfo); 12619// } 12620// } 12621// return retList; 12622// } 12623 12624 // Keys are String (activity class name), values are Activity. 12625 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12626 = new ArrayMap<ComponentName, PackageParser.Service>(); 12627 private int mFlags; 12628 } 12629 12630 private final class ProviderIntentResolver 12631 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12632 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12633 boolean defaultOnly, int userId) { 12634 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12635 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12636 } 12637 12638 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12639 int userId) { 12640 if (!sUserManager.exists(userId)) 12641 return null; 12642 mFlags = flags; 12643 return super.queryIntent(intent, resolvedType, 12644 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12645 userId); 12646 } 12647 12648 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12649 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12650 if (!sUserManager.exists(userId)) 12651 return null; 12652 if (packageProviders == null) { 12653 return null; 12654 } 12655 mFlags = flags; 12656 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12657 final int N = packageProviders.size(); 12658 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12659 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12660 12661 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12662 for (int i = 0; i < N; ++i) { 12663 intentFilters = packageProviders.get(i).intents; 12664 if (intentFilters != null && intentFilters.size() > 0) { 12665 PackageParser.ProviderIntentInfo[] array = 12666 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12667 intentFilters.toArray(array); 12668 listCut.add(array); 12669 } 12670 } 12671 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12672 } 12673 12674 public final void addProvider(PackageParser.Provider p) { 12675 if (mProviders.containsKey(p.getComponentName())) { 12676 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12677 return; 12678 } 12679 12680 mProviders.put(p.getComponentName(), p); 12681 if (DEBUG_SHOW_INFO) { 12682 Log.v(TAG, " " 12683 + (p.info.nonLocalizedLabel != null 12684 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12685 Log.v(TAG, " Class=" + p.info.name); 12686 } 12687 final int NI = p.intents.size(); 12688 int j; 12689 for (j = 0; j < NI; j++) { 12690 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12691 if (DEBUG_SHOW_INFO) { 12692 Log.v(TAG, " IntentFilter:"); 12693 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12694 } 12695 if (!intent.debugCheck()) { 12696 Log.w(TAG, "==> For Provider " + p.info.name); 12697 } 12698 addFilter(intent); 12699 } 12700 } 12701 12702 public final void removeProvider(PackageParser.Provider p) { 12703 mProviders.remove(p.getComponentName()); 12704 if (DEBUG_SHOW_INFO) { 12705 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12706 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12707 Log.v(TAG, " Class=" + p.info.name); 12708 } 12709 final int NI = p.intents.size(); 12710 int j; 12711 for (j = 0; j < NI; j++) { 12712 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12713 if (DEBUG_SHOW_INFO) { 12714 Log.v(TAG, " IntentFilter:"); 12715 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12716 } 12717 removeFilter(intent); 12718 } 12719 } 12720 12721 @Override 12722 protected boolean allowFilterResult( 12723 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12724 ProviderInfo filterPi = filter.provider.info; 12725 for (int i = dest.size() - 1; i >= 0; i--) { 12726 ProviderInfo destPi = dest.get(i).providerInfo; 12727 if (destPi.name == filterPi.name 12728 && destPi.packageName == filterPi.packageName) { 12729 return false; 12730 } 12731 } 12732 return true; 12733 } 12734 12735 @Override 12736 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12737 return new PackageParser.ProviderIntentInfo[size]; 12738 } 12739 12740 @Override 12741 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12742 if (!sUserManager.exists(userId)) 12743 return true; 12744 PackageParser.Package p = filter.provider.owner; 12745 if (p != null) { 12746 PackageSetting ps = (PackageSetting) p.mExtras; 12747 if (ps != null) { 12748 // System apps are never considered stopped for purposes of 12749 // filtering, because there may be no way for the user to 12750 // actually re-launch them. 12751 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12752 && ps.getStopped(userId); 12753 } 12754 } 12755 return false; 12756 } 12757 12758 @Override 12759 protected boolean isPackageForFilter(String packageName, 12760 PackageParser.ProviderIntentInfo info) { 12761 return packageName.equals(info.provider.owner.packageName); 12762 } 12763 12764 @Override 12765 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12766 int match, int userId) { 12767 if (!sUserManager.exists(userId)) 12768 return null; 12769 final PackageParser.ProviderIntentInfo info = filter; 12770 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12771 return null; 12772 } 12773 final PackageParser.Provider provider = info.provider; 12774 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12775 if (ps == null) { 12776 return null; 12777 } 12778 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12779 ps.readUserState(userId), userId); 12780 if (pi == null) { 12781 return null; 12782 } 12783 final ResolveInfo res = new ResolveInfo(); 12784 res.providerInfo = pi; 12785 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12786 res.filter = filter; 12787 } 12788 res.priority = info.getPriority(); 12789 res.preferredOrder = provider.owner.mPreferredOrder; 12790 res.match = match; 12791 res.isDefault = info.hasDefault; 12792 res.labelRes = info.labelRes; 12793 res.nonLocalizedLabel = info.nonLocalizedLabel; 12794 res.icon = info.icon; 12795 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12796 return res; 12797 } 12798 12799 @Override 12800 protected void sortResults(List<ResolveInfo> results) { 12801 Collections.sort(results, mResolvePrioritySorter); 12802 } 12803 12804 @Override 12805 protected void dumpFilter(PrintWriter out, String prefix, 12806 PackageParser.ProviderIntentInfo filter) { 12807 out.print(prefix); 12808 out.print( 12809 Integer.toHexString(System.identityHashCode(filter.provider))); 12810 out.print(' '); 12811 filter.provider.printComponentShortName(out); 12812 out.print(" filter "); 12813 out.println(Integer.toHexString(System.identityHashCode(filter))); 12814 } 12815 12816 @Override 12817 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12818 return filter.provider; 12819 } 12820 12821 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12822 PackageParser.Provider provider = (PackageParser.Provider)label; 12823 out.print(prefix); out.print( 12824 Integer.toHexString(System.identityHashCode(provider))); 12825 out.print(' '); 12826 provider.printComponentShortName(out); 12827 if (count > 1) { 12828 out.print(" ("); out.print(count); out.print(" filters)"); 12829 } 12830 out.println(); 12831 } 12832 12833 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12834 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12835 private int mFlags; 12836 } 12837 12838 static final class EphemeralIntentResolver 12839 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12840 /** 12841 * The result that has the highest defined order. Ordering applies on a 12842 * per-package basis. Mapping is from package name to Pair of order and 12843 * EphemeralResolveInfo. 12844 * <p> 12845 * NOTE: This is implemented as a field variable for convenience and efficiency. 12846 * By having a field variable, we're able to track filter ordering as soon as 12847 * a non-zero order is defined. Otherwise, multiple loops across the result set 12848 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12849 * this needs to be contained entirely within {@link #filterResults()}. 12850 */ 12851 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12852 12853 @Override 12854 protected AuxiliaryResolveInfo[] newArray(int size) { 12855 return new AuxiliaryResolveInfo[size]; 12856 } 12857 12858 @Override 12859 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12860 return true; 12861 } 12862 12863 @Override 12864 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12865 int userId) { 12866 if (!sUserManager.exists(userId)) { 12867 return null; 12868 } 12869 final String packageName = responseObj.resolveInfo.getPackageName(); 12870 final Integer order = responseObj.getOrder(); 12871 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12872 mOrderResult.get(packageName); 12873 // ordering is enabled and this item's order isn't high enough 12874 if (lastOrderResult != null && lastOrderResult.first >= order) { 12875 return null; 12876 } 12877 final EphemeralResolveInfo res = responseObj.resolveInfo; 12878 if (order > 0) { 12879 // non-zero order, enable ordering 12880 mOrderResult.put(packageName, new Pair<>(order, res)); 12881 } 12882 return responseObj; 12883 } 12884 12885 @Override 12886 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12887 // only do work if ordering is enabled [most of the time it won't be] 12888 if (mOrderResult.size() == 0) { 12889 return; 12890 } 12891 int resultSize = results.size(); 12892 for (int i = 0; i < resultSize; i++) { 12893 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12894 final String packageName = info.getPackageName(); 12895 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12896 if (savedInfo == null) { 12897 // package doesn't having ordering 12898 continue; 12899 } 12900 if (savedInfo.second == info) { 12901 // circled back to the highest ordered item; remove from order list 12902 mOrderResult.remove(savedInfo); 12903 if (mOrderResult.size() == 0) { 12904 // no more ordered items 12905 break; 12906 } 12907 continue; 12908 } 12909 // item has a worse order, remove it from the result list 12910 results.remove(i); 12911 resultSize--; 12912 i--; 12913 } 12914 } 12915 } 12916 12917 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12918 new Comparator<ResolveInfo>() { 12919 public int compare(ResolveInfo r1, ResolveInfo r2) { 12920 int v1 = r1.priority; 12921 int v2 = r2.priority; 12922 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12923 if (v1 != v2) { 12924 return (v1 > v2) ? -1 : 1; 12925 } 12926 v1 = r1.preferredOrder; 12927 v2 = r2.preferredOrder; 12928 if (v1 != v2) { 12929 return (v1 > v2) ? -1 : 1; 12930 } 12931 if (r1.isDefault != r2.isDefault) { 12932 return r1.isDefault ? -1 : 1; 12933 } 12934 v1 = r1.match; 12935 v2 = r2.match; 12936 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12937 if (v1 != v2) { 12938 return (v1 > v2) ? -1 : 1; 12939 } 12940 if (r1.system != r2.system) { 12941 return r1.system ? -1 : 1; 12942 } 12943 if (r1.activityInfo != null) { 12944 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12945 } 12946 if (r1.serviceInfo != null) { 12947 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12948 } 12949 if (r1.providerInfo != null) { 12950 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12951 } 12952 return 0; 12953 } 12954 }; 12955 12956 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12957 new Comparator<ProviderInfo>() { 12958 public int compare(ProviderInfo p1, ProviderInfo p2) { 12959 final int v1 = p1.initOrder; 12960 final int v2 = p2.initOrder; 12961 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12962 } 12963 }; 12964 12965 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12966 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12967 final int[] userIds) { 12968 mHandler.post(new Runnable() { 12969 @Override 12970 public void run() { 12971 try { 12972 final IActivityManager am = ActivityManager.getService(); 12973 if (am == null) return; 12974 final int[] resolvedUserIds; 12975 if (userIds == null) { 12976 resolvedUserIds = am.getRunningUserIds(); 12977 } else { 12978 resolvedUserIds = userIds; 12979 } 12980 for (int id : resolvedUserIds) { 12981 final Intent intent = new Intent(action, 12982 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12983 if (extras != null) { 12984 intent.putExtras(extras); 12985 } 12986 if (targetPkg != null) { 12987 intent.setPackage(targetPkg); 12988 } 12989 // Modify the UID when posting to other users 12990 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12991 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12992 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12993 intent.putExtra(Intent.EXTRA_UID, uid); 12994 } 12995 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12996 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12997 if (DEBUG_BROADCASTS) { 12998 RuntimeException here = new RuntimeException("here"); 12999 here.fillInStackTrace(); 13000 Slog.d(TAG, "Sending to user " + id + ": " 13001 + intent.toShortString(false, true, false, false) 13002 + " " + intent.getExtras(), here); 13003 } 13004 am.broadcastIntent(null, intent, null, finishedReceiver, 13005 0, null, null, null, android.app.AppOpsManager.OP_NONE, 13006 null, finishedReceiver != null, false, id); 13007 } 13008 } catch (RemoteException ex) { 13009 } 13010 } 13011 }); 13012 } 13013 13014 /** 13015 * Check if the external storage media is available. This is true if there 13016 * is a mounted external storage medium or if the external storage is 13017 * emulated. 13018 */ 13019 private boolean isExternalMediaAvailable() { 13020 return mMediaMounted || Environment.isExternalStorageEmulated(); 13021 } 13022 13023 @Override 13024 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13025 // writer 13026 synchronized (mPackages) { 13027 if (!isExternalMediaAvailable()) { 13028 // If the external storage is no longer mounted at this point, 13029 // the caller may not have been able to delete all of this 13030 // packages files and can not delete any more. Bail. 13031 return null; 13032 } 13033 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13034 if (lastPackage != null) { 13035 pkgs.remove(lastPackage); 13036 } 13037 if (pkgs.size() > 0) { 13038 return pkgs.get(0); 13039 } 13040 } 13041 return null; 13042 } 13043 13044 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13045 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13046 userId, andCode ? 1 : 0, packageName); 13047 if (mSystemReady) { 13048 msg.sendToTarget(); 13049 } else { 13050 if (mPostSystemReadyMessages == null) { 13051 mPostSystemReadyMessages = new ArrayList<>(); 13052 } 13053 mPostSystemReadyMessages.add(msg); 13054 } 13055 } 13056 13057 void startCleaningPackages() { 13058 // reader 13059 if (!isExternalMediaAvailable()) { 13060 return; 13061 } 13062 synchronized (mPackages) { 13063 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13064 return; 13065 } 13066 } 13067 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13068 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13069 IActivityManager am = ActivityManager.getService(); 13070 if (am != null) { 13071 try { 13072 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 13073 UserHandle.USER_SYSTEM); 13074 } catch (RemoteException e) { 13075 } 13076 } 13077 } 13078 13079 @Override 13080 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13081 int installFlags, String installerPackageName, int userId) { 13082 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13083 13084 final int callingUid = Binder.getCallingUid(); 13085 enforceCrossUserPermission(callingUid, userId, 13086 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13087 13088 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13089 try { 13090 if (observer != null) { 13091 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13092 } 13093 } catch (RemoteException re) { 13094 } 13095 return; 13096 } 13097 13098 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13099 installFlags |= PackageManager.INSTALL_FROM_ADB; 13100 13101 } else { 13102 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13103 // about installerPackageName. 13104 13105 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13106 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13107 } 13108 13109 UserHandle user; 13110 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13111 user = UserHandle.ALL; 13112 } else { 13113 user = new UserHandle(userId); 13114 } 13115 13116 // Only system components can circumvent runtime permissions when installing. 13117 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13118 && mContext.checkCallingOrSelfPermission(Manifest.permission 13119 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13120 throw new SecurityException("You need the " 13121 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13122 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13123 } 13124 13125 final File originFile = new File(originPath); 13126 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13127 13128 final Message msg = mHandler.obtainMessage(INIT_COPY); 13129 final VerificationInfo verificationInfo = new VerificationInfo( 13130 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13131 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13132 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13133 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13134 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13135 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13136 msg.obj = params; 13137 13138 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13139 System.identityHashCode(msg.obj)); 13140 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13141 System.identityHashCode(msg.obj)); 13142 13143 mHandler.sendMessage(msg); 13144 } 13145 13146 13147 /** 13148 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13149 * it is acting on behalf on an enterprise or the user). 13150 * 13151 * Note that the ordering of the conditionals in this method is important. The checks we perform 13152 * are as follows, in this order: 13153 * 13154 * 1) If the install is being performed by a system app, we can trust the app to have set the 13155 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13156 * what it is. 13157 * 2) If the install is being performed by a device or profile owner app, the install reason 13158 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13159 * set the install reason correctly. If the app targets an older SDK version where install 13160 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13161 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13162 * 3) In all other cases, the install is being performed by a regular app that is neither part 13163 * of the system nor a device or profile owner. We have no reason to believe that this app is 13164 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13165 * set to enterprise policy and if so, change it to unknown instead. 13166 */ 13167 private int fixUpInstallReason(String installerPackageName, int installerUid, 13168 int installReason) { 13169 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13170 == PERMISSION_GRANTED) { 13171 // If the install is being performed by a system app, we trust that app to have set the 13172 // install reason correctly. 13173 return installReason; 13174 } 13175 13176 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13177 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13178 if (dpm != null) { 13179 ComponentName owner = null; 13180 try { 13181 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13182 if (owner == null) { 13183 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13184 } 13185 } catch (RemoteException e) { 13186 } 13187 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13188 // If the install is being performed by a device or profile owner, the install 13189 // reason should be enterprise policy. 13190 return PackageManager.INSTALL_REASON_POLICY; 13191 } 13192 } 13193 13194 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13195 // If the install is being performed by a regular app (i.e. neither system app nor 13196 // device or profile owner), we have no reason to believe that the app is acting on 13197 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13198 // change it to unknown instead. 13199 return PackageManager.INSTALL_REASON_UNKNOWN; 13200 } 13201 13202 // If the install is being performed by a regular app and the install reason was set to any 13203 // value but enterprise policy, leave the install reason unchanged. 13204 return installReason; 13205 } 13206 13207 void installStage(String packageName, File stagedDir, String stagedCid, 13208 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13209 String installerPackageName, int installerUid, UserHandle user, 13210 Certificate[][] certificates) { 13211 if (DEBUG_EPHEMERAL) { 13212 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13213 Slog.d(TAG, "Ephemeral install of " + packageName); 13214 } 13215 } 13216 final VerificationInfo verificationInfo = new VerificationInfo( 13217 sessionParams.originatingUri, sessionParams.referrerUri, 13218 sessionParams.originatingUid, installerUid); 13219 13220 final OriginInfo origin; 13221 if (stagedDir != null) { 13222 origin = OriginInfo.fromStagedFile(stagedDir); 13223 } else { 13224 origin = OriginInfo.fromStagedContainer(stagedCid); 13225 } 13226 13227 final Message msg = mHandler.obtainMessage(INIT_COPY); 13228 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13229 sessionParams.installReason); 13230 final InstallParams params = new InstallParams(origin, null, observer, 13231 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13232 verificationInfo, user, sessionParams.abiOverride, 13233 sessionParams.grantedRuntimePermissions, certificates, installReason); 13234 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13235 msg.obj = params; 13236 13237 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13238 System.identityHashCode(msg.obj)); 13239 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13240 System.identityHashCode(msg.obj)); 13241 13242 mHandler.sendMessage(msg); 13243 } 13244 13245 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13246 int userId) { 13247 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13248 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13249 } 13250 13251 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13252 int appId, int... userIds) { 13253 if (ArrayUtils.isEmpty(userIds)) { 13254 return; 13255 } 13256 Bundle extras = new Bundle(1); 13257 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13258 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13259 13260 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13261 packageName, extras, 0, null, null, userIds); 13262 if (isSystem) { 13263 mHandler.post(() -> { 13264 for (int userId : userIds) { 13265 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13266 } 13267 } 13268 ); 13269 } 13270 } 13271 13272 /** 13273 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13274 * automatically without needing an explicit launch. 13275 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13276 */ 13277 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13278 // If user is not running, the app didn't miss any broadcast 13279 if (!mUserManagerInternal.isUserRunning(userId)) { 13280 return; 13281 } 13282 final IActivityManager am = ActivityManager.getService(); 13283 try { 13284 // Deliver LOCKED_BOOT_COMPLETED first 13285 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13286 .setPackage(packageName); 13287 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13288 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13289 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13290 13291 // Deliver BOOT_COMPLETED only if user is unlocked 13292 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13293 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13294 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13295 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13296 } 13297 } catch (RemoteException e) { 13298 throw e.rethrowFromSystemServer(); 13299 } 13300 } 13301 13302 @Override 13303 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13304 int userId) { 13305 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13306 PackageSetting pkgSetting; 13307 final int uid = Binder.getCallingUid(); 13308 enforceCrossUserPermission(uid, userId, 13309 true /* requireFullPermission */, true /* checkShell */, 13310 "setApplicationHiddenSetting for user " + userId); 13311 13312 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13313 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13314 return false; 13315 } 13316 13317 long callingId = Binder.clearCallingIdentity(); 13318 try { 13319 boolean sendAdded = false; 13320 boolean sendRemoved = false; 13321 // writer 13322 synchronized (mPackages) { 13323 pkgSetting = mSettings.mPackages.get(packageName); 13324 if (pkgSetting == null) { 13325 return false; 13326 } 13327 // Do not allow "android" is being disabled 13328 if ("android".equals(packageName)) { 13329 Slog.w(TAG, "Cannot hide package: android"); 13330 return false; 13331 } 13332 // Cannot hide static shared libs as they are considered 13333 // a part of the using app (emulating static linking). Also 13334 // static libs are installed always on internal storage. 13335 PackageParser.Package pkg = mPackages.get(packageName); 13336 if (pkg != null && pkg.staticSharedLibName != null) { 13337 Slog.w(TAG, "Cannot hide package: " + packageName 13338 + " providing static shared library: " 13339 + pkg.staticSharedLibName); 13340 return false; 13341 } 13342 // Only allow protected packages to hide themselves. 13343 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13344 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13345 Slog.w(TAG, "Not hiding protected package: " + packageName); 13346 return false; 13347 } 13348 13349 if (pkgSetting.getHidden(userId) != hidden) { 13350 pkgSetting.setHidden(hidden, userId); 13351 mSettings.writePackageRestrictionsLPr(userId); 13352 if (hidden) { 13353 sendRemoved = true; 13354 } else { 13355 sendAdded = true; 13356 } 13357 } 13358 } 13359 if (sendAdded) { 13360 sendPackageAddedForUser(packageName, pkgSetting, userId); 13361 return true; 13362 } 13363 if (sendRemoved) { 13364 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13365 "hiding pkg"); 13366 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13367 return true; 13368 } 13369 } finally { 13370 Binder.restoreCallingIdentity(callingId); 13371 } 13372 return false; 13373 } 13374 13375 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13376 int userId) { 13377 final PackageRemovedInfo info = new PackageRemovedInfo(); 13378 info.removedPackage = packageName; 13379 info.removedUsers = new int[] {userId}; 13380 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13381 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13382 } 13383 13384 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13385 if (pkgList.length > 0) { 13386 Bundle extras = new Bundle(1); 13387 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13388 13389 sendPackageBroadcast( 13390 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13391 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13392 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13393 new int[] {userId}); 13394 } 13395 } 13396 13397 /** 13398 * Returns true if application is not found or there was an error. Otherwise it returns 13399 * the hidden state of the package for the given user. 13400 */ 13401 @Override 13402 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13403 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13404 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13405 true /* requireFullPermission */, false /* checkShell */, 13406 "getApplicationHidden for user " + userId); 13407 PackageSetting pkgSetting; 13408 long callingId = Binder.clearCallingIdentity(); 13409 try { 13410 // writer 13411 synchronized (mPackages) { 13412 pkgSetting = mSettings.mPackages.get(packageName); 13413 if (pkgSetting == null) { 13414 return true; 13415 } 13416 return pkgSetting.getHidden(userId); 13417 } 13418 } finally { 13419 Binder.restoreCallingIdentity(callingId); 13420 } 13421 } 13422 13423 /** 13424 * @hide 13425 */ 13426 @Override 13427 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13428 int installReason) { 13429 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13430 null); 13431 PackageSetting pkgSetting; 13432 final int uid = Binder.getCallingUid(); 13433 enforceCrossUserPermission(uid, userId, 13434 true /* requireFullPermission */, true /* checkShell */, 13435 "installExistingPackage for user " + userId); 13436 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13437 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13438 } 13439 13440 long callingId = Binder.clearCallingIdentity(); 13441 try { 13442 boolean installed = false; 13443 final boolean instantApp = 13444 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13445 final boolean fullApp = 13446 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13447 13448 // writer 13449 synchronized (mPackages) { 13450 pkgSetting = mSettings.mPackages.get(packageName); 13451 if (pkgSetting == null) { 13452 return PackageManager.INSTALL_FAILED_INVALID_URI; 13453 } 13454 if (!pkgSetting.getInstalled(userId)) { 13455 pkgSetting.setInstalled(true, userId); 13456 pkgSetting.setHidden(false, userId); 13457 pkgSetting.setInstallReason(installReason, userId); 13458 mSettings.writePackageRestrictionsLPr(userId); 13459 mSettings.writeKernelMappingLPr(pkgSetting); 13460 installed = true; 13461 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13462 // upgrade app from instant to full; we don't allow app downgrade 13463 installed = true; 13464 } 13465 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13466 } 13467 13468 if (installed) { 13469 if (pkgSetting.pkg != null) { 13470 synchronized (mInstallLock) { 13471 // We don't need to freeze for a brand new install 13472 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13473 } 13474 } 13475 sendPackageAddedForUser(packageName, pkgSetting, userId); 13476 synchronized (mPackages) { 13477 updateSequenceNumberLP(packageName, new int[]{ userId }); 13478 } 13479 } 13480 } finally { 13481 Binder.restoreCallingIdentity(callingId); 13482 } 13483 13484 return PackageManager.INSTALL_SUCCEEDED; 13485 } 13486 13487 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13488 boolean instantApp, boolean fullApp) { 13489 // no state specified; do nothing 13490 if (!instantApp && !fullApp) { 13491 return; 13492 } 13493 if (userId != UserHandle.USER_ALL) { 13494 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13495 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13496 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13497 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13498 } 13499 } else { 13500 for (int currentUserId : sUserManager.getUserIds()) { 13501 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13502 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13503 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13504 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13505 } 13506 } 13507 } 13508 } 13509 13510 boolean isUserRestricted(int userId, String restrictionKey) { 13511 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13512 if (restrictions.getBoolean(restrictionKey, false)) { 13513 Log.w(TAG, "User is restricted: " + restrictionKey); 13514 return true; 13515 } 13516 return false; 13517 } 13518 13519 @Override 13520 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13521 int userId) { 13522 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13523 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13524 true /* requireFullPermission */, true /* checkShell */, 13525 "setPackagesSuspended for user " + userId); 13526 13527 if (ArrayUtils.isEmpty(packageNames)) { 13528 return packageNames; 13529 } 13530 13531 // List of package names for whom the suspended state has changed. 13532 List<String> changedPackages = new ArrayList<>(packageNames.length); 13533 // List of package names for whom the suspended state is not set as requested in this 13534 // method. 13535 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13536 long callingId = Binder.clearCallingIdentity(); 13537 try { 13538 for (int i = 0; i < packageNames.length; i++) { 13539 String packageName = packageNames[i]; 13540 boolean changed = false; 13541 final int appId; 13542 synchronized (mPackages) { 13543 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13544 if (pkgSetting == null) { 13545 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13546 + "\". Skipping suspending/un-suspending."); 13547 unactionedPackages.add(packageName); 13548 continue; 13549 } 13550 appId = pkgSetting.appId; 13551 if (pkgSetting.getSuspended(userId) != suspended) { 13552 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13553 unactionedPackages.add(packageName); 13554 continue; 13555 } 13556 pkgSetting.setSuspended(suspended, userId); 13557 mSettings.writePackageRestrictionsLPr(userId); 13558 changed = true; 13559 changedPackages.add(packageName); 13560 } 13561 } 13562 13563 if (changed && suspended) { 13564 killApplication(packageName, UserHandle.getUid(userId, appId), 13565 "suspending package"); 13566 } 13567 } 13568 } finally { 13569 Binder.restoreCallingIdentity(callingId); 13570 } 13571 13572 if (!changedPackages.isEmpty()) { 13573 sendPackagesSuspendedForUser(changedPackages.toArray( 13574 new String[changedPackages.size()]), userId, suspended); 13575 } 13576 13577 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13578 } 13579 13580 @Override 13581 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13582 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13583 true /* requireFullPermission */, false /* checkShell */, 13584 "isPackageSuspendedForUser for user " + userId); 13585 synchronized (mPackages) { 13586 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13587 if (pkgSetting == null) { 13588 throw new IllegalArgumentException("Unknown target package: " + packageName); 13589 } 13590 return pkgSetting.getSuspended(userId); 13591 } 13592 } 13593 13594 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13595 if (isPackageDeviceAdmin(packageName, userId)) { 13596 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13597 + "\": has an active device admin"); 13598 return false; 13599 } 13600 13601 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13602 if (packageName.equals(activeLauncherPackageName)) { 13603 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13604 + "\": contains the active launcher"); 13605 return false; 13606 } 13607 13608 if (packageName.equals(mRequiredInstallerPackage)) { 13609 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13610 + "\": required for package installation"); 13611 return false; 13612 } 13613 13614 if (packageName.equals(mRequiredUninstallerPackage)) { 13615 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13616 + "\": required for package uninstallation"); 13617 return false; 13618 } 13619 13620 if (packageName.equals(mRequiredVerifierPackage)) { 13621 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13622 + "\": required for package verification"); 13623 return false; 13624 } 13625 13626 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13627 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13628 + "\": is the default dialer"); 13629 return false; 13630 } 13631 13632 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13633 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13634 + "\": protected package"); 13635 return false; 13636 } 13637 13638 // Cannot suspend static shared libs as they are considered 13639 // a part of the using app (emulating static linking). Also 13640 // static libs are installed always on internal storage. 13641 PackageParser.Package pkg = mPackages.get(packageName); 13642 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13643 Slog.w(TAG, "Cannot suspend package: " + packageName 13644 + " providing static shared library: " 13645 + pkg.staticSharedLibName); 13646 return false; 13647 } 13648 13649 return true; 13650 } 13651 13652 private String getActiveLauncherPackageName(int userId) { 13653 Intent intent = new Intent(Intent.ACTION_MAIN); 13654 intent.addCategory(Intent.CATEGORY_HOME); 13655 ResolveInfo resolveInfo = resolveIntent( 13656 intent, 13657 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13658 PackageManager.MATCH_DEFAULT_ONLY, 13659 userId); 13660 13661 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13662 } 13663 13664 private String getDefaultDialerPackageName(int userId) { 13665 synchronized (mPackages) { 13666 return mSettings.getDefaultDialerPackageNameLPw(userId); 13667 } 13668 } 13669 13670 @Override 13671 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13672 mContext.enforceCallingOrSelfPermission( 13673 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13674 "Only package verification agents can verify applications"); 13675 13676 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13677 final PackageVerificationResponse response = new PackageVerificationResponse( 13678 verificationCode, Binder.getCallingUid()); 13679 msg.arg1 = id; 13680 msg.obj = response; 13681 mHandler.sendMessage(msg); 13682 } 13683 13684 @Override 13685 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13686 long millisecondsToDelay) { 13687 mContext.enforceCallingOrSelfPermission( 13688 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13689 "Only package verification agents can extend verification timeouts"); 13690 13691 final PackageVerificationState state = mPendingVerification.get(id); 13692 final PackageVerificationResponse response = new PackageVerificationResponse( 13693 verificationCodeAtTimeout, Binder.getCallingUid()); 13694 13695 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13696 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13697 } 13698 if (millisecondsToDelay < 0) { 13699 millisecondsToDelay = 0; 13700 } 13701 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13702 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13703 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13704 } 13705 13706 if ((state != null) && !state.timeoutExtended()) { 13707 state.extendTimeout(); 13708 13709 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13710 msg.arg1 = id; 13711 msg.obj = response; 13712 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13713 } 13714 } 13715 13716 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13717 int verificationCode, UserHandle user) { 13718 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13719 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13720 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13721 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13722 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13723 13724 mContext.sendBroadcastAsUser(intent, user, 13725 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13726 } 13727 13728 private ComponentName matchComponentForVerifier(String packageName, 13729 List<ResolveInfo> receivers) { 13730 ActivityInfo targetReceiver = null; 13731 13732 final int NR = receivers.size(); 13733 for (int i = 0; i < NR; i++) { 13734 final ResolveInfo info = receivers.get(i); 13735 if (info.activityInfo == null) { 13736 continue; 13737 } 13738 13739 if (packageName.equals(info.activityInfo.packageName)) { 13740 targetReceiver = info.activityInfo; 13741 break; 13742 } 13743 } 13744 13745 if (targetReceiver == null) { 13746 return null; 13747 } 13748 13749 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13750 } 13751 13752 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13753 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13754 if (pkgInfo.verifiers.length == 0) { 13755 return null; 13756 } 13757 13758 final int N = pkgInfo.verifiers.length; 13759 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13760 for (int i = 0; i < N; i++) { 13761 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13762 13763 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13764 receivers); 13765 if (comp == null) { 13766 continue; 13767 } 13768 13769 final int verifierUid = getUidForVerifier(verifierInfo); 13770 if (verifierUid == -1) { 13771 continue; 13772 } 13773 13774 if (DEBUG_VERIFY) { 13775 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13776 + " with the correct signature"); 13777 } 13778 sufficientVerifiers.add(comp); 13779 verificationState.addSufficientVerifier(verifierUid); 13780 } 13781 13782 return sufficientVerifiers; 13783 } 13784 13785 private int getUidForVerifier(VerifierInfo verifierInfo) { 13786 synchronized (mPackages) { 13787 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13788 if (pkg == null) { 13789 return -1; 13790 } else if (pkg.mSignatures.length != 1) { 13791 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13792 + " has more than one signature; ignoring"); 13793 return -1; 13794 } 13795 13796 /* 13797 * If the public key of the package's signature does not match 13798 * our expected public key, then this is a different package and 13799 * we should skip. 13800 */ 13801 13802 final byte[] expectedPublicKey; 13803 try { 13804 final Signature verifierSig = pkg.mSignatures[0]; 13805 final PublicKey publicKey = verifierSig.getPublicKey(); 13806 expectedPublicKey = publicKey.getEncoded(); 13807 } catch (CertificateException e) { 13808 return -1; 13809 } 13810 13811 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13812 13813 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13814 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13815 + " does not have the expected public key; ignoring"); 13816 return -1; 13817 } 13818 13819 return pkg.applicationInfo.uid; 13820 } 13821 } 13822 13823 @Override 13824 public void finishPackageInstall(int token, boolean didLaunch) { 13825 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13826 13827 if (DEBUG_INSTALL) { 13828 Slog.v(TAG, "BM finishing package install for " + token); 13829 } 13830 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13831 13832 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13833 mHandler.sendMessage(msg); 13834 } 13835 13836 /** 13837 * Get the verification agent timeout. 13838 * 13839 * @return verification timeout in milliseconds 13840 */ 13841 private long getVerificationTimeout() { 13842 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13843 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13844 DEFAULT_VERIFICATION_TIMEOUT); 13845 } 13846 13847 /** 13848 * Get the default verification agent response code. 13849 * 13850 * @return default verification response code 13851 */ 13852 private int getDefaultVerificationResponse() { 13853 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13854 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13855 DEFAULT_VERIFICATION_RESPONSE); 13856 } 13857 13858 /** 13859 * Check whether or not package verification has been enabled. 13860 * 13861 * @return true if verification should be performed 13862 */ 13863 private boolean isVerificationEnabled(int userId, int installFlags) { 13864 if (!DEFAULT_VERIFY_ENABLE) { 13865 return false; 13866 } 13867 // Ephemeral apps don't get the full verification treatment 13868 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13869 if (DEBUG_EPHEMERAL) { 13870 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13871 } 13872 return false; 13873 } 13874 13875 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13876 13877 // Check if installing from ADB 13878 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13879 // Do not run verification in a test harness environment 13880 if (ActivityManager.isRunningInTestHarness()) { 13881 return false; 13882 } 13883 if (ensureVerifyAppsEnabled) { 13884 return true; 13885 } 13886 // Check if the developer does not want package verification for ADB installs 13887 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13888 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13889 return false; 13890 } 13891 } 13892 13893 if (ensureVerifyAppsEnabled) { 13894 return true; 13895 } 13896 13897 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13898 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13899 } 13900 13901 @Override 13902 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13903 throws RemoteException { 13904 mContext.enforceCallingOrSelfPermission( 13905 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13906 "Only intentfilter verification agents can verify applications"); 13907 13908 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13909 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13910 Binder.getCallingUid(), verificationCode, failedDomains); 13911 msg.arg1 = id; 13912 msg.obj = response; 13913 mHandler.sendMessage(msg); 13914 } 13915 13916 @Override 13917 public int getIntentVerificationStatus(String packageName, int userId) { 13918 synchronized (mPackages) { 13919 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13920 } 13921 } 13922 13923 @Override 13924 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13925 mContext.enforceCallingOrSelfPermission( 13926 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13927 13928 boolean result = false; 13929 synchronized (mPackages) { 13930 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13931 } 13932 if (result) { 13933 scheduleWritePackageRestrictionsLocked(userId); 13934 } 13935 return result; 13936 } 13937 13938 @Override 13939 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13940 String packageName) { 13941 synchronized (mPackages) { 13942 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13943 } 13944 } 13945 13946 @Override 13947 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13948 if (TextUtils.isEmpty(packageName)) { 13949 return ParceledListSlice.emptyList(); 13950 } 13951 synchronized (mPackages) { 13952 PackageParser.Package pkg = mPackages.get(packageName); 13953 if (pkg == null || pkg.activities == null) { 13954 return ParceledListSlice.emptyList(); 13955 } 13956 final int count = pkg.activities.size(); 13957 ArrayList<IntentFilter> result = new ArrayList<>(); 13958 for (int n=0; n<count; n++) { 13959 PackageParser.Activity activity = pkg.activities.get(n); 13960 if (activity.intents != null && activity.intents.size() > 0) { 13961 result.addAll(activity.intents); 13962 } 13963 } 13964 return new ParceledListSlice<>(result); 13965 } 13966 } 13967 13968 @Override 13969 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13970 mContext.enforceCallingOrSelfPermission( 13971 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13972 13973 synchronized (mPackages) { 13974 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13975 if (packageName != null) { 13976 result |= updateIntentVerificationStatus(packageName, 13977 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13978 userId); 13979 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13980 packageName, userId); 13981 } 13982 return result; 13983 } 13984 } 13985 13986 @Override 13987 public String getDefaultBrowserPackageName(int userId) { 13988 synchronized (mPackages) { 13989 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13990 } 13991 } 13992 13993 /** 13994 * Get the "allow unknown sources" setting. 13995 * 13996 * @return the current "allow unknown sources" setting 13997 */ 13998 private int getUnknownSourcesSettings() { 13999 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14000 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14001 -1); 14002 } 14003 14004 @Override 14005 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14006 final int uid = Binder.getCallingUid(); 14007 // writer 14008 synchronized (mPackages) { 14009 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14010 if (targetPackageSetting == null) { 14011 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14012 } 14013 14014 PackageSetting installerPackageSetting; 14015 if (installerPackageName != null) { 14016 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14017 if (installerPackageSetting == null) { 14018 throw new IllegalArgumentException("Unknown installer package: " 14019 + installerPackageName); 14020 } 14021 } else { 14022 installerPackageSetting = null; 14023 } 14024 14025 Signature[] callerSignature; 14026 Object obj = mSettings.getUserIdLPr(uid); 14027 if (obj != null) { 14028 if (obj instanceof SharedUserSetting) { 14029 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14030 } else if (obj instanceof PackageSetting) { 14031 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14032 } else { 14033 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14034 } 14035 } else { 14036 throw new SecurityException("Unknown calling UID: " + uid); 14037 } 14038 14039 // Verify: can't set installerPackageName to a package that is 14040 // not signed with the same cert as the caller. 14041 if (installerPackageSetting != null) { 14042 if (compareSignatures(callerSignature, 14043 installerPackageSetting.signatures.mSignatures) 14044 != PackageManager.SIGNATURE_MATCH) { 14045 throw new SecurityException( 14046 "Caller does not have same cert as new installer package " 14047 + installerPackageName); 14048 } 14049 } 14050 14051 // Verify: if target already has an installer package, it must 14052 // be signed with the same cert as the caller. 14053 if (targetPackageSetting.installerPackageName != null) { 14054 PackageSetting setting = mSettings.mPackages.get( 14055 targetPackageSetting.installerPackageName); 14056 // If the currently set package isn't valid, then it's always 14057 // okay to change it. 14058 if (setting != null) { 14059 if (compareSignatures(callerSignature, 14060 setting.signatures.mSignatures) 14061 != PackageManager.SIGNATURE_MATCH) { 14062 throw new SecurityException( 14063 "Caller does not have same cert as old installer package " 14064 + targetPackageSetting.installerPackageName); 14065 } 14066 } 14067 } 14068 14069 // Okay! 14070 targetPackageSetting.installerPackageName = installerPackageName; 14071 if (installerPackageName != null) { 14072 mSettings.mInstallerPackages.add(installerPackageName); 14073 } 14074 scheduleWriteSettingsLocked(); 14075 } 14076 } 14077 14078 @Override 14079 public void setApplicationCategoryHint(String packageName, int categoryHint, 14080 String callerPackageName) { 14081 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14082 callerPackageName); 14083 synchronized (mPackages) { 14084 PackageSetting ps = mSettings.mPackages.get(packageName); 14085 if (ps == null) { 14086 throw new IllegalArgumentException("Unknown target package " + packageName); 14087 } 14088 14089 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14090 throw new IllegalArgumentException("Calling package " + callerPackageName 14091 + " is not installer for " + packageName); 14092 } 14093 14094 if (ps.categoryHint != categoryHint) { 14095 ps.categoryHint = categoryHint; 14096 scheduleWriteSettingsLocked(); 14097 } 14098 } 14099 } 14100 14101 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14102 // Queue up an async operation since the package installation may take a little while. 14103 mHandler.post(new Runnable() { 14104 public void run() { 14105 mHandler.removeCallbacks(this); 14106 // Result object to be returned 14107 PackageInstalledInfo res = new PackageInstalledInfo(); 14108 res.setReturnCode(currentStatus); 14109 res.uid = -1; 14110 res.pkg = null; 14111 res.removedInfo = null; 14112 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14113 args.doPreInstall(res.returnCode); 14114 synchronized (mInstallLock) { 14115 installPackageTracedLI(args, res); 14116 } 14117 args.doPostInstall(res.returnCode, res.uid); 14118 } 14119 14120 // A restore should be performed at this point if (a) the install 14121 // succeeded, (b) the operation is not an update, and (c) the new 14122 // package has not opted out of backup participation. 14123 final boolean update = res.removedInfo != null 14124 && res.removedInfo.removedPackage != null; 14125 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14126 boolean doRestore = !update 14127 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14128 14129 // Set up the post-install work request bookkeeping. This will be used 14130 // and cleaned up by the post-install event handling regardless of whether 14131 // there's a restore pass performed. Token values are >= 1. 14132 int token; 14133 if (mNextInstallToken < 0) mNextInstallToken = 1; 14134 token = mNextInstallToken++; 14135 14136 PostInstallData data = new PostInstallData(args, res); 14137 mRunningInstalls.put(token, data); 14138 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14139 14140 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14141 // Pass responsibility to the Backup Manager. It will perform a 14142 // restore if appropriate, then pass responsibility back to the 14143 // Package Manager to run the post-install observer callbacks 14144 // and broadcasts. 14145 IBackupManager bm = IBackupManager.Stub.asInterface( 14146 ServiceManager.getService(Context.BACKUP_SERVICE)); 14147 if (bm != null) { 14148 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14149 + " to BM for possible restore"); 14150 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14151 try { 14152 // TODO: http://b/22388012 14153 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14154 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14155 } else { 14156 doRestore = false; 14157 } 14158 } catch (RemoteException e) { 14159 // can't happen; the backup manager is local 14160 } catch (Exception e) { 14161 Slog.e(TAG, "Exception trying to enqueue restore", e); 14162 doRestore = false; 14163 } 14164 } else { 14165 Slog.e(TAG, "Backup Manager not found!"); 14166 doRestore = false; 14167 } 14168 } 14169 14170 if (!doRestore) { 14171 // No restore possible, or the Backup Manager was mysteriously not 14172 // available -- just fire the post-install work request directly. 14173 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14174 14175 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14176 14177 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14178 mHandler.sendMessage(msg); 14179 } 14180 } 14181 }); 14182 } 14183 14184 /** 14185 * Callback from PackageSettings whenever an app is first transitioned out of the 14186 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14187 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14188 * here whether the app is the target of an ongoing install, and only send the 14189 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14190 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14191 * handling. 14192 */ 14193 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14194 // Serialize this with the rest of the install-process message chain. In the 14195 // restore-at-install case, this Runnable will necessarily run before the 14196 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14197 // are coherent. In the non-restore case, the app has already completed install 14198 // and been launched through some other means, so it is not in a problematic 14199 // state for observers to see the FIRST_LAUNCH signal. 14200 mHandler.post(new Runnable() { 14201 @Override 14202 public void run() { 14203 for (int i = 0; i < mRunningInstalls.size(); i++) { 14204 final PostInstallData data = mRunningInstalls.valueAt(i); 14205 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14206 continue; 14207 } 14208 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14209 // right package; but is it for the right user? 14210 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14211 if (userId == data.res.newUsers[uIndex]) { 14212 if (DEBUG_BACKUP) { 14213 Slog.i(TAG, "Package " + pkgName 14214 + " being restored so deferring FIRST_LAUNCH"); 14215 } 14216 return; 14217 } 14218 } 14219 } 14220 } 14221 // didn't find it, so not being restored 14222 if (DEBUG_BACKUP) { 14223 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14224 } 14225 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14226 } 14227 }); 14228 } 14229 14230 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14231 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14232 installerPkg, null, userIds); 14233 } 14234 14235 private abstract class HandlerParams { 14236 private static final int MAX_RETRIES = 4; 14237 14238 /** 14239 * Number of times startCopy() has been attempted and had a non-fatal 14240 * error. 14241 */ 14242 private int mRetries = 0; 14243 14244 /** User handle for the user requesting the information or installation. */ 14245 private final UserHandle mUser; 14246 String traceMethod; 14247 int traceCookie; 14248 14249 HandlerParams(UserHandle user) { 14250 mUser = user; 14251 } 14252 14253 UserHandle getUser() { 14254 return mUser; 14255 } 14256 14257 HandlerParams setTraceMethod(String traceMethod) { 14258 this.traceMethod = traceMethod; 14259 return this; 14260 } 14261 14262 HandlerParams setTraceCookie(int traceCookie) { 14263 this.traceCookie = traceCookie; 14264 return this; 14265 } 14266 14267 final boolean startCopy() { 14268 boolean res; 14269 try { 14270 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14271 14272 if (++mRetries > MAX_RETRIES) { 14273 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14274 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14275 handleServiceError(); 14276 return false; 14277 } else { 14278 handleStartCopy(); 14279 res = true; 14280 } 14281 } catch (RemoteException e) { 14282 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14283 mHandler.sendEmptyMessage(MCS_RECONNECT); 14284 res = false; 14285 } 14286 handleReturnCode(); 14287 return res; 14288 } 14289 14290 final void serviceError() { 14291 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14292 handleServiceError(); 14293 handleReturnCode(); 14294 } 14295 14296 abstract void handleStartCopy() throws RemoteException; 14297 abstract void handleServiceError(); 14298 abstract void handleReturnCode(); 14299 } 14300 14301 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14302 for (File path : paths) { 14303 try { 14304 mcs.clearDirectory(path.getAbsolutePath()); 14305 } catch (RemoteException e) { 14306 } 14307 } 14308 } 14309 14310 static class OriginInfo { 14311 /** 14312 * Location where install is coming from, before it has been 14313 * copied/renamed into place. This could be a single monolithic APK 14314 * file, or a cluster directory. This location may be untrusted. 14315 */ 14316 final File file; 14317 final String cid; 14318 14319 /** 14320 * Flag indicating that {@link #file} or {@link #cid} has already been 14321 * staged, meaning downstream users don't need to defensively copy the 14322 * contents. 14323 */ 14324 final boolean staged; 14325 14326 /** 14327 * Flag indicating that {@link #file} or {@link #cid} is an already 14328 * installed app that is being moved. 14329 */ 14330 final boolean existing; 14331 14332 final String resolvedPath; 14333 final File resolvedFile; 14334 14335 static OriginInfo fromNothing() { 14336 return new OriginInfo(null, null, false, false); 14337 } 14338 14339 static OriginInfo fromUntrustedFile(File file) { 14340 return new OriginInfo(file, null, false, false); 14341 } 14342 14343 static OriginInfo fromExistingFile(File file) { 14344 return new OriginInfo(file, null, false, true); 14345 } 14346 14347 static OriginInfo fromStagedFile(File file) { 14348 return new OriginInfo(file, null, true, false); 14349 } 14350 14351 static OriginInfo fromStagedContainer(String cid) { 14352 return new OriginInfo(null, cid, true, false); 14353 } 14354 14355 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14356 this.file = file; 14357 this.cid = cid; 14358 this.staged = staged; 14359 this.existing = existing; 14360 14361 if (cid != null) { 14362 resolvedPath = PackageHelper.getSdDir(cid); 14363 resolvedFile = new File(resolvedPath); 14364 } else if (file != null) { 14365 resolvedPath = file.getAbsolutePath(); 14366 resolvedFile = file; 14367 } else { 14368 resolvedPath = null; 14369 resolvedFile = null; 14370 } 14371 } 14372 } 14373 14374 static class MoveInfo { 14375 final int moveId; 14376 final String fromUuid; 14377 final String toUuid; 14378 final String packageName; 14379 final String dataAppName; 14380 final int appId; 14381 final String seinfo; 14382 final int targetSdkVersion; 14383 14384 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14385 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14386 this.moveId = moveId; 14387 this.fromUuid = fromUuid; 14388 this.toUuid = toUuid; 14389 this.packageName = packageName; 14390 this.dataAppName = dataAppName; 14391 this.appId = appId; 14392 this.seinfo = seinfo; 14393 this.targetSdkVersion = targetSdkVersion; 14394 } 14395 } 14396 14397 static class VerificationInfo { 14398 /** A constant used to indicate that a uid value is not present. */ 14399 public static final int NO_UID = -1; 14400 14401 /** URI referencing where the package was downloaded from. */ 14402 final Uri originatingUri; 14403 14404 /** HTTP referrer URI associated with the originatingURI. */ 14405 final Uri referrer; 14406 14407 /** UID of the application that the install request originated from. */ 14408 final int originatingUid; 14409 14410 /** UID of application requesting the install */ 14411 final int installerUid; 14412 14413 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14414 this.originatingUri = originatingUri; 14415 this.referrer = referrer; 14416 this.originatingUid = originatingUid; 14417 this.installerUid = installerUid; 14418 } 14419 } 14420 14421 class InstallParams extends HandlerParams { 14422 final OriginInfo origin; 14423 final MoveInfo move; 14424 final IPackageInstallObserver2 observer; 14425 int installFlags; 14426 final String installerPackageName; 14427 final String volumeUuid; 14428 private InstallArgs mArgs; 14429 private int mRet; 14430 final String packageAbiOverride; 14431 final String[] grantedRuntimePermissions; 14432 final VerificationInfo verificationInfo; 14433 final Certificate[][] certificates; 14434 final int installReason; 14435 14436 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14437 int installFlags, String installerPackageName, String volumeUuid, 14438 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14439 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14440 super(user); 14441 this.origin = origin; 14442 this.move = move; 14443 this.observer = observer; 14444 this.installFlags = installFlags; 14445 this.installerPackageName = installerPackageName; 14446 this.volumeUuid = volumeUuid; 14447 this.verificationInfo = verificationInfo; 14448 this.packageAbiOverride = packageAbiOverride; 14449 this.grantedRuntimePermissions = grantedPermissions; 14450 this.certificates = certificates; 14451 this.installReason = installReason; 14452 } 14453 14454 @Override 14455 public String toString() { 14456 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14457 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14458 } 14459 14460 private int installLocationPolicy(PackageInfoLite pkgLite) { 14461 String packageName = pkgLite.packageName; 14462 int installLocation = pkgLite.installLocation; 14463 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14464 // reader 14465 synchronized (mPackages) { 14466 // Currently installed package which the new package is attempting to replace or 14467 // null if no such package is installed. 14468 PackageParser.Package installedPkg = mPackages.get(packageName); 14469 // Package which currently owns the data which the new package will own if installed. 14470 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14471 // will be null whereas dataOwnerPkg will contain information about the package 14472 // which was uninstalled while keeping its data. 14473 PackageParser.Package dataOwnerPkg = installedPkg; 14474 if (dataOwnerPkg == null) { 14475 PackageSetting ps = mSettings.mPackages.get(packageName); 14476 if (ps != null) { 14477 dataOwnerPkg = ps.pkg; 14478 } 14479 } 14480 14481 if (dataOwnerPkg != null) { 14482 // If installed, the package will get access to data left on the device by its 14483 // predecessor. As a security measure, this is permited only if this is not a 14484 // version downgrade or if the predecessor package is marked as debuggable and 14485 // a downgrade is explicitly requested. 14486 // 14487 // On debuggable platform builds, downgrades are permitted even for 14488 // non-debuggable packages to make testing easier. Debuggable platform builds do 14489 // not offer security guarantees and thus it's OK to disable some security 14490 // mechanisms to make debugging/testing easier on those builds. However, even on 14491 // debuggable builds downgrades of packages are permitted only if requested via 14492 // installFlags. This is because we aim to keep the behavior of debuggable 14493 // platform builds as close as possible to the behavior of non-debuggable 14494 // platform builds. 14495 final boolean downgradeRequested = 14496 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14497 final boolean packageDebuggable = 14498 (dataOwnerPkg.applicationInfo.flags 14499 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14500 final boolean downgradePermitted = 14501 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14502 if (!downgradePermitted) { 14503 try { 14504 checkDowngrade(dataOwnerPkg, pkgLite); 14505 } catch (PackageManagerException e) { 14506 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14507 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14508 } 14509 } 14510 } 14511 14512 if (installedPkg != null) { 14513 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14514 // Check for updated system application. 14515 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14516 if (onSd) { 14517 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14518 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14519 } 14520 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14521 } else { 14522 if (onSd) { 14523 // Install flag overrides everything. 14524 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14525 } 14526 // If current upgrade specifies particular preference 14527 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14528 // Application explicitly specified internal. 14529 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14530 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14531 // App explictly prefers external. Let policy decide 14532 } else { 14533 // Prefer previous location 14534 if (isExternal(installedPkg)) { 14535 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14536 } 14537 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14538 } 14539 } 14540 } else { 14541 // Invalid install. Return error code 14542 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14543 } 14544 } 14545 } 14546 // All the special cases have been taken care of. 14547 // Return result based on recommended install location. 14548 if (onSd) { 14549 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14550 } 14551 return pkgLite.recommendedInstallLocation; 14552 } 14553 14554 /* 14555 * Invoke remote method to get package information and install 14556 * location values. Override install location based on default 14557 * policy if needed and then create install arguments based 14558 * on the install location. 14559 */ 14560 public void handleStartCopy() throws RemoteException { 14561 int ret = PackageManager.INSTALL_SUCCEEDED; 14562 14563 // If we're already staged, we've firmly committed to an install location 14564 if (origin.staged) { 14565 if (origin.file != null) { 14566 installFlags |= PackageManager.INSTALL_INTERNAL; 14567 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14568 } else if (origin.cid != null) { 14569 installFlags |= PackageManager.INSTALL_EXTERNAL; 14570 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14571 } else { 14572 throw new IllegalStateException("Invalid stage location"); 14573 } 14574 } 14575 14576 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14577 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14578 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14579 PackageInfoLite pkgLite = null; 14580 14581 if (onInt && onSd) { 14582 // Check if both bits are set. 14583 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14584 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14585 } else if (onSd && ephemeral) { 14586 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14587 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14588 } else { 14589 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14590 packageAbiOverride); 14591 14592 if (DEBUG_EPHEMERAL && ephemeral) { 14593 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14594 } 14595 14596 /* 14597 * If we have too little free space, try to free cache 14598 * before giving up. 14599 */ 14600 if (!origin.staged && pkgLite.recommendedInstallLocation 14601 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14602 // TODO: focus freeing disk space on the target device 14603 final StorageManager storage = StorageManager.from(mContext); 14604 final long lowThreshold = storage.getStorageLowBytes( 14605 Environment.getDataDirectory()); 14606 14607 final long sizeBytes = mContainerService.calculateInstalledSize( 14608 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14609 14610 try { 14611 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14612 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14613 installFlags, packageAbiOverride); 14614 } catch (InstallerException e) { 14615 Slog.w(TAG, "Failed to free cache", e); 14616 } 14617 14618 /* 14619 * The cache free must have deleted the file we 14620 * downloaded to install. 14621 * 14622 * TODO: fix the "freeCache" call to not delete 14623 * the file we care about. 14624 */ 14625 if (pkgLite.recommendedInstallLocation 14626 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14627 pkgLite.recommendedInstallLocation 14628 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14629 } 14630 } 14631 } 14632 14633 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14634 int loc = pkgLite.recommendedInstallLocation; 14635 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14636 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14637 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14638 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14639 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14640 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14641 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14642 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14643 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14644 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14645 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14646 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14647 } else { 14648 // Override with defaults if needed. 14649 loc = installLocationPolicy(pkgLite); 14650 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14651 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14652 } else if (!onSd && !onInt) { 14653 // Override install location with flags 14654 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14655 // Set the flag to install on external media. 14656 installFlags |= PackageManager.INSTALL_EXTERNAL; 14657 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14658 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14659 if (DEBUG_EPHEMERAL) { 14660 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14661 } 14662 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14663 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14664 |PackageManager.INSTALL_INTERNAL); 14665 } else { 14666 // Make sure the flag for installing on external 14667 // media is unset 14668 installFlags |= PackageManager.INSTALL_INTERNAL; 14669 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14670 } 14671 } 14672 } 14673 } 14674 14675 final InstallArgs args = createInstallArgs(this); 14676 mArgs = args; 14677 14678 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14679 // TODO: http://b/22976637 14680 // Apps installed for "all" users use the device owner to verify the app 14681 UserHandle verifierUser = getUser(); 14682 if (verifierUser == UserHandle.ALL) { 14683 verifierUser = UserHandle.SYSTEM; 14684 } 14685 14686 /* 14687 * Determine if we have any installed package verifiers. If we 14688 * do, then we'll defer to them to verify the packages. 14689 */ 14690 final int requiredUid = mRequiredVerifierPackage == null ? -1 14691 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14692 verifierUser.getIdentifier()); 14693 if (!origin.existing && requiredUid != -1 14694 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14695 final Intent verification = new Intent( 14696 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14697 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14698 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14699 PACKAGE_MIME_TYPE); 14700 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14701 14702 // Query all live verifiers based on current user state 14703 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14704 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14705 14706 if (DEBUG_VERIFY) { 14707 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14708 + verification.toString() + " with " + pkgLite.verifiers.length 14709 + " optional verifiers"); 14710 } 14711 14712 final int verificationId = mPendingVerificationToken++; 14713 14714 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14715 14716 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14717 installerPackageName); 14718 14719 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14720 installFlags); 14721 14722 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14723 pkgLite.packageName); 14724 14725 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14726 pkgLite.versionCode); 14727 14728 if (verificationInfo != null) { 14729 if (verificationInfo.originatingUri != null) { 14730 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14731 verificationInfo.originatingUri); 14732 } 14733 if (verificationInfo.referrer != null) { 14734 verification.putExtra(Intent.EXTRA_REFERRER, 14735 verificationInfo.referrer); 14736 } 14737 if (verificationInfo.originatingUid >= 0) { 14738 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14739 verificationInfo.originatingUid); 14740 } 14741 if (verificationInfo.installerUid >= 0) { 14742 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14743 verificationInfo.installerUid); 14744 } 14745 } 14746 14747 final PackageVerificationState verificationState = new PackageVerificationState( 14748 requiredUid, args); 14749 14750 mPendingVerification.append(verificationId, verificationState); 14751 14752 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14753 receivers, verificationState); 14754 14755 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14756 final long idleDuration = getVerificationTimeout(); 14757 14758 /* 14759 * If any sufficient verifiers were listed in the package 14760 * manifest, attempt to ask them. 14761 */ 14762 if (sufficientVerifiers != null) { 14763 final int N = sufficientVerifiers.size(); 14764 if (N == 0) { 14765 Slog.i(TAG, "Additional verifiers required, but none installed."); 14766 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14767 } else { 14768 for (int i = 0; i < N; i++) { 14769 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14770 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14771 verifierComponent.getPackageName(), idleDuration, 14772 verifierUser.getIdentifier(), false, "package verifier"); 14773 14774 final Intent sufficientIntent = new Intent(verification); 14775 sufficientIntent.setComponent(verifierComponent); 14776 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14777 } 14778 } 14779 } 14780 14781 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14782 mRequiredVerifierPackage, receivers); 14783 if (ret == PackageManager.INSTALL_SUCCEEDED 14784 && mRequiredVerifierPackage != null) { 14785 Trace.asyncTraceBegin( 14786 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14787 /* 14788 * Send the intent to the required verification agent, 14789 * but only start the verification timeout after the 14790 * target BroadcastReceivers have run. 14791 */ 14792 verification.setComponent(requiredVerifierComponent); 14793 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14794 requiredVerifierComponent.getPackageName(), idleDuration, 14795 verifierUser.getIdentifier(), false, "package verifier"); 14796 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14797 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14798 new BroadcastReceiver() { 14799 @Override 14800 public void onReceive(Context context, Intent intent) { 14801 final Message msg = mHandler 14802 .obtainMessage(CHECK_PENDING_VERIFICATION); 14803 msg.arg1 = verificationId; 14804 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14805 } 14806 }, null, 0, null, null); 14807 14808 /* 14809 * We don't want the copy to proceed until verification 14810 * succeeds, so null out this field. 14811 */ 14812 mArgs = null; 14813 } 14814 } else { 14815 /* 14816 * No package verification is enabled, so immediately start 14817 * the remote call to initiate copy using temporary file. 14818 */ 14819 ret = args.copyApk(mContainerService, true); 14820 } 14821 } 14822 14823 mRet = ret; 14824 } 14825 14826 @Override 14827 void handleReturnCode() { 14828 // If mArgs is null, then MCS couldn't be reached. When it 14829 // reconnects, it will try again to install. At that point, this 14830 // will succeed. 14831 if (mArgs != null) { 14832 processPendingInstall(mArgs, mRet); 14833 } 14834 } 14835 14836 @Override 14837 void handleServiceError() { 14838 mArgs = createInstallArgs(this); 14839 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14840 } 14841 14842 public boolean isForwardLocked() { 14843 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14844 } 14845 } 14846 14847 /** 14848 * Used during creation of InstallArgs 14849 * 14850 * @param installFlags package installation flags 14851 * @return true if should be installed on external storage 14852 */ 14853 private static boolean installOnExternalAsec(int installFlags) { 14854 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14855 return false; 14856 } 14857 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14858 return true; 14859 } 14860 return false; 14861 } 14862 14863 /** 14864 * Used during creation of InstallArgs 14865 * 14866 * @param installFlags package installation flags 14867 * @return true if should be installed as forward locked 14868 */ 14869 private static boolean installForwardLocked(int installFlags) { 14870 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14871 } 14872 14873 private InstallArgs createInstallArgs(InstallParams params) { 14874 if (params.move != null) { 14875 return new MoveInstallArgs(params); 14876 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14877 return new AsecInstallArgs(params); 14878 } else { 14879 return new FileInstallArgs(params); 14880 } 14881 } 14882 14883 /** 14884 * Create args that describe an existing installed package. Typically used 14885 * when cleaning up old installs, or used as a move source. 14886 */ 14887 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14888 String resourcePath, String[] instructionSets) { 14889 final boolean isInAsec; 14890 if (installOnExternalAsec(installFlags)) { 14891 /* Apps on SD card are always in ASEC containers. */ 14892 isInAsec = true; 14893 } else if (installForwardLocked(installFlags) 14894 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14895 /* 14896 * Forward-locked apps are only in ASEC containers if they're the 14897 * new style 14898 */ 14899 isInAsec = true; 14900 } else { 14901 isInAsec = false; 14902 } 14903 14904 if (isInAsec) { 14905 return new AsecInstallArgs(codePath, instructionSets, 14906 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14907 } else { 14908 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14909 } 14910 } 14911 14912 static abstract class InstallArgs { 14913 /** @see InstallParams#origin */ 14914 final OriginInfo origin; 14915 /** @see InstallParams#move */ 14916 final MoveInfo move; 14917 14918 final IPackageInstallObserver2 observer; 14919 // Always refers to PackageManager flags only 14920 final int installFlags; 14921 final String installerPackageName; 14922 final String volumeUuid; 14923 final UserHandle user; 14924 final String abiOverride; 14925 final String[] installGrantPermissions; 14926 /** If non-null, drop an async trace when the install completes */ 14927 final String traceMethod; 14928 final int traceCookie; 14929 final Certificate[][] certificates; 14930 final int installReason; 14931 14932 // The list of instruction sets supported by this app. This is currently 14933 // only used during the rmdex() phase to clean up resources. We can get rid of this 14934 // if we move dex files under the common app path. 14935 /* nullable */ String[] instructionSets; 14936 14937 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14938 int installFlags, String installerPackageName, String volumeUuid, 14939 UserHandle user, String[] instructionSets, 14940 String abiOverride, String[] installGrantPermissions, 14941 String traceMethod, int traceCookie, Certificate[][] certificates, 14942 int installReason) { 14943 this.origin = origin; 14944 this.move = move; 14945 this.installFlags = installFlags; 14946 this.observer = observer; 14947 this.installerPackageName = installerPackageName; 14948 this.volumeUuid = volumeUuid; 14949 this.user = user; 14950 this.instructionSets = instructionSets; 14951 this.abiOverride = abiOverride; 14952 this.installGrantPermissions = installGrantPermissions; 14953 this.traceMethod = traceMethod; 14954 this.traceCookie = traceCookie; 14955 this.certificates = certificates; 14956 this.installReason = installReason; 14957 } 14958 14959 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14960 abstract int doPreInstall(int status); 14961 14962 /** 14963 * Rename package into final resting place. All paths on the given 14964 * scanned package should be updated to reflect the rename. 14965 */ 14966 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14967 abstract int doPostInstall(int status, int uid); 14968 14969 /** @see PackageSettingBase#codePathString */ 14970 abstract String getCodePath(); 14971 /** @see PackageSettingBase#resourcePathString */ 14972 abstract String getResourcePath(); 14973 14974 // Need installer lock especially for dex file removal. 14975 abstract void cleanUpResourcesLI(); 14976 abstract boolean doPostDeleteLI(boolean delete); 14977 14978 /** 14979 * Called before the source arguments are copied. This is used mostly 14980 * for MoveParams when it needs to read the source file to put it in the 14981 * destination. 14982 */ 14983 int doPreCopy() { 14984 return PackageManager.INSTALL_SUCCEEDED; 14985 } 14986 14987 /** 14988 * Called after the source arguments are copied. This is used mostly for 14989 * MoveParams when it needs to read the source file to put it in the 14990 * destination. 14991 */ 14992 int doPostCopy(int uid) { 14993 return PackageManager.INSTALL_SUCCEEDED; 14994 } 14995 14996 protected boolean isFwdLocked() { 14997 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14998 } 14999 15000 protected boolean isExternalAsec() { 15001 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15002 } 15003 15004 protected boolean isEphemeral() { 15005 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15006 } 15007 15008 UserHandle getUser() { 15009 return user; 15010 } 15011 } 15012 15013 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15014 if (!allCodePaths.isEmpty()) { 15015 if (instructionSets == null) { 15016 throw new IllegalStateException("instructionSet == null"); 15017 } 15018 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15019 for (String codePath : allCodePaths) { 15020 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15021 try { 15022 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15023 } catch (InstallerException ignored) { 15024 } 15025 } 15026 } 15027 } 15028 } 15029 15030 /** 15031 * Logic to handle installation of non-ASEC applications, including copying 15032 * and renaming logic. 15033 */ 15034 class FileInstallArgs extends InstallArgs { 15035 private File codeFile; 15036 private File resourceFile; 15037 15038 // Example topology: 15039 // /data/app/com.example/base.apk 15040 // /data/app/com.example/split_foo.apk 15041 // /data/app/com.example/lib/arm/libfoo.so 15042 // /data/app/com.example/lib/arm64/libfoo.so 15043 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15044 15045 /** New install */ 15046 FileInstallArgs(InstallParams params) { 15047 super(params.origin, params.move, params.observer, params.installFlags, 15048 params.installerPackageName, params.volumeUuid, 15049 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15050 params.grantedRuntimePermissions, 15051 params.traceMethod, params.traceCookie, params.certificates, 15052 params.installReason); 15053 if (isFwdLocked()) { 15054 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15055 } 15056 } 15057 15058 /** Existing install */ 15059 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15060 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15061 null, null, null, 0, null /*certificates*/, 15062 PackageManager.INSTALL_REASON_UNKNOWN); 15063 this.codeFile = (codePath != null) ? new File(codePath) : null; 15064 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15065 } 15066 15067 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15068 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15069 try { 15070 return doCopyApk(imcs, temp); 15071 } finally { 15072 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15073 } 15074 } 15075 15076 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15077 if (origin.staged) { 15078 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15079 codeFile = origin.file; 15080 resourceFile = origin.file; 15081 return PackageManager.INSTALL_SUCCEEDED; 15082 } 15083 15084 try { 15085 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15086 final File tempDir = 15087 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15088 codeFile = tempDir; 15089 resourceFile = tempDir; 15090 } catch (IOException e) { 15091 Slog.w(TAG, "Failed to create copy file: " + e); 15092 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15093 } 15094 15095 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15096 @Override 15097 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15098 if (!FileUtils.isValidExtFilename(name)) { 15099 throw new IllegalArgumentException("Invalid filename: " + name); 15100 } 15101 try { 15102 final File file = new File(codeFile, name); 15103 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15104 O_RDWR | O_CREAT, 0644); 15105 Os.chmod(file.getAbsolutePath(), 0644); 15106 return new ParcelFileDescriptor(fd); 15107 } catch (ErrnoException e) { 15108 throw new RemoteException("Failed to open: " + e.getMessage()); 15109 } 15110 } 15111 }; 15112 15113 int ret = PackageManager.INSTALL_SUCCEEDED; 15114 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15115 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15116 Slog.e(TAG, "Failed to copy package"); 15117 return ret; 15118 } 15119 15120 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15121 NativeLibraryHelper.Handle handle = null; 15122 try { 15123 handle = NativeLibraryHelper.Handle.create(codeFile); 15124 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15125 abiOverride); 15126 } catch (IOException e) { 15127 Slog.e(TAG, "Copying native libraries failed", e); 15128 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15129 } finally { 15130 IoUtils.closeQuietly(handle); 15131 } 15132 15133 return ret; 15134 } 15135 15136 int doPreInstall(int status) { 15137 if (status != PackageManager.INSTALL_SUCCEEDED) { 15138 cleanUp(); 15139 } 15140 return status; 15141 } 15142 15143 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15144 if (status != PackageManager.INSTALL_SUCCEEDED) { 15145 cleanUp(); 15146 return false; 15147 } 15148 15149 final File targetDir = codeFile.getParentFile(); 15150 final File beforeCodeFile = codeFile; 15151 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15152 15153 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15154 try { 15155 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15156 } catch (ErrnoException e) { 15157 Slog.w(TAG, "Failed to rename", e); 15158 return false; 15159 } 15160 15161 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15162 Slog.w(TAG, "Failed to restorecon"); 15163 return false; 15164 } 15165 15166 // Reflect the rename internally 15167 codeFile = afterCodeFile; 15168 resourceFile = afterCodeFile; 15169 15170 // Reflect the rename in scanned details 15171 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15172 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15173 afterCodeFile, pkg.baseCodePath)); 15174 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15175 afterCodeFile, pkg.splitCodePaths)); 15176 15177 // Reflect the rename in app info 15178 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15179 pkg.setApplicationInfoCodePath(pkg.codePath); 15180 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15181 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15182 pkg.setApplicationInfoResourcePath(pkg.codePath); 15183 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15184 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15185 15186 return true; 15187 } 15188 15189 int doPostInstall(int status, int uid) { 15190 if (status != PackageManager.INSTALL_SUCCEEDED) { 15191 cleanUp(); 15192 } 15193 return status; 15194 } 15195 15196 @Override 15197 String getCodePath() { 15198 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15199 } 15200 15201 @Override 15202 String getResourcePath() { 15203 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15204 } 15205 15206 private boolean cleanUp() { 15207 if (codeFile == null || !codeFile.exists()) { 15208 return false; 15209 } 15210 15211 removeCodePathLI(codeFile); 15212 15213 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15214 resourceFile.delete(); 15215 } 15216 15217 return true; 15218 } 15219 15220 void cleanUpResourcesLI() { 15221 // Try enumerating all code paths before deleting 15222 List<String> allCodePaths = Collections.EMPTY_LIST; 15223 if (codeFile != null && codeFile.exists()) { 15224 try { 15225 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15226 allCodePaths = pkg.getAllCodePaths(); 15227 } catch (PackageParserException e) { 15228 // Ignored; we tried our best 15229 } 15230 } 15231 15232 cleanUp(); 15233 removeDexFiles(allCodePaths, instructionSets); 15234 } 15235 15236 boolean doPostDeleteLI(boolean delete) { 15237 // XXX err, shouldn't we respect the delete flag? 15238 cleanUpResourcesLI(); 15239 return true; 15240 } 15241 } 15242 15243 private boolean isAsecExternal(String cid) { 15244 final String asecPath = PackageHelper.getSdFilesystem(cid); 15245 return !asecPath.startsWith(mAsecInternalPath); 15246 } 15247 15248 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15249 PackageManagerException { 15250 if (copyRet < 0) { 15251 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15252 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15253 throw new PackageManagerException(copyRet, message); 15254 } 15255 } 15256 } 15257 15258 /** 15259 * Extract the StorageManagerService "container ID" from the full code path of an 15260 * .apk. 15261 */ 15262 static String cidFromCodePath(String fullCodePath) { 15263 int eidx = fullCodePath.lastIndexOf("/"); 15264 String subStr1 = fullCodePath.substring(0, eidx); 15265 int sidx = subStr1.lastIndexOf("/"); 15266 return subStr1.substring(sidx+1, eidx); 15267 } 15268 15269 /** 15270 * Logic to handle installation of ASEC applications, including copying and 15271 * renaming logic. 15272 */ 15273 class AsecInstallArgs extends InstallArgs { 15274 static final String RES_FILE_NAME = "pkg.apk"; 15275 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15276 15277 String cid; 15278 String packagePath; 15279 String resourcePath; 15280 15281 /** New install */ 15282 AsecInstallArgs(InstallParams params) { 15283 super(params.origin, params.move, params.observer, params.installFlags, 15284 params.installerPackageName, params.volumeUuid, 15285 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15286 params.grantedRuntimePermissions, 15287 params.traceMethod, params.traceCookie, params.certificates, 15288 params.installReason); 15289 } 15290 15291 /** Existing install */ 15292 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15293 boolean isExternal, boolean isForwardLocked) { 15294 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15295 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15296 instructionSets, null, null, null, 0, null /*certificates*/, 15297 PackageManager.INSTALL_REASON_UNKNOWN); 15298 // Hackily pretend we're still looking at a full code path 15299 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15300 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15301 } 15302 15303 // Extract cid from fullCodePath 15304 int eidx = fullCodePath.lastIndexOf("/"); 15305 String subStr1 = fullCodePath.substring(0, eidx); 15306 int sidx = subStr1.lastIndexOf("/"); 15307 cid = subStr1.substring(sidx+1, eidx); 15308 setMountPath(subStr1); 15309 } 15310 15311 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15312 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15313 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15314 instructionSets, null, null, null, 0, null /*certificates*/, 15315 PackageManager.INSTALL_REASON_UNKNOWN); 15316 this.cid = cid; 15317 setMountPath(PackageHelper.getSdDir(cid)); 15318 } 15319 15320 void createCopyFile() { 15321 cid = mInstallerService.allocateExternalStageCidLegacy(); 15322 } 15323 15324 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15325 if (origin.staged && origin.cid != null) { 15326 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15327 cid = origin.cid; 15328 setMountPath(PackageHelper.getSdDir(cid)); 15329 return PackageManager.INSTALL_SUCCEEDED; 15330 } 15331 15332 if (temp) { 15333 createCopyFile(); 15334 } else { 15335 /* 15336 * Pre-emptively destroy the container since it's destroyed if 15337 * copying fails due to it existing anyway. 15338 */ 15339 PackageHelper.destroySdDir(cid); 15340 } 15341 15342 final String newMountPath = imcs.copyPackageToContainer( 15343 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15344 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15345 15346 if (newMountPath != null) { 15347 setMountPath(newMountPath); 15348 return PackageManager.INSTALL_SUCCEEDED; 15349 } else { 15350 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15351 } 15352 } 15353 15354 @Override 15355 String getCodePath() { 15356 return packagePath; 15357 } 15358 15359 @Override 15360 String getResourcePath() { 15361 return resourcePath; 15362 } 15363 15364 int doPreInstall(int status) { 15365 if (status != PackageManager.INSTALL_SUCCEEDED) { 15366 // Destroy container 15367 PackageHelper.destroySdDir(cid); 15368 } else { 15369 boolean mounted = PackageHelper.isContainerMounted(cid); 15370 if (!mounted) { 15371 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15372 Process.SYSTEM_UID); 15373 if (newMountPath != null) { 15374 setMountPath(newMountPath); 15375 } else { 15376 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15377 } 15378 } 15379 } 15380 return status; 15381 } 15382 15383 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15384 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15385 String newMountPath = null; 15386 if (PackageHelper.isContainerMounted(cid)) { 15387 // Unmount the container 15388 if (!PackageHelper.unMountSdDir(cid)) { 15389 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15390 return false; 15391 } 15392 } 15393 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15394 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15395 " which might be stale. Will try to clean up."); 15396 // Clean up the stale container and proceed to recreate. 15397 if (!PackageHelper.destroySdDir(newCacheId)) { 15398 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15399 return false; 15400 } 15401 // Successfully cleaned up stale container. Try to rename again. 15402 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15403 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15404 + " inspite of cleaning it up."); 15405 return false; 15406 } 15407 } 15408 if (!PackageHelper.isContainerMounted(newCacheId)) { 15409 Slog.w(TAG, "Mounting container " + newCacheId); 15410 newMountPath = PackageHelper.mountSdDir(newCacheId, 15411 getEncryptKey(), Process.SYSTEM_UID); 15412 } else { 15413 newMountPath = PackageHelper.getSdDir(newCacheId); 15414 } 15415 if (newMountPath == null) { 15416 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15417 return false; 15418 } 15419 Log.i(TAG, "Succesfully renamed " + cid + 15420 " to " + newCacheId + 15421 " at new path: " + newMountPath); 15422 cid = newCacheId; 15423 15424 final File beforeCodeFile = new File(packagePath); 15425 setMountPath(newMountPath); 15426 final File afterCodeFile = new File(packagePath); 15427 15428 // Reflect the rename in scanned details 15429 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15430 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15431 afterCodeFile, pkg.baseCodePath)); 15432 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15433 afterCodeFile, pkg.splitCodePaths)); 15434 15435 // Reflect the rename in app info 15436 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15437 pkg.setApplicationInfoCodePath(pkg.codePath); 15438 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15439 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15440 pkg.setApplicationInfoResourcePath(pkg.codePath); 15441 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15442 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15443 15444 return true; 15445 } 15446 15447 private void setMountPath(String mountPath) { 15448 final File mountFile = new File(mountPath); 15449 15450 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15451 if (monolithicFile.exists()) { 15452 packagePath = monolithicFile.getAbsolutePath(); 15453 if (isFwdLocked()) { 15454 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15455 } else { 15456 resourcePath = packagePath; 15457 } 15458 } else { 15459 packagePath = mountFile.getAbsolutePath(); 15460 resourcePath = packagePath; 15461 } 15462 } 15463 15464 int doPostInstall(int status, int uid) { 15465 if (status != PackageManager.INSTALL_SUCCEEDED) { 15466 cleanUp(); 15467 } else { 15468 final int groupOwner; 15469 final String protectedFile; 15470 if (isFwdLocked()) { 15471 groupOwner = UserHandle.getSharedAppGid(uid); 15472 protectedFile = RES_FILE_NAME; 15473 } else { 15474 groupOwner = -1; 15475 protectedFile = null; 15476 } 15477 15478 if (uid < Process.FIRST_APPLICATION_UID 15479 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15480 Slog.e(TAG, "Failed to finalize " + cid); 15481 PackageHelper.destroySdDir(cid); 15482 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15483 } 15484 15485 boolean mounted = PackageHelper.isContainerMounted(cid); 15486 if (!mounted) { 15487 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15488 } 15489 } 15490 return status; 15491 } 15492 15493 private void cleanUp() { 15494 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15495 15496 // Destroy secure container 15497 PackageHelper.destroySdDir(cid); 15498 } 15499 15500 private List<String> getAllCodePaths() { 15501 final File codeFile = new File(getCodePath()); 15502 if (codeFile != null && codeFile.exists()) { 15503 try { 15504 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15505 return pkg.getAllCodePaths(); 15506 } catch (PackageParserException e) { 15507 // Ignored; we tried our best 15508 } 15509 } 15510 return Collections.EMPTY_LIST; 15511 } 15512 15513 void cleanUpResourcesLI() { 15514 // Enumerate all code paths before deleting 15515 cleanUpResourcesLI(getAllCodePaths()); 15516 } 15517 15518 private void cleanUpResourcesLI(List<String> allCodePaths) { 15519 cleanUp(); 15520 removeDexFiles(allCodePaths, instructionSets); 15521 } 15522 15523 String getPackageName() { 15524 return getAsecPackageName(cid); 15525 } 15526 15527 boolean doPostDeleteLI(boolean delete) { 15528 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15529 final List<String> allCodePaths = getAllCodePaths(); 15530 boolean mounted = PackageHelper.isContainerMounted(cid); 15531 if (mounted) { 15532 // Unmount first 15533 if (PackageHelper.unMountSdDir(cid)) { 15534 mounted = false; 15535 } 15536 } 15537 if (!mounted && delete) { 15538 cleanUpResourcesLI(allCodePaths); 15539 } 15540 return !mounted; 15541 } 15542 15543 @Override 15544 int doPreCopy() { 15545 if (isFwdLocked()) { 15546 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15547 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15548 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15549 } 15550 } 15551 15552 return PackageManager.INSTALL_SUCCEEDED; 15553 } 15554 15555 @Override 15556 int doPostCopy(int uid) { 15557 if (isFwdLocked()) { 15558 if (uid < Process.FIRST_APPLICATION_UID 15559 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15560 RES_FILE_NAME)) { 15561 Slog.e(TAG, "Failed to finalize " + cid); 15562 PackageHelper.destroySdDir(cid); 15563 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15564 } 15565 } 15566 15567 return PackageManager.INSTALL_SUCCEEDED; 15568 } 15569 } 15570 15571 /** 15572 * Logic to handle movement of existing installed applications. 15573 */ 15574 class MoveInstallArgs extends InstallArgs { 15575 private File codeFile; 15576 private File resourceFile; 15577 15578 /** New install */ 15579 MoveInstallArgs(InstallParams params) { 15580 super(params.origin, params.move, params.observer, params.installFlags, 15581 params.installerPackageName, params.volumeUuid, 15582 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15583 params.grantedRuntimePermissions, 15584 params.traceMethod, params.traceCookie, params.certificates, 15585 params.installReason); 15586 } 15587 15588 int copyApk(IMediaContainerService imcs, boolean temp) { 15589 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15590 + move.fromUuid + " to " + move.toUuid); 15591 synchronized (mInstaller) { 15592 try { 15593 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15594 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15595 } catch (InstallerException e) { 15596 Slog.w(TAG, "Failed to move app", e); 15597 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15598 } 15599 } 15600 15601 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15602 resourceFile = codeFile; 15603 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15604 15605 return PackageManager.INSTALL_SUCCEEDED; 15606 } 15607 15608 int doPreInstall(int status) { 15609 if (status != PackageManager.INSTALL_SUCCEEDED) { 15610 cleanUp(move.toUuid); 15611 } 15612 return status; 15613 } 15614 15615 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15616 if (status != PackageManager.INSTALL_SUCCEEDED) { 15617 cleanUp(move.toUuid); 15618 return false; 15619 } 15620 15621 // Reflect the move in app info 15622 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15623 pkg.setApplicationInfoCodePath(pkg.codePath); 15624 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15625 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15626 pkg.setApplicationInfoResourcePath(pkg.codePath); 15627 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15628 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15629 15630 return true; 15631 } 15632 15633 int doPostInstall(int status, int uid) { 15634 if (status == PackageManager.INSTALL_SUCCEEDED) { 15635 cleanUp(move.fromUuid); 15636 } else { 15637 cleanUp(move.toUuid); 15638 } 15639 return status; 15640 } 15641 15642 @Override 15643 String getCodePath() { 15644 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15645 } 15646 15647 @Override 15648 String getResourcePath() { 15649 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15650 } 15651 15652 private boolean cleanUp(String volumeUuid) { 15653 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15654 move.dataAppName); 15655 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15656 final int[] userIds = sUserManager.getUserIds(); 15657 synchronized (mInstallLock) { 15658 // Clean up both app data and code 15659 // All package moves are frozen until finished 15660 for (int userId : userIds) { 15661 try { 15662 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15663 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15664 } catch (InstallerException e) { 15665 Slog.w(TAG, String.valueOf(e)); 15666 } 15667 } 15668 removeCodePathLI(codeFile); 15669 } 15670 return true; 15671 } 15672 15673 void cleanUpResourcesLI() { 15674 throw new UnsupportedOperationException(); 15675 } 15676 15677 boolean doPostDeleteLI(boolean delete) { 15678 throw new UnsupportedOperationException(); 15679 } 15680 } 15681 15682 static String getAsecPackageName(String packageCid) { 15683 int idx = packageCid.lastIndexOf("-"); 15684 if (idx == -1) { 15685 return packageCid; 15686 } 15687 return packageCid.substring(0, idx); 15688 } 15689 15690 // Utility method used to create code paths based on package name and available index. 15691 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15692 String idxStr = ""; 15693 int idx = 1; 15694 // Fall back to default value of idx=1 if prefix is not 15695 // part of oldCodePath 15696 if (oldCodePath != null) { 15697 String subStr = oldCodePath; 15698 // Drop the suffix right away 15699 if (suffix != null && subStr.endsWith(suffix)) { 15700 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15701 } 15702 // If oldCodePath already contains prefix find out the 15703 // ending index to either increment or decrement. 15704 int sidx = subStr.lastIndexOf(prefix); 15705 if (sidx != -1) { 15706 subStr = subStr.substring(sidx + prefix.length()); 15707 if (subStr != null) { 15708 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15709 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15710 } 15711 try { 15712 idx = Integer.parseInt(subStr); 15713 if (idx <= 1) { 15714 idx++; 15715 } else { 15716 idx--; 15717 } 15718 } catch(NumberFormatException e) { 15719 } 15720 } 15721 } 15722 } 15723 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15724 return prefix + idxStr; 15725 } 15726 15727 private File getNextCodePath(File targetDir, String packageName) { 15728 File result; 15729 SecureRandom random = new SecureRandom(); 15730 byte[] bytes = new byte[16]; 15731 do { 15732 random.nextBytes(bytes); 15733 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15734 result = new File(targetDir, packageName + "-" + suffix); 15735 } while (result.exists()); 15736 return result; 15737 } 15738 15739 // Utility method that returns the relative package path with respect 15740 // to the installation directory. Like say for /data/data/com.test-1.apk 15741 // string com.test-1 is returned. 15742 static String deriveCodePathName(String codePath) { 15743 if (codePath == null) { 15744 return null; 15745 } 15746 final File codeFile = new File(codePath); 15747 final String name = codeFile.getName(); 15748 if (codeFile.isDirectory()) { 15749 return name; 15750 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15751 final int lastDot = name.lastIndexOf('.'); 15752 return name.substring(0, lastDot); 15753 } else { 15754 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15755 return null; 15756 } 15757 } 15758 15759 static class PackageInstalledInfo { 15760 String name; 15761 int uid; 15762 // The set of users that originally had this package installed. 15763 int[] origUsers; 15764 // The set of users that now have this package installed. 15765 int[] newUsers; 15766 PackageParser.Package pkg; 15767 int returnCode; 15768 String returnMsg; 15769 PackageRemovedInfo removedInfo; 15770 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15771 15772 public void setError(int code, String msg) { 15773 setReturnCode(code); 15774 setReturnMessage(msg); 15775 Slog.w(TAG, msg); 15776 } 15777 15778 public void setError(String msg, PackageParserException e) { 15779 setReturnCode(e.error); 15780 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15781 Slog.w(TAG, msg, e); 15782 } 15783 15784 public void setError(String msg, PackageManagerException e) { 15785 returnCode = e.error; 15786 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15787 Slog.w(TAG, msg, e); 15788 } 15789 15790 public void setReturnCode(int returnCode) { 15791 this.returnCode = returnCode; 15792 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15793 for (int i = 0; i < childCount; i++) { 15794 addedChildPackages.valueAt(i).returnCode = returnCode; 15795 } 15796 } 15797 15798 private void setReturnMessage(String returnMsg) { 15799 this.returnMsg = returnMsg; 15800 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15801 for (int i = 0; i < childCount; i++) { 15802 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15803 } 15804 } 15805 15806 // In some error cases we want to convey more info back to the observer 15807 String origPackage; 15808 String origPermission; 15809 } 15810 15811 /* 15812 * Install a non-existing package. 15813 */ 15814 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15815 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15816 PackageInstalledInfo res, int installReason) { 15817 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15818 15819 // Remember this for later, in case we need to rollback this install 15820 String pkgName = pkg.packageName; 15821 15822 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15823 15824 synchronized(mPackages) { 15825 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15826 if (renamedPackage != null) { 15827 // A package with the same name is already installed, though 15828 // it has been renamed to an older name. The package we 15829 // are trying to install should be installed as an update to 15830 // the existing one, but that has not been requested, so bail. 15831 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15832 + " without first uninstalling package running as " 15833 + renamedPackage); 15834 return; 15835 } 15836 if (mPackages.containsKey(pkgName)) { 15837 // Don't allow installation over an existing package with the same name. 15838 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15839 + " without first uninstalling."); 15840 return; 15841 } 15842 } 15843 15844 try { 15845 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15846 System.currentTimeMillis(), user); 15847 15848 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15849 15850 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15851 prepareAppDataAfterInstallLIF(newPackage); 15852 15853 } else { 15854 // Remove package from internal structures, but keep around any 15855 // data that might have already existed 15856 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15857 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15858 } 15859 } catch (PackageManagerException e) { 15860 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15861 } 15862 15863 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15864 } 15865 15866 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15867 // Can't rotate keys during boot or if sharedUser. 15868 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15869 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15870 return false; 15871 } 15872 // app is using upgradeKeySets; make sure all are valid 15873 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15874 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15875 for (int i = 0; i < upgradeKeySets.length; i++) { 15876 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15877 Slog.wtf(TAG, "Package " 15878 + (oldPs.name != null ? oldPs.name : "<null>") 15879 + " contains upgrade-key-set reference to unknown key-set: " 15880 + upgradeKeySets[i] 15881 + " reverting to signatures check."); 15882 return false; 15883 } 15884 } 15885 return true; 15886 } 15887 15888 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15889 // Upgrade keysets are being used. Determine if new package has a superset of the 15890 // required keys. 15891 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15892 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15893 for (int i = 0; i < upgradeKeySets.length; i++) { 15894 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15895 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15896 return true; 15897 } 15898 } 15899 return false; 15900 } 15901 15902 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15903 try (DigestInputStream digestStream = 15904 new DigestInputStream(new FileInputStream(file), digest)) { 15905 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15906 } 15907 } 15908 15909 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15910 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15911 int installReason) { 15912 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15913 15914 final PackageParser.Package oldPackage; 15915 final String pkgName = pkg.packageName; 15916 final int[] allUsers; 15917 final int[] installedUsers; 15918 15919 synchronized(mPackages) { 15920 oldPackage = mPackages.get(pkgName); 15921 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15922 15923 // don't allow upgrade to target a release SDK from a pre-release SDK 15924 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15925 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15926 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15927 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15928 if (oldTargetsPreRelease 15929 && !newTargetsPreRelease 15930 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15931 Slog.w(TAG, "Can't install package targeting released sdk"); 15932 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15933 return; 15934 } 15935 15936 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15937 15938 // don't allow an upgrade from full to ephemeral 15939 if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) { 15940 // can't downgrade from full to instant 15941 Slog.w(TAG, "Can't replace app with instant app: " + pkgName); 15942 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15943 return; 15944 } 15945 15946 // verify signatures are valid 15947 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15948 if (!checkUpgradeKeySetLP(ps, pkg)) { 15949 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15950 "New package not signed by keys specified by upgrade-keysets: " 15951 + pkgName); 15952 return; 15953 } 15954 } else { 15955 // default to original signature matching 15956 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15957 != PackageManager.SIGNATURE_MATCH) { 15958 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15959 "New package has a different signature: " + pkgName); 15960 return; 15961 } 15962 } 15963 15964 // don't allow a system upgrade unless the upgrade hash matches 15965 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15966 byte[] digestBytes = null; 15967 try { 15968 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15969 updateDigest(digest, new File(pkg.baseCodePath)); 15970 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15971 for (String path : pkg.splitCodePaths) { 15972 updateDigest(digest, new File(path)); 15973 } 15974 } 15975 digestBytes = digest.digest(); 15976 } catch (NoSuchAlgorithmException | IOException e) { 15977 res.setError(INSTALL_FAILED_INVALID_APK, 15978 "Could not compute hash: " + pkgName); 15979 return; 15980 } 15981 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15982 res.setError(INSTALL_FAILED_INVALID_APK, 15983 "New package fails restrict-update check: " + pkgName); 15984 return; 15985 } 15986 // retain upgrade restriction 15987 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15988 } 15989 15990 // Check for shared user id changes 15991 String invalidPackageName = 15992 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15993 if (invalidPackageName != null) { 15994 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15995 "Package " + invalidPackageName + " tried to change user " 15996 + oldPackage.mSharedUserId); 15997 return; 15998 } 15999 16000 // In case of rollback, remember per-user/profile install state 16001 allUsers = sUserManager.getUserIds(); 16002 installedUsers = ps.queryInstalledUsers(allUsers, true); 16003 } 16004 16005 // Update what is removed 16006 res.removedInfo = new PackageRemovedInfo(); 16007 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16008 res.removedInfo.removedPackage = oldPackage.packageName; 16009 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16010 res.removedInfo.isUpdate = true; 16011 res.removedInfo.origUsers = installedUsers; 16012 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 16013 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16014 for (int i = 0; i < installedUsers.length; i++) { 16015 final int userId = installedUsers[i]; 16016 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16017 } 16018 16019 final int childCount = (oldPackage.childPackages != null) 16020 ? oldPackage.childPackages.size() : 0; 16021 for (int i = 0; i < childCount; i++) { 16022 boolean childPackageUpdated = false; 16023 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16024 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16025 if (res.addedChildPackages != null) { 16026 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16027 if (childRes != null) { 16028 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16029 childRes.removedInfo.removedPackage = childPkg.packageName; 16030 childRes.removedInfo.isUpdate = true; 16031 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16032 childPackageUpdated = true; 16033 } 16034 } 16035 if (!childPackageUpdated) { 16036 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16037 childRemovedRes.removedPackage = childPkg.packageName; 16038 childRemovedRes.isUpdate = false; 16039 childRemovedRes.dataRemoved = true; 16040 synchronized (mPackages) { 16041 if (childPs != null) { 16042 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16043 } 16044 } 16045 if (res.removedInfo.removedChildPackages == null) { 16046 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16047 } 16048 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16049 } 16050 } 16051 16052 boolean sysPkg = (isSystemApp(oldPackage)); 16053 if (sysPkg) { 16054 // Set the system/privileged flags as needed 16055 final boolean privileged = 16056 (oldPackage.applicationInfo.privateFlags 16057 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16058 final int systemPolicyFlags = policyFlags 16059 | PackageParser.PARSE_IS_SYSTEM 16060 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16061 16062 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16063 user, allUsers, installerPackageName, res, installReason); 16064 } else { 16065 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16066 user, allUsers, installerPackageName, res, installReason); 16067 } 16068 } 16069 16070 public List<String> getPreviousCodePaths(String packageName) { 16071 final PackageSetting ps = mSettings.mPackages.get(packageName); 16072 final List<String> result = new ArrayList<String>(); 16073 if (ps != null && ps.oldCodePaths != null) { 16074 result.addAll(ps.oldCodePaths); 16075 } 16076 return result; 16077 } 16078 16079 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16080 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16081 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16082 int installReason) { 16083 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16084 + deletedPackage); 16085 16086 String pkgName = deletedPackage.packageName; 16087 boolean deletedPkg = true; 16088 boolean addedPkg = false; 16089 boolean updatedSettings = false; 16090 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16091 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16092 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16093 16094 final long origUpdateTime = (pkg.mExtras != null) 16095 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16096 16097 // First delete the existing package while retaining the data directory 16098 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16099 res.removedInfo, true, pkg)) { 16100 // If the existing package wasn't successfully deleted 16101 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16102 deletedPkg = false; 16103 } else { 16104 // Successfully deleted the old package; proceed with replace. 16105 16106 // If deleted package lived in a container, give users a chance to 16107 // relinquish resources before killing. 16108 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16109 if (DEBUG_INSTALL) { 16110 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16111 } 16112 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16113 final ArrayList<String> pkgList = new ArrayList<String>(1); 16114 pkgList.add(deletedPackage.applicationInfo.packageName); 16115 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16116 } 16117 16118 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16119 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16120 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16121 16122 try { 16123 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16124 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16125 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16126 installReason); 16127 16128 // Update the in-memory copy of the previous code paths. 16129 PackageSetting ps = mSettings.mPackages.get(pkgName); 16130 if (!killApp) { 16131 if (ps.oldCodePaths == null) { 16132 ps.oldCodePaths = new ArraySet<>(); 16133 } 16134 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16135 if (deletedPackage.splitCodePaths != null) { 16136 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16137 } 16138 } else { 16139 ps.oldCodePaths = null; 16140 } 16141 if (ps.childPackageNames != null) { 16142 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16143 final String childPkgName = ps.childPackageNames.get(i); 16144 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16145 childPs.oldCodePaths = ps.oldCodePaths; 16146 } 16147 } 16148 // set instant app status, but, only if it's explicitly specified 16149 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16150 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16151 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16152 prepareAppDataAfterInstallLIF(newPackage); 16153 addedPkg = true; 16154 } catch (PackageManagerException e) { 16155 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16156 } 16157 } 16158 16159 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16160 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16161 16162 // Revert all internal state mutations and added folders for the failed install 16163 if (addedPkg) { 16164 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16165 res.removedInfo, true, null); 16166 } 16167 16168 // Restore the old package 16169 if (deletedPkg) { 16170 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16171 File restoreFile = new File(deletedPackage.codePath); 16172 // Parse old package 16173 boolean oldExternal = isExternal(deletedPackage); 16174 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16175 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16176 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16177 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16178 try { 16179 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16180 null); 16181 } catch (PackageManagerException e) { 16182 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16183 + e.getMessage()); 16184 return; 16185 } 16186 16187 synchronized (mPackages) { 16188 // Ensure the installer package name up to date 16189 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16190 16191 // Update permissions for restored package 16192 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16193 16194 mSettings.writeLPr(); 16195 } 16196 16197 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16198 } 16199 } else { 16200 synchronized (mPackages) { 16201 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16202 if (ps != null) { 16203 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16204 if (res.removedInfo.removedChildPackages != null) { 16205 final int childCount = res.removedInfo.removedChildPackages.size(); 16206 // Iterate in reverse as we may modify the collection 16207 for (int i = childCount - 1; i >= 0; i--) { 16208 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16209 if (res.addedChildPackages.containsKey(childPackageName)) { 16210 res.removedInfo.removedChildPackages.removeAt(i); 16211 } else { 16212 PackageRemovedInfo childInfo = res.removedInfo 16213 .removedChildPackages.valueAt(i); 16214 childInfo.removedForAllUsers = mPackages.get( 16215 childInfo.removedPackage) == null; 16216 } 16217 } 16218 } 16219 } 16220 } 16221 } 16222 } 16223 16224 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16225 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16226 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16227 int installReason) { 16228 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16229 + ", old=" + deletedPackage); 16230 16231 final boolean disabledSystem; 16232 16233 // Remove existing system package 16234 removePackageLI(deletedPackage, true); 16235 16236 synchronized (mPackages) { 16237 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16238 } 16239 if (!disabledSystem) { 16240 // We didn't need to disable the .apk as a current system package, 16241 // which means we are replacing another update that is already 16242 // installed. We need to make sure to delete the older one's .apk. 16243 res.removedInfo.args = createInstallArgsForExisting(0, 16244 deletedPackage.applicationInfo.getCodePath(), 16245 deletedPackage.applicationInfo.getResourcePath(), 16246 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16247 } else { 16248 res.removedInfo.args = null; 16249 } 16250 16251 // Successfully disabled the old package. Now proceed with re-installation 16252 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16253 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16254 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16255 16256 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16257 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16258 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16259 16260 PackageParser.Package newPackage = null; 16261 try { 16262 // Add the package to the internal data structures 16263 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16264 16265 // Set the update and install times 16266 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16267 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16268 System.currentTimeMillis()); 16269 16270 // Update the package dynamic state if succeeded 16271 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16272 // Now that the install succeeded make sure we remove data 16273 // directories for any child package the update removed. 16274 final int deletedChildCount = (deletedPackage.childPackages != null) 16275 ? deletedPackage.childPackages.size() : 0; 16276 final int newChildCount = (newPackage.childPackages != null) 16277 ? newPackage.childPackages.size() : 0; 16278 for (int i = 0; i < deletedChildCount; i++) { 16279 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16280 boolean childPackageDeleted = true; 16281 for (int j = 0; j < newChildCount; j++) { 16282 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16283 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16284 childPackageDeleted = false; 16285 break; 16286 } 16287 } 16288 if (childPackageDeleted) { 16289 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16290 deletedChildPkg.packageName); 16291 if (ps != null && res.removedInfo.removedChildPackages != null) { 16292 PackageRemovedInfo removedChildRes = res.removedInfo 16293 .removedChildPackages.get(deletedChildPkg.packageName); 16294 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16295 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16296 } 16297 } 16298 } 16299 16300 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16301 installReason); 16302 prepareAppDataAfterInstallLIF(newPackage); 16303 } 16304 } catch (PackageManagerException e) { 16305 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16306 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16307 } 16308 16309 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16310 // Re installation failed. Restore old information 16311 // Remove new pkg information 16312 if (newPackage != null) { 16313 removeInstalledPackageLI(newPackage, true); 16314 } 16315 // Add back the old system package 16316 try { 16317 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16318 } catch (PackageManagerException e) { 16319 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16320 } 16321 16322 synchronized (mPackages) { 16323 if (disabledSystem) { 16324 enableSystemPackageLPw(deletedPackage); 16325 } 16326 16327 // Ensure the installer package name up to date 16328 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16329 16330 // Update permissions for restored package 16331 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16332 16333 mSettings.writeLPr(); 16334 } 16335 16336 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16337 + " after failed upgrade"); 16338 } 16339 } 16340 16341 /** 16342 * Checks whether the parent or any of the child packages have a change shared 16343 * user. For a package to be a valid update the shred users of the parent and 16344 * the children should match. We may later support changing child shared users. 16345 * @param oldPkg The updated package. 16346 * @param newPkg The update package. 16347 * @return The shared user that change between the versions. 16348 */ 16349 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16350 PackageParser.Package newPkg) { 16351 // Check parent shared user 16352 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16353 return newPkg.packageName; 16354 } 16355 // Check child shared users 16356 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16357 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16358 for (int i = 0; i < newChildCount; i++) { 16359 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16360 // If this child was present, did it have the same shared user? 16361 for (int j = 0; j < oldChildCount; j++) { 16362 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16363 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16364 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16365 return newChildPkg.packageName; 16366 } 16367 } 16368 } 16369 return null; 16370 } 16371 16372 private void removeNativeBinariesLI(PackageSetting ps) { 16373 // Remove the lib path for the parent package 16374 if (ps != null) { 16375 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16376 // Remove the lib path for the child packages 16377 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16378 for (int i = 0; i < childCount; i++) { 16379 PackageSetting childPs = null; 16380 synchronized (mPackages) { 16381 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16382 } 16383 if (childPs != null) { 16384 NativeLibraryHelper.removeNativeBinariesLI(childPs 16385 .legacyNativeLibraryPathString); 16386 } 16387 } 16388 } 16389 } 16390 16391 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16392 // Enable the parent package 16393 mSettings.enableSystemPackageLPw(pkg.packageName); 16394 // Enable the child packages 16395 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16396 for (int i = 0; i < childCount; i++) { 16397 PackageParser.Package childPkg = pkg.childPackages.get(i); 16398 mSettings.enableSystemPackageLPw(childPkg.packageName); 16399 } 16400 } 16401 16402 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16403 PackageParser.Package newPkg) { 16404 // Disable the parent package (parent always replaced) 16405 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16406 // Disable the child packages 16407 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16408 for (int i = 0; i < childCount; i++) { 16409 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16410 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16411 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16412 } 16413 return disabled; 16414 } 16415 16416 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16417 String installerPackageName) { 16418 // Enable the parent package 16419 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16420 // Enable the child packages 16421 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16422 for (int i = 0; i < childCount; i++) { 16423 PackageParser.Package childPkg = pkg.childPackages.get(i); 16424 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16425 } 16426 } 16427 16428 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16429 // Collect all used permissions in the UID 16430 ArraySet<String> usedPermissions = new ArraySet<>(); 16431 final int packageCount = su.packages.size(); 16432 for (int i = 0; i < packageCount; i++) { 16433 PackageSetting ps = su.packages.valueAt(i); 16434 if (ps.pkg == null) { 16435 continue; 16436 } 16437 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16438 for (int j = 0; j < requestedPermCount; j++) { 16439 String permission = ps.pkg.requestedPermissions.get(j); 16440 BasePermission bp = mSettings.mPermissions.get(permission); 16441 if (bp != null) { 16442 usedPermissions.add(permission); 16443 } 16444 } 16445 } 16446 16447 PermissionsState permissionsState = su.getPermissionsState(); 16448 // Prune install permissions 16449 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16450 final int installPermCount = installPermStates.size(); 16451 for (int i = installPermCount - 1; i >= 0; i--) { 16452 PermissionState permissionState = installPermStates.get(i); 16453 if (!usedPermissions.contains(permissionState.getName())) { 16454 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16455 if (bp != null) { 16456 permissionsState.revokeInstallPermission(bp); 16457 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16458 PackageManager.MASK_PERMISSION_FLAGS, 0); 16459 } 16460 } 16461 } 16462 16463 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16464 16465 // Prune runtime permissions 16466 for (int userId : allUserIds) { 16467 List<PermissionState> runtimePermStates = permissionsState 16468 .getRuntimePermissionStates(userId); 16469 final int runtimePermCount = runtimePermStates.size(); 16470 for (int i = runtimePermCount - 1; i >= 0; i--) { 16471 PermissionState permissionState = runtimePermStates.get(i); 16472 if (!usedPermissions.contains(permissionState.getName())) { 16473 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16474 if (bp != null) { 16475 permissionsState.revokeRuntimePermission(bp, userId); 16476 permissionsState.updatePermissionFlags(bp, userId, 16477 PackageManager.MASK_PERMISSION_FLAGS, 0); 16478 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16479 runtimePermissionChangedUserIds, userId); 16480 } 16481 } 16482 } 16483 } 16484 16485 return runtimePermissionChangedUserIds; 16486 } 16487 16488 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16489 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16490 // Update the parent package setting 16491 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16492 res, user, installReason); 16493 // Update the child packages setting 16494 final int childCount = (newPackage.childPackages != null) 16495 ? newPackage.childPackages.size() : 0; 16496 for (int i = 0; i < childCount; i++) { 16497 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16498 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16499 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16500 childRes.origUsers, childRes, user, installReason); 16501 } 16502 } 16503 16504 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16505 String installerPackageName, int[] allUsers, int[] installedForUsers, 16506 PackageInstalledInfo res, UserHandle user, int installReason) { 16507 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16508 16509 String pkgName = newPackage.packageName; 16510 synchronized (mPackages) { 16511 //write settings. the installStatus will be incomplete at this stage. 16512 //note that the new package setting would have already been 16513 //added to mPackages. It hasn't been persisted yet. 16514 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16515 // TODO: Remove this write? It's also written at the end of this method 16516 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16517 mSettings.writeLPr(); 16518 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16519 } 16520 16521 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16522 synchronized (mPackages) { 16523 updatePermissionsLPw(newPackage.packageName, newPackage, 16524 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16525 ? UPDATE_PERMISSIONS_ALL : 0)); 16526 // For system-bundled packages, we assume that installing an upgraded version 16527 // of the package implies that the user actually wants to run that new code, 16528 // so we enable the package. 16529 PackageSetting ps = mSettings.mPackages.get(pkgName); 16530 final int userId = user.getIdentifier(); 16531 if (ps != null) { 16532 if (isSystemApp(newPackage)) { 16533 if (DEBUG_INSTALL) { 16534 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16535 } 16536 // Enable system package for requested users 16537 if (res.origUsers != null) { 16538 for (int origUserId : res.origUsers) { 16539 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16540 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16541 origUserId, installerPackageName); 16542 } 16543 } 16544 } 16545 // Also convey the prior install/uninstall state 16546 if (allUsers != null && installedForUsers != null) { 16547 for (int currentUserId : allUsers) { 16548 final boolean installed = ArrayUtils.contains( 16549 installedForUsers, currentUserId); 16550 if (DEBUG_INSTALL) { 16551 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16552 } 16553 ps.setInstalled(installed, currentUserId); 16554 } 16555 // these install state changes will be persisted in the 16556 // upcoming call to mSettings.writeLPr(). 16557 } 16558 } 16559 // It's implied that when a user requests installation, they want the app to be 16560 // installed and enabled. 16561 if (userId != UserHandle.USER_ALL) { 16562 ps.setInstalled(true, userId); 16563 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16564 } 16565 16566 // When replacing an existing package, preserve the original install reason for all 16567 // users that had the package installed before. 16568 final Set<Integer> previousUserIds = new ArraySet<>(); 16569 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16570 final int installReasonCount = res.removedInfo.installReasons.size(); 16571 for (int i = 0; i < installReasonCount; i++) { 16572 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16573 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16574 ps.setInstallReason(previousInstallReason, previousUserId); 16575 previousUserIds.add(previousUserId); 16576 } 16577 } 16578 16579 // Set install reason for users that are having the package newly installed. 16580 if (userId == UserHandle.USER_ALL) { 16581 for (int currentUserId : sUserManager.getUserIds()) { 16582 if (!previousUserIds.contains(currentUserId)) { 16583 ps.setInstallReason(installReason, currentUserId); 16584 } 16585 } 16586 } else if (!previousUserIds.contains(userId)) { 16587 ps.setInstallReason(installReason, userId); 16588 } 16589 mSettings.writeKernelMappingLPr(ps); 16590 } 16591 res.name = pkgName; 16592 res.uid = newPackage.applicationInfo.uid; 16593 res.pkg = newPackage; 16594 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16595 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16596 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16597 //to update install status 16598 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16599 mSettings.writeLPr(); 16600 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16601 } 16602 16603 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16604 } 16605 16606 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16607 try { 16608 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16609 installPackageLI(args, res); 16610 } finally { 16611 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16612 } 16613 } 16614 16615 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16616 final int installFlags = args.installFlags; 16617 final String installerPackageName = args.installerPackageName; 16618 final String volumeUuid = args.volumeUuid; 16619 final File tmpPackageFile = new File(args.getCodePath()); 16620 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16621 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16622 || (args.volumeUuid != null)); 16623 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16624 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16625 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16626 boolean replace = false; 16627 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16628 if (args.move != null) { 16629 // moving a complete application; perform an initial scan on the new install location 16630 scanFlags |= SCAN_INITIAL; 16631 } 16632 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16633 scanFlags |= SCAN_DONT_KILL_APP; 16634 } 16635 if (instantApp) { 16636 scanFlags |= SCAN_AS_INSTANT_APP; 16637 } 16638 if (fullApp) { 16639 scanFlags |= SCAN_AS_FULL_APP; 16640 } 16641 16642 // Result object to be returned 16643 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16644 16645 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16646 16647 // Sanity check 16648 if (instantApp && (forwardLocked || onExternal)) { 16649 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16650 + " external=" + onExternal); 16651 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16652 return; 16653 } 16654 16655 // Retrieve PackageSettings and parse package 16656 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16657 | PackageParser.PARSE_ENFORCE_CODE 16658 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16659 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16660 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16661 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16662 PackageParser pp = new PackageParser(); 16663 pp.setSeparateProcesses(mSeparateProcesses); 16664 pp.setDisplayMetrics(mMetrics); 16665 16666 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16667 final PackageParser.Package pkg; 16668 try { 16669 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16670 } catch (PackageParserException e) { 16671 res.setError("Failed parse during installPackageLI", e); 16672 return; 16673 } finally { 16674 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16675 } 16676 16677// // Ephemeral apps must have target SDK >= O. 16678// // TODO: Update conditional and error message when O gets locked down 16679// if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16680// res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16681// "Ephemeral apps must have target SDK version of at least O"); 16682// return; 16683// } 16684 16685 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16686 // Static shared libraries have synthetic package names 16687 renameStaticSharedLibraryPackage(pkg); 16688 16689 // No static shared libs on external storage 16690 if (onExternal) { 16691 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16692 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16693 "Packages declaring static-shared libs cannot be updated"); 16694 return; 16695 } 16696 } 16697 16698 // If we are installing a clustered package add results for the children 16699 if (pkg.childPackages != null) { 16700 synchronized (mPackages) { 16701 final int childCount = pkg.childPackages.size(); 16702 for (int i = 0; i < childCount; i++) { 16703 PackageParser.Package childPkg = pkg.childPackages.get(i); 16704 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16705 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16706 childRes.pkg = childPkg; 16707 childRes.name = childPkg.packageName; 16708 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16709 if (childPs != null) { 16710 childRes.origUsers = childPs.queryInstalledUsers( 16711 sUserManager.getUserIds(), true); 16712 } 16713 if ((mPackages.containsKey(childPkg.packageName))) { 16714 childRes.removedInfo = new PackageRemovedInfo(); 16715 childRes.removedInfo.removedPackage = childPkg.packageName; 16716 } 16717 if (res.addedChildPackages == null) { 16718 res.addedChildPackages = new ArrayMap<>(); 16719 } 16720 res.addedChildPackages.put(childPkg.packageName, childRes); 16721 } 16722 } 16723 } 16724 16725 // If package doesn't declare API override, mark that we have an install 16726 // time CPU ABI override. 16727 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16728 pkg.cpuAbiOverride = args.abiOverride; 16729 } 16730 16731 String pkgName = res.name = pkg.packageName; 16732 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16733 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16734 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16735 return; 16736 } 16737 } 16738 16739 try { 16740 // either use what we've been given or parse directly from the APK 16741 if (args.certificates != null) { 16742 try { 16743 PackageParser.populateCertificates(pkg, args.certificates); 16744 } catch (PackageParserException e) { 16745 // there was something wrong with the certificates we were given; 16746 // try to pull them from the APK 16747 PackageParser.collectCertificates(pkg, parseFlags); 16748 } 16749 } else { 16750 PackageParser.collectCertificates(pkg, parseFlags); 16751 } 16752 } catch (PackageParserException e) { 16753 res.setError("Failed collect during installPackageLI", e); 16754 return; 16755 } 16756 16757 // Get rid of all references to package scan path via parser. 16758 pp = null; 16759 String oldCodePath = null; 16760 boolean systemApp = false; 16761 synchronized (mPackages) { 16762 // Check if installing already existing package 16763 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16764 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16765 if (pkg.mOriginalPackages != null 16766 && pkg.mOriginalPackages.contains(oldName) 16767 && mPackages.containsKey(oldName)) { 16768 // This package is derived from an original package, 16769 // and this device has been updating from that original 16770 // name. We must continue using the original name, so 16771 // rename the new package here. 16772 pkg.setPackageName(oldName); 16773 pkgName = pkg.packageName; 16774 replace = true; 16775 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16776 + oldName + " pkgName=" + pkgName); 16777 } else if (mPackages.containsKey(pkgName)) { 16778 // This package, under its official name, already exists 16779 // on the device; we should replace it. 16780 replace = true; 16781 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16782 } 16783 16784 // Child packages are installed through the parent package 16785 if (pkg.parentPackage != null) { 16786 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16787 "Package " + pkg.packageName + " is child of package " 16788 + pkg.parentPackage.parentPackage + ". Child packages " 16789 + "can be updated only through the parent package."); 16790 return; 16791 } 16792 16793 if (replace) { 16794 // Prevent apps opting out from runtime permissions 16795 PackageParser.Package oldPackage = mPackages.get(pkgName); 16796 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16797 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16798 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16799 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16800 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16801 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16802 + " doesn't support runtime permissions but the old" 16803 + " target SDK " + oldTargetSdk + " does."); 16804 return; 16805 } 16806 16807 // Prevent installing of child packages 16808 if (oldPackage.parentPackage != null) { 16809 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16810 "Package " + pkg.packageName + " is child of package " 16811 + oldPackage.parentPackage + ". Child packages " 16812 + "can be updated only through the parent package."); 16813 return; 16814 } 16815 } 16816 } 16817 16818 PackageSetting ps = mSettings.mPackages.get(pkgName); 16819 if (ps != null) { 16820 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16821 16822 // Static shared libs have same package with different versions where 16823 // we internally use a synthetic package name to allow multiple versions 16824 // of the same package, therefore we need to compare signatures against 16825 // the package setting for the latest library version. 16826 PackageSetting signatureCheckPs = ps; 16827 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16828 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16829 if (libraryEntry != null) { 16830 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16831 } 16832 } 16833 16834 // Quick sanity check that we're signed correctly if updating; 16835 // we'll check this again later when scanning, but we want to 16836 // bail early here before tripping over redefined permissions. 16837 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16838 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16839 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16840 + pkg.packageName + " upgrade keys do not match the " 16841 + "previously installed version"); 16842 return; 16843 } 16844 } else { 16845 try { 16846 verifySignaturesLP(signatureCheckPs, pkg); 16847 } catch (PackageManagerException e) { 16848 res.setError(e.error, e.getMessage()); 16849 return; 16850 } 16851 } 16852 16853 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16854 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16855 systemApp = (ps.pkg.applicationInfo.flags & 16856 ApplicationInfo.FLAG_SYSTEM) != 0; 16857 } 16858 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16859 } 16860 16861 // Check whether the newly-scanned package wants to define an already-defined perm 16862 int N = pkg.permissions.size(); 16863 for (int i = N-1; i >= 0; i--) { 16864 PackageParser.Permission perm = pkg.permissions.get(i); 16865 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16866 if (bp != null) { 16867 // If the defining package is signed with our cert, it's okay. This 16868 // also includes the "updating the same package" case, of course. 16869 // "updating same package" could also involve key-rotation. 16870 final boolean sigsOk; 16871 if (bp.sourcePackage.equals(pkg.packageName) 16872 && (bp.packageSetting instanceof PackageSetting) 16873 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16874 scanFlags))) { 16875 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16876 } else { 16877 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16878 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16879 } 16880 if (!sigsOk) { 16881 // If the owning package is the system itself, we log but allow 16882 // install to proceed; we fail the install on all other permission 16883 // redefinitions. 16884 if (!bp.sourcePackage.equals("android")) { 16885 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16886 + pkg.packageName + " attempting to redeclare permission " 16887 + perm.info.name + " already owned by " + bp.sourcePackage); 16888 res.origPermission = perm.info.name; 16889 res.origPackage = bp.sourcePackage; 16890 return; 16891 } else { 16892 Slog.w(TAG, "Package " + pkg.packageName 16893 + " attempting to redeclare system permission " 16894 + perm.info.name + "; ignoring new declaration"); 16895 pkg.permissions.remove(i); 16896 } 16897 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16898 // Prevent apps to change protection level to dangerous from any other 16899 // type as this would allow a privilege escalation where an app adds a 16900 // normal/signature permission in other app's group and later redefines 16901 // it as dangerous leading to the group auto-grant. 16902 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16903 == PermissionInfo.PROTECTION_DANGEROUS) { 16904 if (bp != null && !bp.isRuntime()) { 16905 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16906 + "non-runtime permission " + perm.info.name 16907 + " to runtime; keeping old protection level"); 16908 perm.info.protectionLevel = bp.protectionLevel; 16909 } 16910 } 16911 } 16912 } 16913 } 16914 } 16915 16916 if (systemApp) { 16917 if (onExternal) { 16918 // Abort update; system app can't be replaced with app on sdcard 16919 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16920 "Cannot install updates to system apps on sdcard"); 16921 return; 16922 } else if (instantApp) { 16923 // Abort update; system app can't be replaced with an instant app 16924 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16925 "Cannot update a system app with an instant app"); 16926 return; 16927 } 16928 } 16929 16930 if (args.move != null) { 16931 // We did an in-place move, so dex is ready to roll 16932 scanFlags |= SCAN_NO_DEX; 16933 scanFlags |= SCAN_MOVE; 16934 16935 synchronized (mPackages) { 16936 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16937 if (ps == null) { 16938 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16939 "Missing settings for moved package " + pkgName); 16940 } 16941 16942 // We moved the entire application as-is, so bring over the 16943 // previously derived ABI information. 16944 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16945 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16946 } 16947 16948 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16949 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16950 scanFlags |= SCAN_NO_DEX; 16951 16952 try { 16953 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16954 args.abiOverride : pkg.cpuAbiOverride); 16955 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16956 true /*extractLibs*/, mAppLib32InstallDir); 16957 } catch (PackageManagerException pme) { 16958 Slog.e(TAG, "Error deriving application ABI", pme); 16959 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16960 return; 16961 } 16962 16963 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16964 // Do not run PackageDexOptimizer through the local performDexOpt 16965 // method because `pkg` may not be in `mPackages` yet. 16966 // 16967 // Also, don't fail application installs if the dexopt step fails. 16968 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16969 null /* instructionSets */, false /* checkProfiles */, 16970 getCompilerFilterForReason(REASON_INSTALL), 16971 getOrCreateCompilerPackageStats(pkg)); 16972 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16973 16974 // Notify BackgroundDexOptJobService that the package has been changed. 16975 // If this is an update of a package which used to fail to compile, 16976 // BDOS will remove it from its blacklist. 16977 // TODO: Layering violation 16978 BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName); 16979 } 16980 16981 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16982 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16983 return; 16984 } 16985 16986 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16987 16988 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16989 "installPackageLI")) { 16990 if (replace) { 16991 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16992 // Static libs have a synthetic package name containing the version 16993 // and cannot be updated as an update would get a new package name, 16994 // unless this is the exact same version code which is useful for 16995 // development. 16996 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16997 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16998 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16999 + "static-shared libs cannot be updated"); 17000 return; 17001 } 17002 } 17003 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17004 installerPackageName, res, args.installReason); 17005 } else { 17006 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17007 args.user, installerPackageName, volumeUuid, res, args.installReason); 17008 } 17009 } 17010 synchronized (mPackages) { 17011 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17012 if (ps != null) { 17013 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17014 } 17015 17016 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17017 for (int i = 0; i < childCount; i++) { 17018 PackageParser.Package childPkg = pkg.childPackages.get(i); 17019 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17020 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17021 if (childPs != null) { 17022 childRes.newUsers = childPs.queryInstalledUsers( 17023 sUserManager.getUserIds(), true); 17024 } 17025 } 17026 17027 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17028 updateSequenceNumberLP(pkgName, res.newUsers); 17029 } 17030 } 17031 } 17032 17033 private void startIntentFilterVerifications(int userId, boolean replacing, 17034 PackageParser.Package pkg) { 17035 if (mIntentFilterVerifierComponent == null) { 17036 Slog.w(TAG, "No IntentFilter verification will not be done as " 17037 + "there is no IntentFilterVerifier available!"); 17038 return; 17039 } 17040 17041 final int verifierUid = getPackageUid( 17042 mIntentFilterVerifierComponent.getPackageName(), 17043 MATCH_DEBUG_TRIAGED_MISSING, 17044 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17045 17046 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17047 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17048 mHandler.sendMessage(msg); 17049 17050 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17051 for (int i = 0; i < childCount; i++) { 17052 PackageParser.Package childPkg = pkg.childPackages.get(i); 17053 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17054 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17055 mHandler.sendMessage(msg); 17056 } 17057 } 17058 17059 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17060 PackageParser.Package pkg) { 17061 int size = pkg.activities.size(); 17062 if (size == 0) { 17063 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17064 "No activity, so no need to verify any IntentFilter!"); 17065 return; 17066 } 17067 17068 final boolean hasDomainURLs = hasDomainURLs(pkg); 17069 if (!hasDomainURLs) { 17070 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17071 "No domain URLs, so no need to verify any IntentFilter!"); 17072 return; 17073 } 17074 17075 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17076 + " if any IntentFilter from the " + size 17077 + " Activities needs verification ..."); 17078 17079 int count = 0; 17080 final String packageName = pkg.packageName; 17081 17082 synchronized (mPackages) { 17083 // If this is a new install and we see that we've already run verification for this 17084 // package, we have nothing to do: it means the state was restored from backup. 17085 if (!replacing) { 17086 IntentFilterVerificationInfo ivi = 17087 mSettings.getIntentFilterVerificationLPr(packageName); 17088 if (ivi != null) { 17089 if (DEBUG_DOMAIN_VERIFICATION) { 17090 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17091 + ivi.getStatusString()); 17092 } 17093 return; 17094 } 17095 } 17096 17097 // If any filters need to be verified, then all need to be. 17098 boolean needToVerify = false; 17099 for (PackageParser.Activity a : pkg.activities) { 17100 for (ActivityIntentInfo filter : a.intents) { 17101 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17102 if (DEBUG_DOMAIN_VERIFICATION) { 17103 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17104 } 17105 needToVerify = true; 17106 break; 17107 } 17108 } 17109 } 17110 17111 if (needToVerify) { 17112 final int verificationId = mIntentFilterVerificationToken++; 17113 for (PackageParser.Activity a : pkg.activities) { 17114 for (ActivityIntentInfo filter : a.intents) { 17115 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17116 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17117 "Verification needed for IntentFilter:" + filter.toString()); 17118 mIntentFilterVerifier.addOneIntentFilterVerification( 17119 verifierUid, userId, verificationId, filter, packageName); 17120 count++; 17121 } 17122 } 17123 } 17124 } 17125 } 17126 17127 if (count > 0) { 17128 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17129 + " IntentFilter verification" + (count > 1 ? "s" : "") 17130 + " for userId:" + userId); 17131 mIntentFilterVerifier.startVerifications(userId); 17132 } else { 17133 if (DEBUG_DOMAIN_VERIFICATION) { 17134 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17135 } 17136 } 17137 } 17138 17139 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17140 final ComponentName cn = filter.activity.getComponentName(); 17141 final String packageName = cn.getPackageName(); 17142 17143 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17144 packageName); 17145 if (ivi == null) { 17146 return true; 17147 } 17148 int status = ivi.getStatus(); 17149 switch (status) { 17150 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17151 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17152 return true; 17153 17154 default: 17155 // Nothing to do 17156 return false; 17157 } 17158 } 17159 17160 private static boolean isMultiArch(ApplicationInfo info) { 17161 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17162 } 17163 17164 private static boolean isExternal(PackageParser.Package pkg) { 17165 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17166 } 17167 17168 private static boolean isExternal(PackageSetting ps) { 17169 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17170 } 17171 17172 private static boolean isSystemApp(PackageParser.Package pkg) { 17173 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17174 } 17175 17176 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17177 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17178 } 17179 17180 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17181 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17182 } 17183 17184 private static boolean isSystemApp(PackageSetting ps) { 17185 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17186 } 17187 17188 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17189 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17190 } 17191 17192 private int packageFlagsToInstallFlags(PackageSetting ps) { 17193 int installFlags = 0; 17194 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17195 // This existing package was an external ASEC install when we have 17196 // the external flag without a UUID 17197 installFlags |= PackageManager.INSTALL_EXTERNAL; 17198 } 17199 if (ps.isForwardLocked()) { 17200 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17201 } 17202 return installFlags; 17203 } 17204 17205 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17206 if (isExternal(pkg)) { 17207 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17208 return StorageManager.UUID_PRIMARY_PHYSICAL; 17209 } else { 17210 return pkg.volumeUuid; 17211 } 17212 } else { 17213 return StorageManager.UUID_PRIVATE_INTERNAL; 17214 } 17215 } 17216 17217 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17218 if (isExternal(pkg)) { 17219 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17220 return mSettings.getExternalVersion(); 17221 } else { 17222 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17223 } 17224 } else { 17225 return mSettings.getInternalVersion(); 17226 } 17227 } 17228 17229 private void deleteTempPackageFiles() { 17230 final FilenameFilter filter = new FilenameFilter() { 17231 public boolean accept(File dir, String name) { 17232 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17233 } 17234 }; 17235 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17236 file.delete(); 17237 } 17238 } 17239 17240 @Override 17241 public void deletePackageAsUser(String packageName, int versionCode, 17242 IPackageDeleteObserver observer, int userId, int flags) { 17243 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17244 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17245 } 17246 17247 @Override 17248 public void deletePackageVersioned(VersionedPackage versionedPackage, 17249 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17250 mContext.enforceCallingOrSelfPermission( 17251 android.Manifest.permission.DELETE_PACKAGES, null); 17252 Preconditions.checkNotNull(versionedPackage); 17253 Preconditions.checkNotNull(observer); 17254 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17255 PackageManager.VERSION_CODE_HIGHEST, 17256 Integer.MAX_VALUE, "versionCode must be >= -1"); 17257 17258 final String packageName = versionedPackage.getPackageName(); 17259 // TODO: We will change version code to long, so in the new API it is long 17260 final int versionCode = (int) versionedPackage.getVersionCode(); 17261 final String internalPackageName; 17262 synchronized (mPackages) { 17263 // Normalize package name to handle renamed packages and static libs 17264 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17265 // TODO: We will change version code to long, so in the new API it is long 17266 (int) versionedPackage.getVersionCode()); 17267 } 17268 17269 final int uid = Binder.getCallingUid(); 17270 if (!isOrphaned(internalPackageName) 17271 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17272 try { 17273 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17274 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17275 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17276 observer.onUserActionRequired(intent); 17277 } catch (RemoteException re) { 17278 } 17279 return; 17280 } 17281 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17282 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17283 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17284 mContext.enforceCallingOrSelfPermission( 17285 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17286 "deletePackage for user " + userId); 17287 } 17288 17289 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17290 try { 17291 observer.onPackageDeleted(packageName, 17292 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17293 } catch (RemoteException re) { 17294 } 17295 return; 17296 } 17297 17298 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17299 try { 17300 observer.onPackageDeleted(packageName, 17301 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17302 } catch (RemoteException re) { 17303 } 17304 return; 17305 } 17306 17307 if (DEBUG_REMOVE) { 17308 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17309 + " deleteAllUsers: " + deleteAllUsers + " version=" 17310 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17311 ? "VERSION_CODE_HIGHEST" : versionCode)); 17312 } 17313 // Queue up an async operation since the package deletion may take a little while. 17314 mHandler.post(new Runnable() { 17315 public void run() { 17316 mHandler.removeCallbacks(this); 17317 int returnCode; 17318 if (!deleteAllUsers) { 17319 returnCode = deletePackageX(internalPackageName, versionCode, 17320 userId, deleteFlags); 17321 } else { 17322 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17323 internalPackageName, users); 17324 // If nobody is blocking uninstall, proceed with delete for all users 17325 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17326 returnCode = deletePackageX(internalPackageName, versionCode, 17327 userId, deleteFlags); 17328 } else { 17329 // Otherwise uninstall individually for users with blockUninstalls=false 17330 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17331 for (int userId : users) { 17332 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17333 returnCode = deletePackageX(internalPackageName, versionCode, 17334 userId, userFlags); 17335 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17336 Slog.w(TAG, "Package delete failed for user " + userId 17337 + ", returnCode " + returnCode); 17338 } 17339 } 17340 } 17341 // The app has only been marked uninstalled for certain users. 17342 // We still need to report that delete was blocked 17343 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17344 } 17345 } 17346 try { 17347 observer.onPackageDeleted(packageName, returnCode, null); 17348 } catch (RemoteException e) { 17349 Log.i(TAG, "Observer no longer exists."); 17350 } //end catch 17351 } //end run 17352 }); 17353 } 17354 17355 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17356 if (pkg.staticSharedLibName != null) { 17357 return pkg.manifestPackageName; 17358 } 17359 return pkg.packageName; 17360 } 17361 17362 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17363 // Handle renamed packages 17364 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17365 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17366 17367 // Is this a static library? 17368 SparseArray<SharedLibraryEntry> versionedLib = 17369 mStaticLibsByDeclaringPackage.get(packageName); 17370 if (versionedLib == null || versionedLib.size() <= 0) { 17371 return packageName; 17372 } 17373 17374 // Figure out which lib versions the caller can see 17375 SparseIntArray versionsCallerCanSee = null; 17376 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17377 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17378 && callingAppId != Process.ROOT_UID) { 17379 versionsCallerCanSee = new SparseIntArray(); 17380 String libName = versionedLib.valueAt(0).info.getName(); 17381 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17382 if (uidPackages != null) { 17383 for (String uidPackage : uidPackages) { 17384 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17385 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17386 if (libIdx >= 0) { 17387 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17388 versionsCallerCanSee.append(libVersion, libVersion); 17389 } 17390 } 17391 } 17392 } 17393 17394 // Caller can see nothing - done 17395 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17396 return packageName; 17397 } 17398 17399 // Find the version the caller can see and the app version code 17400 SharedLibraryEntry highestVersion = null; 17401 final int versionCount = versionedLib.size(); 17402 for (int i = 0; i < versionCount; i++) { 17403 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17404 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17405 libEntry.info.getVersion()) < 0) { 17406 continue; 17407 } 17408 // TODO: We will change version code to long, so in the new API it is long 17409 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17410 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17411 if (libVersionCode == versionCode) { 17412 return libEntry.apk; 17413 } 17414 } else if (highestVersion == null) { 17415 highestVersion = libEntry; 17416 } else if (libVersionCode > highestVersion.info 17417 .getDeclaringPackage().getVersionCode()) { 17418 highestVersion = libEntry; 17419 } 17420 } 17421 17422 if (highestVersion != null) { 17423 return highestVersion.apk; 17424 } 17425 17426 return packageName; 17427 } 17428 17429 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17430 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17431 || callingUid == Process.SYSTEM_UID) { 17432 return true; 17433 } 17434 final int callingUserId = UserHandle.getUserId(callingUid); 17435 // If the caller installed the pkgName, then allow it to silently uninstall. 17436 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17437 return true; 17438 } 17439 17440 // Allow package verifier to silently uninstall. 17441 if (mRequiredVerifierPackage != null && 17442 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17443 return true; 17444 } 17445 17446 // Allow package uninstaller to silently uninstall. 17447 if (mRequiredUninstallerPackage != null && 17448 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17449 return true; 17450 } 17451 17452 // Allow storage manager to silently uninstall. 17453 if (mStorageManagerPackage != null && 17454 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17455 return true; 17456 } 17457 return false; 17458 } 17459 17460 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17461 int[] result = EMPTY_INT_ARRAY; 17462 for (int userId : userIds) { 17463 if (getBlockUninstallForUser(packageName, userId)) { 17464 result = ArrayUtils.appendInt(result, userId); 17465 } 17466 } 17467 return result; 17468 } 17469 17470 @Override 17471 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17472 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17473 } 17474 17475 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17476 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17477 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17478 try { 17479 if (dpm != null) { 17480 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17481 /* callingUserOnly =*/ false); 17482 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17483 : deviceOwnerComponentName.getPackageName(); 17484 // Does the package contains the device owner? 17485 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17486 // this check is probably not needed, since DO should be registered as a device 17487 // admin on some user too. (Original bug for this: b/17657954) 17488 if (packageName.equals(deviceOwnerPackageName)) { 17489 return true; 17490 } 17491 // Does it contain a device admin for any user? 17492 int[] users; 17493 if (userId == UserHandle.USER_ALL) { 17494 users = sUserManager.getUserIds(); 17495 } else { 17496 users = new int[]{userId}; 17497 } 17498 for (int i = 0; i < users.length; ++i) { 17499 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17500 return true; 17501 } 17502 } 17503 } 17504 } catch (RemoteException e) { 17505 } 17506 return false; 17507 } 17508 17509 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17510 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17511 } 17512 17513 /** 17514 * This method is an internal method that could be get invoked either 17515 * to delete an installed package or to clean up a failed installation. 17516 * After deleting an installed package, a broadcast is sent to notify any 17517 * listeners that the package has been removed. For cleaning up a failed 17518 * installation, the broadcast is not necessary since the package's 17519 * installation wouldn't have sent the initial broadcast either 17520 * The key steps in deleting a package are 17521 * deleting the package information in internal structures like mPackages, 17522 * deleting the packages base directories through installd 17523 * updating mSettings to reflect current status 17524 * persisting settings for later use 17525 * sending a broadcast if necessary 17526 */ 17527 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17528 final PackageRemovedInfo info = new PackageRemovedInfo(); 17529 final boolean res; 17530 17531 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17532 ? UserHandle.USER_ALL : userId; 17533 17534 if (isPackageDeviceAdmin(packageName, removeUser)) { 17535 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17536 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17537 } 17538 17539 PackageSetting uninstalledPs = null; 17540 17541 // for the uninstall-updates case and restricted profiles, remember the per- 17542 // user handle installed state 17543 int[] allUsers; 17544 synchronized (mPackages) { 17545 uninstalledPs = mSettings.mPackages.get(packageName); 17546 if (uninstalledPs == null) { 17547 Slog.w(TAG, "Not removing non-existent package " + packageName); 17548 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17549 } 17550 17551 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17552 && uninstalledPs.versionCode != versionCode) { 17553 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17554 + uninstalledPs.versionCode + " != " + versionCode); 17555 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17556 } 17557 17558 // Static shared libs can be declared by any package, so let us not 17559 // allow removing a package if it provides a lib others depend on. 17560 PackageParser.Package pkg = mPackages.get(packageName); 17561 if (pkg != null && pkg.staticSharedLibName != null) { 17562 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17563 pkg.staticSharedLibVersion); 17564 if (libEntry != null) { 17565 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17566 libEntry.info, 0, userId); 17567 if (!ArrayUtils.isEmpty(libClientPackages)) { 17568 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17569 + " hosting lib " + libEntry.info.getName() + " version " 17570 + libEntry.info.getVersion() + " used by " + libClientPackages); 17571 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17572 } 17573 } 17574 } 17575 17576 allUsers = sUserManager.getUserIds(); 17577 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17578 } 17579 17580 final int freezeUser; 17581 if (isUpdatedSystemApp(uninstalledPs) 17582 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17583 // We're downgrading a system app, which will apply to all users, so 17584 // freeze them all during the downgrade 17585 freezeUser = UserHandle.USER_ALL; 17586 } else { 17587 freezeUser = removeUser; 17588 } 17589 17590 synchronized (mInstallLock) { 17591 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17592 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17593 deleteFlags, "deletePackageX")) { 17594 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17595 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17596 } 17597 synchronized (mPackages) { 17598 if (res) { 17599 mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg, 17600 info.removedUsers); 17601 updateSequenceNumberLP(packageName, info.removedUsers); 17602 } 17603 } 17604 } 17605 17606 if (res) { 17607 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17608 info.sendPackageRemovedBroadcasts(killApp); 17609 info.sendSystemPackageUpdatedBroadcasts(); 17610 info.sendSystemPackageAppearedBroadcasts(); 17611 } 17612 // Force a gc here. 17613 Runtime.getRuntime().gc(); 17614 // Delete the resources here after sending the broadcast to let 17615 // other processes clean up before deleting resources. 17616 if (info.args != null) { 17617 synchronized (mInstallLock) { 17618 info.args.doPostDeleteLI(true); 17619 } 17620 } 17621 17622 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17623 } 17624 17625 class PackageRemovedInfo { 17626 String removedPackage; 17627 int uid = -1; 17628 int removedAppId = -1; 17629 int[] origUsers; 17630 int[] removedUsers = null; 17631 SparseArray<Integer> installReasons; 17632 boolean isRemovedPackageSystemUpdate = false; 17633 boolean isUpdate; 17634 boolean dataRemoved; 17635 boolean removedForAllUsers; 17636 boolean isStaticSharedLib; 17637 // Clean up resources deleted packages. 17638 InstallArgs args = null; 17639 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17640 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17641 17642 void sendPackageRemovedBroadcasts(boolean killApp) { 17643 sendPackageRemovedBroadcastInternal(killApp); 17644 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17645 for (int i = 0; i < childCount; i++) { 17646 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17647 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17648 } 17649 } 17650 17651 void sendSystemPackageUpdatedBroadcasts() { 17652 if (isRemovedPackageSystemUpdate) { 17653 sendSystemPackageUpdatedBroadcastsInternal(); 17654 final int childCount = (removedChildPackages != null) 17655 ? removedChildPackages.size() : 0; 17656 for (int i = 0; i < childCount; i++) { 17657 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17658 if (childInfo.isRemovedPackageSystemUpdate) { 17659 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17660 } 17661 } 17662 } 17663 } 17664 17665 void sendSystemPackageAppearedBroadcasts() { 17666 final int packageCount = (appearedChildPackages != null) 17667 ? appearedChildPackages.size() : 0; 17668 for (int i = 0; i < packageCount; i++) { 17669 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17670 sendPackageAddedForNewUsers(installedInfo.name, true, 17671 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17672 } 17673 } 17674 17675 private void sendSystemPackageUpdatedBroadcastsInternal() { 17676 Bundle extras = new Bundle(2); 17677 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17678 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17679 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17680 extras, 0, null, null, null); 17681 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17682 extras, 0, null, null, null); 17683 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17684 null, 0, removedPackage, null, null); 17685 } 17686 17687 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17688 // Don't send static shared library removal broadcasts as these 17689 // libs are visible only the the apps that depend on them an one 17690 // cannot remove the library if it has a dependency. 17691 if (isStaticSharedLib) { 17692 return; 17693 } 17694 Bundle extras = new Bundle(2); 17695 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17696 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17697 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17698 if (isUpdate || isRemovedPackageSystemUpdate) { 17699 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17700 } 17701 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17702 if (removedPackage != null) { 17703 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17704 extras, 0, null, null, removedUsers); 17705 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17706 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17707 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17708 null, null, removedUsers); 17709 } 17710 } 17711 if (removedAppId >= 0) { 17712 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17713 removedUsers); 17714 } 17715 } 17716 } 17717 17718 /* 17719 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17720 * flag is not set, the data directory is removed as well. 17721 * make sure this flag is set for partially installed apps. If not its meaningless to 17722 * delete a partially installed application. 17723 */ 17724 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17725 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17726 String packageName = ps.name; 17727 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17728 // Retrieve object to delete permissions for shared user later on 17729 final PackageParser.Package deletedPkg; 17730 final PackageSetting deletedPs; 17731 // reader 17732 synchronized (mPackages) { 17733 deletedPkg = mPackages.get(packageName); 17734 deletedPs = mSettings.mPackages.get(packageName); 17735 if (outInfo != null) { 17736 outInfo.removedPackage = packageName; 17737 outInfo.isStaticSharedLib = deletedPkg != null 17738 && deletedPkg.staticSharedLibName != null; 17739 outInfo.removedUsers = deletedPs != null 17740 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17741 : null; 17742 } 17743 } 17744 17745 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17746 17747 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17748 final PackageParser.Package resolvedPkg; 17749 if (deletedPkg != null) { 17750 resolvedPkg = deletedPkg; 17751 } else { 17752 // We don't have a parsed package when it lives on an ejected 17753 // adopted storage device, so fake something together 17754 resolvedPkg = new PackageParser.Package(ps.name); 17755 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17756 } 17757 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17758 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17759 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17760 if (outInfo != null) { 17761 outInfo.dataRemoved = true; 17762 } 17763 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17764 } 17765 17766 int removedAppId = -1; 17767 17768 // writer 17769 synchronized (mPackages) { 17770 boolean installedStateChanged = false; 17771 if (deletedPs != null) { 17772 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17773 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17774 clearDefaultBrowserIfNeeded(packageName); 17775 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17776 removedAppId = mSettings.removePackageLPw(packageName); 17777 if (outInfo != null) { 17778 outInfo.removedAppId = removedAppId; 17779 } 17780 updatePermissionsLPw(deletedPs.name, null, 0); 17781 if (deletedPs.sharedUser != null) { 17782 // Remove permissions associated with package. Since runtime 17783 // permissions are per user we have to kill the removed package 17784 // or packages running under the shared user of the removed 17785 // package if revoking the permissions requested only by the removed 17786 // package is successful and this causes a change in gids. 17787 for (int userId : UserManagerService.getInstance().getUserIds()) { 17788 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17789 userId); 17790 if (userIdToKill == UserHandle.USER_ALL 17791 || userIdToKill >= UserHandle.USER_SYSTEM) { 17792 // If gids changed for this user, kill all affected packages. 17793 mHandler.post(new Runnable() { 17794 @Override 17795 public void run() { 17796 // This has to happen with no lock held. 17797 killApplication(deletedPs.name, deletedPs.appId, 17798 KILL_APP_REASON_GIDS_CHANGED); 17799 } 17800 }); 17801 break; 17802 } 17803 } 17804 } 17805 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17806 } 17807 // make sure to preserve per-user disabled state if this removal was just 17808 // a downgrade of a system app to the factory package 17809 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17810 if (DEBUG_REMOVE) { 17811 Slog.d(TAG, "Propagating install state across downgrade"); 17812 } 17813 for (int userId : allUserHandles) { 17814 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17815 if (DEBUG_REMOVE) { 17816 Slog.d(TAG, " user " + userId + " => " + installed); 17817 } 17818 if (installed != ps.getInstalled(userId)) { 17819 installedStateChanged = true; 17820 } 17821 ps.setInstalled(installed, userId); 17822 } 17823 } 17824 } 17825 // can downgrade to reader 17826 if (writeSettings) { 17827 // Save settings now 17828 mSettings.writeLPr(); 17829 } 17830 if (installedStateChanged) { 17831 mSettings.writeKernelMappingLPr(ps); 17832 } 17833 } 17834 if (removedAppId != -1) { 17835 // A user ID was deleted here. Go through all users and remove it 17836 // from KeyStore. 17837 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17838 } 17839 } 17840 17841 static boolean locationIsPrivileged(File path) { 17842 try { 17843 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17844 .getCanonicalPath(); 17845 return path.getCanonicalPath().startsWith(privilegedAppDir); 17846 } catch (IOException e) { 17847 Slog.e(TAG, "Unable to access code path " + path); 17848 } 17849 return false; 17850 } 17851 17852 /* 17853 * Tries to delete system package. 17854 */ 17855 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17856 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17857 boolean writeSettings) { 17858 if (deletedPs.parentPackageName != null) { 17859 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17860 return false; 17861 } 17862 17863 final boolean applyUserRestrictions 17864 = (allUserHandles != null) && (outInfo.origUsers != null); 17865 final PackageSetting disabledPs; 17866 // Confirm if the system package has been updated 17867 // An updated system app can be deleted. This will also have to restore 17868 // the system pkg from system partition 17869 // reader 17870 synchronized (mPackages) { 17871 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17872 } 17873 17874 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17875 + " disabledPs=" + disabledPs); 17876 17877 if (disabledPs == null) { 17878 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17879 return false; 17880 } else if (DEBUG_REMOVE) { 17881 Slog.d(TAG, "Deleting system pkg from data partition"); 17882 } 17883 17884 if (DEBUG_REMOVE) { 17885 if (applyUserRestrictions) { 17886 Slog.d(TAG, "Remembering install states:"); 17887 for (int userId : allUserHandles) { 17888 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17889 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17890 } 17891 } 17892 } 17893 17894 // Delete the updated package 17895 outInfo.isRemovedPackageSystemUpdate = true; 17896 if (outInfo.removedChildPackages != null) { 17897 final int childCount = (deletedPs.childPackageNames != null) 17898 ? deletedPs.childPackageNames.size() : 0; 17899 for (int i = 0; i < childCount; i++) { 17900 String childPackageName = deletedPs.childPackageNames.get(i); 17901 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17902 .contains(childPackageName)) { 17903 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17904 childPackageName); 17905 if (childInfo != null) { 17906 childInfo.isRemovedPackageSystemUpdate = true; 17907 } 17908 } 17909 } 17910 } 17911 17912 if (disabledPs.versionCode < deletedPs.versionCode) { 17913 // Delete data for downgrades 17914 flags &= ~PackageManager.DELETE_KEEP_DATA; 17915 } else { 17916 // Preserve data by setting flag 17917 flags |= PackageManager.DELETE_KEEP_DATA; 17918 } 17919 17920 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17921 outInfo, writeSettings, disabledPs.pkg); 17922 if (!ret) { 17923 return false; 17924 } 17925 17926 // writer 17927 synchronized (mPackages) { 17928 // Reinstate the old system package 17929 enableSystemPackageLPw(disabledPs.pkg); 17930 // Remove any native libraries from the upgraded package. 17931 removeNativeBinariesLI(deletedPs); 17932 } 17933 17934 // Install the system package 17935 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17936 int parseFlags = mDefParseFlags 17937 | PackageParser.PARSE_MUST_BE_APK 17938 | PackageParser.PARSE_IS_SYSTEM 17939 | PackageParser.PARSE_IS_SYSTEM_DIR; 17940 if (locationIsPrivileged(disabledPs.codePath)) { 17941 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17942 } 17943 17944 final PackageParser.Package newPkg; 17945 try { 17946 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17947 0 /* currentTime */, null); 17948 } catch (PackageManagerException e) { 17949 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17950 + e.getMessage()); 17951 return false; 17952 } 17953 17954 try { 17955 // update shared libraries for the newly re-installed system package 17956 updateSharedLibrariesLPr(newPkg, null); 17957 } catch (PackageManagerException e) { 17958 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17959 } 17960 17961 prepareAppDataAfterInstallLIF(newPkg); 17962 17963 // writer 17964 synchronized (mPackages) { 17965 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17966 17967 // Propagate the permissions state as we do not want to drop on the floor 17968 // runtime permissions. The update permissions method below will take 17969 // care of removing obsolete permissions and grant install permissions. 17970 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17971 updatePermissionsLPw(newPkg.packageName, newPkg, 17972 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17973 17974 if (applyUserRestrictions) { 17975 boolean installedStateChanged = false; 17976 if (DEBUG_REMOVE) { 17977 Slog.d(TAG, "Propagating install state across reinstall"); 17978 } 17979 for (int userId : allUserHandles) { 17980 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17981 if (DEBUG_REMOVE) { 17982 Slog.d(TAG, " user " + userId + " => " + installed); 17983 } 17984 if (installed != ps.getInstalled(userId)) { 17985 installedStateChanged = true; 17986 } 17987 ps.setInstalled(installed, userId); 17988 17989 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17990 } 17991 // Regardless of writeSettings we need to ensure that this restriction 17992 // state propagation is persisted 17993 mSettings.writeAllUsersPackageRestrictionsLPr(); 17994 if (installedStateChanged) { 17995 mSettings.writeKernelMappingLPr(ps); 17996 } 17997 } 17998 // can downgrade to reader here 17999 if (writeSettings) { 18000 mSettings.writeLPr(); 18001 } 18002 } 18003 return true; 18004 } 18005 18006 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18007 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18008 PackageRemovedInfo outInfo, boolean writeSettings, 18009 PackageParser.Package replacingPackage) { 18010 synchronized (mPackages) { 18011 if (outInfo != null) { 18012 outInfo.uid = ps.appId; 18013 } 18014 18015 if (outInfo != null && outInfo.removedChildPackages != null) { 18016 final int childCount = (ps.childPackageNames != null) 18017 ? ps.childPackageNames.size() : 0; 18018 for (int i = 0; i < childCount; i++) { 18019 String childPackageName = ps.childPackageNames.get(i); 18020 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18021 if (childPs == null) { 18022 return false; 18023 } 18024 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18025 childPackageName); 18026 if (childInfo != null) { 18027 childInfo.uid = childPs.appId; 18028 } 18029 } 18030 } 18031 } 18032 18033 // Delete package data from internal structures and also remove data if flag is set 18034 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18035 18036 // Delete the child packages data 18037 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18038 for (int i = 0; i < childCount; i++) { 18039 PackageSetting childPs; 18040 synchronized (mPackages) { 18041 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18042 } 18043 if (childPs != null) { 18044 PackageRemovedInfo childOutInfo = (outInfo != null 18045 && outInfo.removedChildPackages != null) 18046 ? outInfo.removedChildPackages.get(childPs.name) : null; 18047 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18048 && (replacingPackage != null 18049 && !replacingPackage.hasChildPackage(childPs.name)) 18050 ? flags & ~DELETE_KEEP_DATA : flags; 18051 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18052 deleteFlags, writeSettings); 18053 } 18054 } 18055 18056 // Delete application code and resources only for parent packages 18057 if (ps.parentPackageName == null) { 18058 if (deleteCodeAndResources && (outInfo != null)) { 18059 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18060 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18061 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18062 } 18063 } 18064 18065 return true; 18066 } 18067 18068 @Override 18069 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18070 int userId) { 18071 mContext.enforceCallingOrSelfPermission( 18072 android.Manifest.permission.DELETE_PACKAGES, null); 18073 synchronized (mPackages) { 18074 PackageSetting ps = mSettings.mPackages.get(packageName); 18075 if (ps == null) { 18076 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18077 return false; 18078 } 18079 // Cannot block uninstall of static shared libs as they are 18080 // considered a part of the using app (emulating static linking). 18081 // Also static libs are installed always on internal storage. 18082 PackageParser.Package pkg = mPackages.get(packageName); 18083 if (pkg != null && pkg.staticSharedLibName != null) { 18084 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18085 + " providing static shared library: " + pkg.staticSharedLibName); 18086 return false; 18087 } 18088 if (!ps.getInstalled(userId)) { 18089 // Can't block uninstall for an app that is not installed or enabled. 18090 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18091 return false; 18092 } 18093 ps.setBlockUninstall(blockUninstall, userId); 18094 mSettings.writePackageRestrictionsLPr(userId); 18095 } 18096 return true; 18097 } 18098 18099 @Override 18100 public boolean getBlockUninstallForUser(String packageName, int userId) { 18101 synchronized (mPackages) { 18102 PackageSetting ps = mSettings.mPackages.get(packageName); 18103 if (ps == null) { 18104 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18105 return false; 18106 } 18107 return ps.getBlockUninstall(userId); 18108 } 18109 } 18110 18111 @Override 18112 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18113 int callingUid = Binder.getCallingUid(); 18114 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18115 throw new SecurityException( 18116 "setRequiredForSystemUser can only be run by the system or root"); 18117 } 18118 synchronized (mPackages) { 18119 PackageSetting ps = mSettings.mPackages.get(packageName); 18120 if (ps == null) { 18121 Log.w(TAG, "Package doesn't exist: " + packageName); 18122 return false; 18123 } 18124 if (systemUserApp) { 18125 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18126 } else { 18127 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18128 } 18129 mSettings.writeLPr(); 18130 } 18131 return true; 18132 } 18133 18134 /* 18135 * This method handles package deletion in general 18136 */ 18137 private boolean deletePackageLIF(String packageName, UserHandle user, 18138 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18139 PackageRemovedInfo outInfo, boolean writeSettings, 18140 PackageParser.Package replacingPackage) { 18141 if (packageName == null) { 18142 Slog.w(TAG, "Attempt to delete null packageName."); 18143 return false; 18144 } 18145 18146 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18147 18148 PackageSetting ps; 18149 synchronized (mPackages) { 18150 ps = mSettings.mPackages.get(packageName); 18151 if (ps == null) { 18152 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18153 return false; 18154 } 18155 18156 if (ps.parentPackageName != null && (!isSystemApp(ps) 18157 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18158 if (DEBUG_REMOVE) { 18159 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18160 + ((user == null) ? UserHandle.USER_ALL : user)); 18161 } 18162 final int removedUserId = (user != null) ? user.getIdentifier() 18163 : UserHandle.USER_ALL; 18164 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18165 return false; 18166 } 18167 markPackageUninstalledForUserLPw(ps, user); 18168 scheduleWritePackageRestrictionsLocked(user); 18169 return true; 18170 } 18171 } 18172 18173 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18174 && user.getIdentifier() != UserHandle.USER_ALL)) { 18175 // The caller is asking that the package only be deleted for a single 18176 // user. To do this, we just mark its uninstalled state and delete 18177 // its data. If this is a system app, we only allow this to happen if 18178 // they have set the special DELETE_SYSTEM_APP which requests different 18179 // semantics than normal for uninstalling system apps. 18180 markPackageUninstalledForUserLPw(ps, user); 18181 18182 if (!isSystemApp(ps)) { 18183 // Do not uninstall the APK if an app should be cached 18184 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18185 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18186 // Other user still have this package installed, so all 18187 // we need to do is clear this user's data and save that 18188 // it is uninstalled. 18189 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18190 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18191 return false; 18192 } 18193 scheduleWritePackageRestrictionsLocked(user); 18194 return true; 18195 } else { 18196 // We need to set it back to 'installed' so the uninstall 18197 // broadcasts will be sent correctly. 18198 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18199 ps.setInstalled(true, user.getIdentifier()); 18200 mSettings.writeKernelMappingLPr(ps); 18201 } 18202 } else { 18203 // This is a system app, so we assume that the 18204 // other users still have this package installed, so all 18205 // we need to do is clear this user's data and save that 18206 // it is uninstalled. 18207 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18208 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18209 return false; 18210 } 18211 scheduleWritePackageRestrictionsLocked(user); 18212 return true; 18213 } 18214 } 18215 18216 // If we are deleting a composite package for all users, keep track 18217 // of result for each child. 18218 if (ps.childPackageNames != null && outInfo != null) { 18219 synchronized (mPackages) { 18220 final int childCount = ps.childPackageNames.size(); 18221 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18222 for (int i = 0; i < childCount; i++) { 18223 String childPackageName = ps.childPackageNames.get(i); 18224 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18225 childInfo.removedPackage = childPackageName; 18226 outInfo.removedChildPackages.put(childPackageName, childInfo); 18227 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18228 if (childPs != null) { 18229 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18230 } 18231 } 18232 } 18233 } 18234 18235 boolean ret = false; 18236 if (isSystemApp(ps)) { 18237 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18238 // When an updated system application is deleted we delete the existing resources 18239 // as well and fall back to existing code in system partition 18240 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18241 } else { 18242 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18243 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18244 outInfo, writeSettings, replacingPackage); 18245 } 18246 18247 // Take a note whether we deleted the package for all users 18248 if (outInfo != null) { 18249 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18250 if (outInfo.removedChildPackages != null) { 18251 synchronized (mPackages) { 18252 final int childCount = outInfo.removedChildPackages.size(); 18253 for (int i = 0; i < childCount; i++) { 18254 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18255 if (childInfo != null) { 18256 childInfo.removedForAllUsers = mPackages.get( 18257 childInfo.removedPackage) == null; 18258 } 18259 } 18260 } 18261 } 18262 // If we uninstalled an update to a system app there may be some 18263 // child packages that appeared as they are declared in the system 18264 // app but were not declared in the update. 18265 if (isSystemApp(ps)) { 18266 synchronized (mPackages) { 18267 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18268 final int childCount = (updatedPs.childPackageNames != null) 18269 ? updatedPs.childPackageNames.size() : 0; 18270 for (int i = 0; i < childCount; i++) { 18271 String childPackageName = updatedPs.childPackageNames.get(i); 18272 if (outInfo.removedChildPackages == null 18273 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18274 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18275 if (childPs == null) { 18276 continue; 18277 } 18278 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18279 installRes.name = childPackageName; 18280 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18281 installRes.pkg = mPackages.get(childPackageName); 18282 installRes.uid = childPs.pkg.applicationInfo.uid; 18283 if (outInfo.appearedChildPackages == null) { 18284 outInfo.appearedChildPackages = new ArrayMap<>(); 18285 } 18286 outInfo.appearedChildPackages.put(childPackageName, installRes); 18287 } 18288 } 18289 } 18290 } 18291 } 18292 18293 return ret; 18294 } 18295 18296 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18297 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18298 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18299 for (int nextUserId : userIds) { 18300 if (DEBUG_REMOVE) { 18301 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18302 } 18303 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18304 false /*installed*/, 18305 true /*stopped*/, 18306 true /*notLaunched*/, 18307 false /*hidden*/, 18308 false /*suspended*/, 18309 false /*instantApp*/, 18310 null /*lastDisableAppCaller*/, 18311 null /*enabledComponents*/, 18312 null /*disabledComponents*/, 18313 false /*blockUninstall*/, 18314 ps.readUserState(nextUserId).domainVerificationStatus, 18315 0, PackageManager.INSTALL_REASON_UNKNOWN); 18316 } 18317 mSettings.writeKernelMappingLPr(ps); 18318 } 18319 18320 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18321 PackageRemovedInfo outInfo) { 18322 final PackageParser.Package pkg; 18323 synchronized (mPackages) { 18324 pkg = mPackages.get(ps.name); 18325 } 18326 18327 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18328 : new int[] {userId}; 18329 for (int nextUserId : userIds) { 18330 if (DEBUG_REMOVE) { 18331 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18332 + nextUserId); 18333 } 18334 18335 destroyAppDataLIF(pkg, userId, 18336 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18337 destroyAppProfilesLIF(pkg, userId); 18338 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18339 schedulePackageCleaning(ps.name, nextUserId, false); 18340 synchronized (mPackages) { 18341 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18342 scheduleWritePackageRestrictionsLocked(nextUserId); 18343 } 18344 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18345 } 18346 } 18347 18348 if (outInfo != null) { 18349 outInfo.removedPackage = ps.name; 18350 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18351 outInfo.removedAppId = ps.appId; 18352 outInfo.removedUsers = userIds; 18353 } 18354 18355 return true; 18356 } 18357 18358 private final class ClearStorageConnection implements ServiceConnection { 18359 IMediaContainerService mContainerService; 18360 18361 @Override 18362 public void onServiceConnected(ComponentName name, IBinder service) { 18363 synchronized (this) { 18364 mContainerService = IMediaContainerService.Stub 18365 .asInterface(Binder.allowBlocking(service)); 18366 notifyAll(); 18367 } 18368 } 18369 18370 @Override 18371 public void onServiceDisconnected(ComponentName name) { 18372 } 18373 } 18374 18375 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18376 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18377 18378 final boolean mounted; 18379 if (Environment.isExternalStorageEmulated()) { 18380 mounted = true; 18381 } else { 18382 final String status = Environment.getExternalStorageState(); 18383 18384 mounted = status.equals(Environment.MEDIA_MOUNTED) 18385 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18386 } 18387 18388 if (!mounted) { 18389 return; 18390 } 18391 18392 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18393 int[] users; 18394 if (userId == UserHandle.USER_ALL) { 18395 users = sUserManager.getUserIds(); 18396 } else { 18397 users = new int[] { userId }; 18398 } 18399 final ClearStorageConnection conn = new ClearStorageConnection(); 18400 if (mContext.bindServiceAsUser( 18401 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18402 try { 18403 for (int curUser : users) { 18404 long timeout = SystemClock.uptimeMillis() + 5000; 18405 synchronized (conn) { 18406 long now; 18407 while (conn.mContainerService == null && 18408 (now = SystemClock.uptimeMillis()) < timeout) { 18409 try { 18410 conn.wait(timeout - now); 18411 } catch (InterruptedException e) { 18412 } 18413 } 18414 } 18415 if (conn.mContainerService == null) { 18416 return; 18417 } 18418 18419 final UserEnvironment userEnv = new UserEnvironment(curUser); 18420 clearDirectory(conn.mContainerService, 18421 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18422 if (allData) { 18423 clearDirectory(conn.mContainerService, 18424 userEnv.buildExternalStorageAppDataDirs(packageName)); 18425 clearDirectory(conn.mContainerService, 18426 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18427 } 18428 } 18429 } finally { 18430 mContext.unbindService(conn); 18431 } 18432 } 18433 } 18434 18435 @Override 18436 public void clearApplicationProfileData(String packageName) { 18437 enforceSystemOrRoot("Only the system can clear all profile data"); 18438 18439 final PackageParser.Package pkg; 18440 synchronized (mPackages) { 18441 pkg = mPackages.get(packageName); 18442 } 18443 18444 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18445 synchronized (mInstallLock) { 18446 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18447 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18448 true /* removeBaseMarker */); 18449 } 18450 } 18451 } 18452 18453 @Override 18454 public void clearApplicationUserData(final String packageName, 18455 final IPackageDataObserver observer, final int userId) { 18456 mContext.enforceCallingOrSelfPermission( 18457 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18458 18459 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18460 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18461 18462 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18463 throw new SecurityException("Cannot clear data for a protected package: " 18464 + packageName); 18465 } 18466 // Queue up an async operation since the package deletion may take a little while. 18467 mHandler.post(new Runnable() { 18468 public void run() { 18469 mHandler.removeCallbacks(this); 18470 final boolean succeeded; 18471 try (PackageFreezer freezer = freezePackage(packageName, 18472 "clearApplicationUserData")) { 18473 synchronized (mInstallLock) { 18474 succeeded = clearApplicationUserDataLIF(packageName, userId); 18475 } 18476 clearExternalStorageDataSync(packageName, userId, true); 18477 synchronized (mPackages) { 18478 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18479 packageName, userId); 18480 } 18481 } 18482 if (succeeded) { 18483 // invoke DeviceStorageMonitor's update method to clear any notifications 18484 DeviceStorageMonitorInternal dsm = LocalServices 18485 .getService(DeviceStorageMonitorInternal.class); 18486 if (dsm != null) { 18487 dsm.checkMemory(); 18488 } 18489 } 18490 if(observer != null) { 18491 try { 18492 observer.onRemoveCompleted(packageName, succeeded); 18493 } catch (RemoteException e) { 18494 Log.i(TAG, "Observer no longer exists."); 18495 } 18496 } //end if observer 18497 } //end run 18498 }); 18499 } 18500 18501 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18502 if (packageName == null) { 18503 Slog.w(TAG, "Attempt to delete null packageName."); 18504 return false; 18505 } 18506 18507 // Try finding details about the requested package 18508 PackageParser.Package pkg; 18509 synchronized (mPackages) { 18510 pkg = mPackages.get(packageName); 18511 if (pkg == null) { 18512 final PackageSetting ps = mSettings.mPackages.get(packageName); 18513 if (ps != null) { 18514 pkg = ps.pkg; 18515 } 18516 } 18517 18518 if (pkg == null) { 18519 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18520 return false; 18521 } 18522 18523 PackageSetting ps = (PackageSetting) pkg.mExtras; 18524 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18525 } 18526 18527 clearAppDataLIF(pkg, userId, 18528 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18529 18530 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18531 removeKeystoreDataIfNeeded(userId, appId); 18532 18533 UserManagerInternal umInternal = getUserManagerInternal(); 18534 final int flags; 18535 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18536 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18537 } else if (umInternal.isUserRunning(userId)) { 18538 flags = StorageManager.FLAG_STORAGE_DE; 18539 } else { 18540 flags = 0; 18541 } 18542 prepareAppDataContentsLIF(pkg, userId, flags); 18543 18544 return true; 18545 } 18546 18547 /** 18548 * Reverts user permission state changes (permissions and flags) in 18549 * all packages for a given user. 18550 * 18551 * @param userId The device user for which to do a reset. 18552 */ 18553 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18554 final int packageCount = mPackages.size(); 18555 for (int i = 0; i < packageCount; i++) { 18556 PackageParser.Package pkg = mPackages.valueAt(i); 18557 PackageSetting ps = (PackageSetting) pkg.mExtras; 18558 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18559 } 18560 } 18561 18562 private void resetNetworkPolicies(int userId) { 18563 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18564 } 18565 18566 /** 18567 * Reverts user permission state changes (permissions and flags). 18568 * 18569 * @param ps The package for which to reset. 18570 * @param userId The device user for which to do a reset. 18571 */ 18572 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18573 final PackageSetting ps, final int userId) { 18574 if (ps.pkg == null) { 18575 return; 18576 } 18577 18578 // These are flags that can change base on user actions. 18579 final int userSettableMask = FLAG_PERMISSION_USER_SET 18580 | FLAG_PERMISSION_USER_FIXED 18581 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18582 | FLAG_PERMISSION_REVIEW_REQUIRED; 18583 18584 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18585 | FLAG_PERMISSION_POLICY_FIXED; 18586 18587 boolean writeInstallPermissions = false; 18588 boolean writeRuntimePermissions = false; 18589 18590 final int permissionCount = ps.pkg.requestedPermissions.size(); 18591 for (int i = 0; i < permissionCount; i++) { 18592 String permission = ps.pkg.requestedPermissions.get(i); 18593 18594 BasePermission bp = mSettings.mPermissions.get(permission); 18595 if (bp == null) { 18596 continue; 18597 } 18598 18599 // If shared user we just reset the state to which only this app contributed. 18600 if (ps.sharedUser != null) { 18601 boolean used = false; 18602 final int packageCount = ps.sharedUser.packages.size(); 18603 for (int j = 0; j < packageCount; j++) { 18604 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18605 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18606 && pkg.pkg.requestedPermissions.contains(permission)) { 18607 used = true; 18608 break; 18609 } 18610 } 18611 if (used) { 18612 continue; 18613 } 18614 } 18615 18616 PermissionsState permissionsState = ps.getPermissionsState(); 18617 18618 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18619 18620 // Always clear the user settable flags. 18621 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18622 bp.name) != null; 18623 // If permission review is enabled and this is a legacy app, mark the 18624 // permission as requiring a review as this is the initial state. 18625 int flags = 0; 18626 if (mPermissionReviewRequired 18627 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18628 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18629 } 18630 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18631 if (hasInstallState) { 18632 writeInstallPermissions = true; 18633 } else { 18634 writeRuntimePermissions = true; 18635 } 18636 } 18637 18638 // Below is only runtime permission handling. 18639 if (!bp.isRuntime()) { 18640 continue; 18641 } 18642 18643 // Never clobber system or policy. 18644 if ((oldFlags & policyOrSystemFlags) != 0) { 18645 continue; 18646 } 18647 18648 // If this permission was granted by default, make sure it is. 18649 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18650 if (permissionsState.grantRuntimePermission(bp, userId) 18651 != PERMISSION_OPERATION_FAILURE) { 18652 writeRuntimePermissions = true; 18653 } 18654 // If permission review is enabled the permissions for a legacy apps 18655 // are represented as constantly granted runtime ones, so don't revoke. 18656 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18657 // Otherwise, reset the permission. 18658 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18659 switch (revokeResult) { 18660 case PERMISSION_OPERATION_SUCCESS: 18661 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18662 writeRuntimePermissions = true; 18663 final int appId = ps.appId; 18664 mHandler.post(new Runnable() { 18665 @Override 18666 public void run() { 18667 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18668 } 18669 }); 18670 } break; 18671 } 18672 } 18673 } 18674 18675 // Synchronously write as we are taking permissions away. 18676 if (writeRuntimePermissions) { 18677 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18678 } 18679 18680 // Synchronously write as we are taking permissions away. 18681 if (writeInstallPermissions) { 18682 mSettings.writeLPr(); 18683 } 18684 } 18685 18686 /** 18687 * Remove entries from the keystore daemon. Will only remove it if the 18688 * {@code appId} is valid. 18689 */ 18690 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18691 if (appId < 0) { 18692 return; 18693 } 18694 18695 final KeyStore keyStore = KeyStore.getInstance(); 18696 if (keyStore != null) { 18697 if (userId == UserHandle.USER_ALL) { 18698 for (final int individual : sUserManager.getUserIds()) { 18699 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18700 } 18701 } else { 18702 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18703 } 18704 } else { 18705 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18706 } 18707 } 18708 18709 @Override 18710 public void deleteApplicationCacheFiles(final String packageName, 18711 final IPackageDataObserver observer) { 18712 final int userId = UserHandle.getCallingUserId(); 18713 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18714 } 18715 18716 @Override 18717 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18718 final IPackageDataObserver observer) { 18719 mContext.enforceCallingOrSelfPermission( 18720 android.Manifest.permission.DELETE_CACHE_FILES, null); 18721 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18722 /* requireFullPermission= */ true, /* checkShell= */ false, 18723 "delete application cache files"); 18724 18725 final PackageParser.Package pkg; 18726 synchronized (mPackages) { 18727 pkg = mPackages.get(packageName); 18728 } 18729 18730 // Queue up an async operation since the package deletion may take a little while. 18731 mHandler.post(new Runnable() { 18732 public void run() { 18733 synchronized (mInstallLock) { 18734 final int flags = StorageManager.FLAG_STORAGE_DE 18735 | StorageManager.FLAG_STORAGE_CE; 18736 // We're only clearing cache files, so we don't care if the 18737 // app is unfrozen and still able to run 18738 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18739 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18740 } 18741 clearExternalStorageDataSync(packageName, userId, false); 18742 if (observer != null) { 18743 try { 18744 observer.onRemoveCompleted(packageName, true); 18745 } catch (RemoteException e) { 18746 Log.i(TAG, "Observer no longer exists."); 18747 } 18748 } 18749 } 18750 }); 18751 } 18752 18753 @Override 18754 public void getPackageSizeInfo(final String packageName, int userHandle, 18755 final IPackageStatsObserver observer) { 18756 Slog.w(TAG, "Shame on you for calling a hidden API. Shame!"); 18757 try { 18758 observer.onGetStatsCompleted(null, false); 18759 } catch (RemoteException ignored) { 18760 } 18761 } 18762 18763 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18764 final PackageSetting ps; 18765 synchronized (mPackages) { 18766 ps = mSettings.mPackages.get(packageName); 18767 if (ps == null) { 18768 Slog.w(TAG, "Failed to find settings for " + packageName); 18769 return false; 18770 } 18771 } 18772 18773 final String[] packageNames = { packageName }; 18774 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18775 final String[] codePaths = { ps.codePathString }; 18776 18777 try { 18778 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18779 ps.appId, ceDataInodes, codePaths, stats); 18780 18781 // For now, ignore code size of packages on system partition 18782 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18783 stats.codeSize = 0; 18784 } 18785 18786 // External clients expect these to be tracked separately 18787 stats.dataSize -= stats.cacheSize; 18788 18789 } catch (InstallerException e) { 18790 Slog.w(TAG, String.valueOf(e)); 18791 return false; 18792 } 18793 18794 return true; 18795 } 18796 18797 private int getUidTargetSdkVersionLockedLPr(int uid) { 18798 Object obj = mSettings.getUserIdLPr(uid); 18799 if (obj instanceof SharedUserSetting) { 18800 final SharedUserSetting sus = (SharedUserSetting) obj; 18801 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18802 final Iterator<PackageSetting> it = sus.packages.iterator(); 18803 while (it.hasNext()) { 18804 final PackageSetting ps = it.next(); 18805 if (ps.pkg != null) { 18806 int v = ps.pkg.applicationInfo.targetSdkVersion; 18807 if (v < vers) vers = v; 18808 } 18809 } 18810 return vers; 18811 } else if (obj instanceof PackageSetting) { 18812 final PackageSetting ps = (PackageSetting) obj; 18813 if (ps.pkg != null) { 18814 return ps.pkg.applicationInfo.targetSdkVersion; 18815 } 18816 } 18817 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18818 } 18819 18820 @Override 18821 public void addPreferredActivity(IntentFilter filter, int match, 18822 ComponentName[] set, ComponentName activity, int userId) { 18823 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18824 "Adding preferred"); 18825 } 18826 18827 private void addPreferredActivityInternal(IntentFilter filter, int match, 18828 ComponentName[] set, ComponentName activity, boolean always, int userId, 18829 String opname) { 18830 // writer 18831 int callingUid = Binder.getCallingUid(); 18832 enforceCrossUserPermission(callingUid, userId, 18833 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18834 if (filter.countActions() == 0) { 18835 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18836 return; 18837 } 18838 synchronized (mPackages) { 18839 if (mContext.checkCallingOrSelfPermission( 18840 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18841 != PackageManager.PERMISSION_GRANTED) { 18842 if (getUidTargetSdkVersionLockedLPr(callingUid) 18843 < Build.VERSION_CODES.FROYO) { 18844 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18845 + callingUid); 18846 return; 18847 } 18848 mContext.enforceCallingOrSelfPermission( 18849 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18850 } 18851 18852 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18853 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18854 + userId + ":"); 18855 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18856 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18857 scheduleWritePackageRestrictionsLocked(userId); 18858 postPreferredActivityChangedBroadcast(userId); 18859 } 18860 } 18861 18862 private void postPreferredActivityChangedBroadcast(int userId) { 18863 mHandler.post(() -> { 18864 final IActivityManager am = ActivityManager.getService(); 18865 if (am == null) { 18866 return; 18867 } 18868 18869 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18870 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18871 try { 18872 am.broadcastIntent(null, intent, null, null, 18873 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18874 null, false, false, userId); 18875 } catch (RemoteException e) { 18876 } 18877 }); 18878 } 18879 18880 @Override 18881 public void replacePreferredActivity(IntentFilter filter, int match, 18882 ComponentName[] set, ComponentName activity, int userId) { 18883 if (filter.countActions() != 1) { 18884 throw new IllegalArgumentException( 18885 "replacePreferredActivity expects filter to have only 1 action."); 18886 } 18887 if (filter.countDataAuthorities() != 0 18888 || filter.countDataPaths() != 0 18889 || filter.countDataSchemes() > 1 18890 || filter.countDataTypes() != 0) { 18891 throw new IllegalArgumentException( 18892 "replacePreferredActivity expects filter to have no data authorities, " + 18893 "paths, or types; and at most one scheme."); 18894 } 18895 18896 final int callingUid = Binder.getCallingUid(); 18897 enforceCrossUserPermission(callingUid, userId, 18898 true /* requireFullPermission */, false /* checkShell */, 18899 "replace preferred activity"); 18900 synchronized (mPackages) { 18901 if (mContext.checkCallingOrSelfPermission( 18902 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18903 != PackageManager.PERMISSION_GRANTED) { 18904 if (getUidTargetSdkVersionLockedLPr(callingUid) 18905 < Build.VERSION_CODES.FROYO) { 18906 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18907 + Binder.getCallingUid()); 18908 return; 18909 } 18910 mContext.enforceCallingOrSelfPermission( 18911 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18912 } 18913 18914 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18915 if (pir != null) { 18916 // Get all of the existing entries that exactly match this filter. 18917 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18918 if (existing != null && existing.size() == 1) { 18919 PreferredActivity cur = existing.get(0); 18920 if (DEBUG_PREFERRED) { 18921 Slog.i(TAG, "Checking replace of preferred:"); 18922 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18923 if (!cur.mPref.mAlways) { 18924 Slog.i(TAG, " -- CUR; not mAlways!"); 18925 } else { 18926 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18927 Slog.i(TAG, " -- CUR: mSet=" 18928 + Arrays.toString(cur.mPref.mSetComponents)); 18929 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18930 Slog.i(TAG, " -- NEW: mMatch=" 18931 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18932 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18933 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18934 } 18935 } 18936 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18937 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18938 && cur.mPref.sameSet(set)) { 18939 // Setting the preferred activity to what it happens to be already 18940 if (DEBUG_PREFERRED) { 18941 Slog.i(TAG, "Replacing with same preferred activity " 18942 + cur.mPref.mShortComponent + " for user " 18943 + userId + ":"); 18944 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18945 } 18946 return; 18947 } 18948 } 18949 18950 if (existing != null) { 18951 if (DEBUG_PREFERRED) { 18952 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18953 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18954 } 18955 for (int i = 0; i < existing.size(); i++) { 18956 PreferredActivity pa = existing.get(i); 18957 if (DEBUG_PREFERRED) { 18958 Slog.i(TAG, "Removing existing preferred activity " 18959 + pa.mPref.mComponent + ":"); 18960 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18961 } 18962 pir.removeFilter(pa); 18963 } 18964 } 18965 } 18966 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18967 "Replacing preferred"); 18968 } 18969 } 18970 18971 @Override 18972 public void clearPackagePreferredActivities(String packageName) { 18973 final int uid = Binder.getCallingUid(); 18974 // writer 18975 synchronized (mPackages) { 18976 PackageParser.Package pkg = mPackages.get(packageName); 18977 if (pkg == null || pkg.applicationInfo.uid != uid) { 18978 if (mContext.checkCallingOrSelfPermission( 18979 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18980 != PackageManager.PERMISSION_GRANTED) { 18981 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18982 < Build.VERSION_CODES.FROYO) { 18983 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18984 + Binder.getCallingUid()); 18985 return; 18986 } 18987 mContext.enforceCallingOrSelfPermission( 18988 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18989 } 18990 } 18991 18992 int user = UserHandle.getCallingUserId(); 18993 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18994 scheduleWritePackageRestrictionsLocked(user); 18995 } 18996 } 18997 } 18998 18999 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19000 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19001 ArrayList<PreferredActivity> removed = null; 19002 boolean changed = false; 19003 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19004 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19005 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19006 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19007 continue; 19008 } 19009 Iterator<PreferredActivity> it = pir.filterIterator(); 19010 while (it.hasNext()) { 19011 PreferredActivity pa = it.next(); 19012 // Mark entry for removal only if it matches the package name 19013 // and the entry is of type "always". 19014 if (packageName == null || 19015 (pa.mPref.mComponent.getPackageName().equals(packageName) 19016 && pa.mPref.mAlways)) { 19017 if (removed == null) { 19018 removed = new ArrayList<PreferredActivity>(); 19019 } 19020 removed.add(pa); 19021 } 19022 } 19023 if (removed != null) { 19024 for (int j=0; j<removed.size(); j++) { 19025 PreferredActivity pa = removed.get(j); 19026 pir.removeFilter(pa); 19027 } 19028 changed = true; 19029 } 19030 } 19031 if (changed) { 19032 postPreferredActivityChangedBroadcast(userId); 19033 } 19034 return changed; 19035 } 19036 19037 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19038 private void clearIntentFilterVerificationsLPw(int userId) { 19039 final int packageCount = mPackages.size(); 19040 for (int i = 0; i < packageCount; i++) { 19041 PackageParser.Package pkg = mPackages.valueAt(i); 19042 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19043 } 19044 } 19045 19046 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19047 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19048 if (userId == UserHandle.USER_ALL) { 19049 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19050 sUserManager.getUserIds())) { 19051 for (int oneUserId : sUserManager.getUserIds()) { 19052 scheduleWritePackageRestrictionsLocked(oneUserId); 19053 } 19054 } 19055 } else { 19056 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19057 scheduleWritePackageRestrictionsLocked(userId); 19058 } 19059 } 19060 } 19061 19062 void clearDefaultBrowserIfNeeded(String packageName) { 19063 for (int oneUserId : sUserManager.getUserIds()) { 19064 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19065 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19066 if (packageName.equals(defaultBrowserPackageName)) { 19067 setDefaultBrowserPackageName(null, oneUserId); 19068 } 19069 } 19070 } 19071 19072 @Override 19073 public void resetApplicationPreferences(int userId) { 19074 mContext.enforceCallingOrSelfPermission( 19075 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19076 final long identity = Binder.clearCallingIdentity(); 19077 // writer 19078 try { 19079 synchronized (mPackages) { 19080 clearPackagePreferredActivitiesLPw(null, userId); 19081 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19082 // TODO: We have to reset the default SMS and Phone. This requires 19083 // significant refactoring to keep all default apps in the package 19084 // manager (cleaner but more work) or have the services provide 19085 // callbacks to the package manager to request a default app reset. 19086 applyFactoryDefaultBrowserLPw(userId); 19087 clearIntentFilterVerificationsLPw(userId); 19088 primeDomainVerificationsLPw(userId); 19089 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19090 scheduleWritePackageRestrictionsLocked(userId); 19091 } 19092 resetNetworkPolicies(userId); 19093 } finally { 19094 Binder.restoreCallingIdentity(identity); 19095 } 19096 } 19097 19098 @Override 19099 public int getPreferredActivities(List<IntentFilter> outFilters, 19100 List<ComponentName> outActivities, String packageName) { 19101 19102 int num = 0; 19103 final int userId = UserHandle.getCallingUserId(); 19104 // reader 19105 synchronized (mPackages) { 19106 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19107 if (pir != null) { 19108 final Iterator<PreferredActivity> it = pir.filterIterator(); 19109 while (it.hasNext()) { 19110 final PreferredActivity pa = it.next(); 19111 if (packageName == null 19112 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19113 && pa.mPref.mAlways)) { 19114 if (outFilters != null) { 19115 outFilters.add(new IntentFilter(pa)); 19116 } 19117 if (outActivities != null) { 19118 outActivities.add(pa.mPref.mComponent); 19119 } 19120 } 19121 } 19122 } 19123 } 19124 19125 return num; 19126 } 19127 19128 @Override 19129 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19130 int userId) { 19131 int callingUid = Binder.getCallingUid(); 19132 if (callingUid != Process.SYSTEM_UID) { 19133 throw new SecurityException( 19134 "addPersistentPreferredActivity can only be run by the system"); 19135 } 19136 if (filter.countActions() == 0) { 19137 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19138 return; 19139 } 19140 synchronized (mPackages) { 19141 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19142 ":"); 19143 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19144 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19145 new PersistentPreferredActivity(filter, activity)); 19146 scheduleWritePackageRestrictionsLocked(userId); 19147 postPreferredActivityChangedBroadcast(userId); 19148 } 19149 } 19150 19151 @Override 19152 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19153 int callingUid = Binder.getCallingUid(); 19154 if (callingUid != Process.SYSTEM_UID) { 19155 throw new SecurityException( 19156 "clearPackagePersistentPreferredActivities can only be run by the system"); 19157 } 19158 ArrayList<PersistentPreferredActivity> removed = null; 19159 boolean changed = false; 19160 synchronized (mPackages) { 19161 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19162 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19163 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19164 .valueAt(i); 19165 if (userId != thisUserId) { 19166 continue; 19167 } 19168 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19169 while (it.hasNext()) { 19170 PersistentPreferredActivity ppa = it.next(); 19171 // Mark entry for removal only if it matches the package name. 19172 if (ppa.mComponent.getPackageName().equals(packageName)) { 19173 if (removed == null) { 19174 removed = new ArrayList<PersistentPreferredActivity>(); 19175 } 19176 removed.add(ppa); 19177 } 19178 } 19179 if (removed != null) { 19180 for (int j=0; j<removed.size(); j++) { 19181 PersistentPreferredActivity ppa = removed.get(j); 19182 ppir.removeFilter(ppa); 19183 } 19184 changed = true; 19185 } 19186 } 19187 19188 if (changed) { 19189 scheduleWritePackageRestrictionsLocked(userId); 19190 postPreferredActivityChangedBroadcast(userId); 19191 } 19192 } 19193 } 19194 19195 /** 19196 * Common machinery for picking apart a restored XML blob and passing 19197 * it to a caller-supplied functor to be applied to the running system. 19198 */ 19199 private void restoreFromXml(XmlPullParser parser, int userId, 19200 String expectedStartTag, BlobXmlRestorer functor) 19201 throws IOException, XmlPullParserException { 19202 int type; 19203 while ((type = parser.next()) != XmlPullParser.START_TAG 19204 && type != XmlPullParser.END_DOCUMENT) { 19205 } 19206 if (type != XmlPullParser.START_TAG) { 19207 // oops didn't find a start tag?! 19208 if (DEBUG_BACKUP) { 19209 Slog.e(TAG, "Didn't find start tag during restore"); 19210 } 19211 return; 19212 } 19213Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19214 // this is supposed to be TAG_PREFERRED_BACKUP 19215 if (!expectedStartTag.equals(parser.getName())) { 19216 if (DEBUG_BACKUP) { 19217 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19218 } 19219 return; 19220 } 19221 19222 // skip interfering stuff, then we're aligned with the backing implementation 19223 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19224Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19225 functor.apply(parser, userId); 19226 } 19227 19228 private interface BlobXmlRestorer { 19229 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19230 } 19231 19232 /** 19233 * Non-Binder method, support for the backup/restore mechanism: write the 19234 * full set of preferred activities in its canonical XML format. Returns the 19235 * XML output as a byte array, or null if there is none. 19236 */ 19237 @Override 19238 public byte[] getPreferredActivityBackup(int userId) { 19239 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19240 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19241 } 19242 19243 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19244 try { 19245 final XmlSerializer serializer = new FastXmlSerializer(); 19246 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19247 serializer.startDocument(null, true); 19248 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19249 19250 synchronized (mPackages) { 19251 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19252 } 19253 19254 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19255 serializer.endDocument(); 19256 serializer.flush(); 19257 } catch (Exception e) { 19258 if (DEBUG_BACKUP) { 19259 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19260 } 19261 return null; 19262 } 19263 19264 return dataStream.toByteArray(); 19265 } 19266 19267 @Override 19268 public void restorePreferredActivities(byte[] backup, int userId) { 19269 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19270 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19271 } 19272 19273 try { 19274 final XmlPullParser parser = Xml.newPullParser(); 19275 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19276 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19277 new BlobXmlRestorer() { 19278 @Override 19279 public void apply(XmlPullParser parser, int userId) 19280 throws XmlPullParserException, IOException { 19281 synchronized (mPackages) { 19282 mSettings.readPreferredActivitiesLPw(parser, userId); 19283 } 19284 } 19285 } ); 19286 } catch (Exception e) { 19287 if (DEBUG_BACKUP) { 19288 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19289 } 19290 } 19291 } 19292 19293 /** 19294 * Non-Binder method, support for the backup/restore mechanism: write the 19295 * default browser (etc) settings in its canonical XML format. Returns the default 19296 * browser XML representation as a byte array, or null if there is none. 19297 */ 19298 @Override 19299 public byte[] getDefaultAppsBackup(int userId) { 19300 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19301 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19302 } 19303 19304 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19305 try { 19306 final XmlSerializer serializer = new FastXmlSerializer(); 19307 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19308 serializer.startDocument(null, true); 19309 serializer.startTag(null, TAG_DEFAULT_APPS); 19310 19311 synchronized (mPackages) { 19312 mSettings.writeDefaultAppsLPr(serializer, userId); 19313 } 19314 19315 serializer.endTag(null, TAG_DEFAULT_APPS); 19316 serializer.endDocument(); 19317 serializer.flush(); 19318 } catch (Exception e) { 19319 if (DEBUG_BACKUP) { 19320 Slog.e(TAG, "Unable to write default apps for backup", e); 19321 } 19322 return null; 19323 } 19324 19325 return dataStream.toByteArray(); 19326 } 19327 19328 @Override 19329 public void restoreDefaultApps(byte[] backup, int userId) { 19330 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19331 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19332 } 19333 19334 try { 19335 final XmlPullParser parser = Xml.newPullParser(); 19336 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19337 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19338 new BlobXmlRestorer() { 19339 @Override 19340 public void apply(XmlPullParser parser, int userId) 19341 throws XmlPullParserException, IOException { 19342 synchronized (mPackages) { 19343 mSettings.readDefaultAppsLPw(parser, userId); 19344 } 19345 } 19346 } ); 19347 } catch (Exception e) { 19348 if (DEBUG_BACKUP) { 19349 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19350 } 19351 } 19352 } 19353 19354 @Override 19355 public byte[] getIntentFilterVerificationBackup(int userId) { 19356 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19357 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19358 } 19359 19360 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19361 try { 19362 final XmlSerializer serializer = new FastXmlSerializer(); 19363 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19364 serializer.startDocument(null, true); 19365 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19366 19367 synchronized (mPackages) { 19368 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19369 } 19370 19371 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19372 serializer.endDocument(); 19373 serializer.flush(); 19374 } catch (Exception e) { 19375 if (DEBUG_BACKUP) { 19376 Slog.e(TAG, "Unable to write default apps for backup", e); 19377 } 19378 return null; 19379 } 19380 19381 return dataStream.toByteArray(); 19382 } 19383 19384 @Override 19385 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19386 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19387 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19388 } 19389 19390 try { 19391 final XmlPullParser parser = Xml.newPullParser(); 19392 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19393 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19394 new BlobXmlRestorer() { 19395 @Override 19396 public void apply(XmlPullParser parser, int userId) 19397 throws XmlPullParserException, IOException { 19398 synchronized (mPackages) { 19399 mSettings.readAllDomainVerificationsLPr(parser, userId); 19400 mSettings.writeLPr(); 19401 } 19402 } 19403 } ); 19404 } catch (Exception e) { 19405 if (DEBUG_BACKUP) { 19406 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19407 } 19408 } 19409 } 19410 19411 @Override 19412 public byte[] getPermissionGrantBackup(int userId) { 19413 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19414 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19415 } 19416 19417 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19418 try { 19419 final XmlSerializer serializer = new FastXmlSerializer(); 19420 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19421 serializer.startDocument(null, true); 19422 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19423 19424 synchronized (mPackages) { 19425 serializeRuntimePermissionGrantsLPr(serializer, userId); 19426 } 19427 19428 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19429 serializer.endDocument(); 19430 serializer.flush(); 19431 } catch (Exception e) { 19432 if (DEBUG_BACKUP) { 19433 Slog.e(TAG, "Unable to write default apps for backup", e); 19434 } 19435 return null; 19436 } 19437 19438 return dataStream.toByteArray(); 19439 } 19440 19441 @Override 19442 public void restorePermissionGrants(byte[] backup, int userId) { 19443 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19444 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19445 } 19446 19447 try { 19448 final XmlPullParser parser = Xml.newPullParser(); 19449 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19450 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19451 new BlobXmlRestorer() { 19452 @Override 19453 public void apply(XmlPullParser parser, int userId) 19454 throws XmlPullParserException, IOException { 19455 synchronized (mPackages) { 19456 processRestoredPermissionGrantsLPr(parser, userId); 19457 } 19458 } 19459 } ); 19460 } catch (Exception e) { 19461 if (DEBUG_BACKUP) { 19462 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19463 } 19464 } 19465 } 19466 19467 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19468 throws IOException { 19469 serializer.startTag(null, TAG_ALL_GRANTS); 19470 19471 final int N = mSettings.mPackages.size(); 19472 for (int i = 0; i < N; i++) { 19473 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19474 boolean pkgGrantsKnown = false; 19475 19476 PermissionsState packagePerms = ps.getPermissionsState(); 19477 19478 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19479 final int grantFlags = state.getFlags(); 19480 // only look at grants that are not system/policy fixed 19481 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19482 final boolean isGranted = state.isGranted(); 19483 // And only back up the user-twiddled state bits 19484 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19485 final String packageName = mSettings.mPackages.keyAt(i); 19486 if (!pkgGrantsKnown) { 19487 serializer.startTag(null, TAG_GRANT); 19488 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19489 pkgGrantsKnown = true; 19490 } 19491 19492 final boolean userSet = 19493 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19494 final boolean userFixed = 19495 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19496 final boolean revoke = 19497 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19498 19499 serializer.startTag(null, TAG_PERMISSION); 19500 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19501 if (isGranted) { 19502 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19503 } 19504 if (userSet) { 19505 serializer.attribute(null, ATTR_USER_SET, "true"); 19506 } 19507 if (userFixed) { 19508 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19509 } 19510 if (revoke) { 19511 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19512 } 19513 serializer.endTag(null, TAG_PERMISSION); 19514 } 19515 } 19516 } 19517 19518 if (pkgGrantsKnown) { 19519 serializer.endTag(null, TAG_GRANT); 19520 } 19521 } 19522 19523 serializer.endTag(null, TAG_ALL_GRANTS); 19524 } 19525 19526 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19527 throws XmlPullParserException, IOException { 19528 String pkgName = null; 19529 int outerDepth = parser.getDepth(); 19530 int type; 19531 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19532 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19533 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19534 continue; 19535 } 19536 19537 final String tagName = parser.getName(); 19538 if (tagName.equals(TAG_GRANT)) { 19539 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19540 if (DEBUG_BACKUP) { 19541 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19542 } 19543 } else if (tagName.equals(TAG_PERMISSION)) { 19544 19545 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19546 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19547 19548 int newFlagSet = 0; 19549 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19550 newFlagSet |= FLAG_PERMISSION_USER_SET; 19551 } 19552 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19553 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19554 } 19555 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19556 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19557 } 19558 if (DEBUG_BACKUP) { 19559 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19560 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19561 } 19562 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19563 if (ps != null) { 19564 // Already installed so we apply the grant immediately 19565 if (DEBUG_BACKUP) { 19566 Slog.v(TAG, " + already installed; applying"); 19567 } 19568 PermissionsState perms = ps.getPermissionsState(); 19569 BasePermission bp = mSettings.mPermissions.get(permName); 19570 if (bp != null) { 19571 if (isGranted) { 19572 perms.grantRuntimePermission(bp, userId); 19573 } 19574 if (newFlagSet != 0) { 19575 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19576 } 19577 } 19578 } else { 19579 // Need to wait for post-restore install to apply the grant 19580 if (DEBUG_BACKUP) { 19581 Slog.v(TAG, " - not yet installed; saving for later"); 19582 } 19583 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19584 isGranted, newFlagSet, userId); 19585 } 19586 } else { 19587 PackageManagerService.reportSettingsProblem(Log.WARN, 19588 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19589 XmlUtils.skipCurrentTag(parser); 19590 } 19591 } 19592 19593 scheduleWriteSettingsLocked(); 19594 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19595 } 19596 19597 @Override 19598 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19599 int sourceUserId, int targetUserId, int flags) { 19600 mContext.enforceCallingOrSelfPermission( 19601 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19602 int callingUid = Binder.getCallingUid(); 19603 enforceOwnerRights(ownerPackage, callingUid); 19604 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19605 if (intentFilter.countActions() == 0) { 19606 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19607 return; 19608 } 19609 synchronized (mPackages) { 19610 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19611 ownerPackage, targetUserId, flags); 19612 CrossProfileIntentResolver resolver = 19613 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19614 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19615 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19616 if (existing != null) { 19617 int size = existing.size(); 19618 for (int i = 0; i < size; i++) { 19619 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19620 return; 19621 } 19622 } 19623 } 19624 resolver.addFilter(newFilter); 19625 scheduleWritePackageRestrictionsLocked(sourceUserId); 19626 } 19627 } 19628 19629 @Override 19630 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19631 mContext.enforceCallingOrSelfPermission( 19632 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19633 int callingUid = Binder.getCallingUid(); 19634 enforceOwnerRights(ownerPackage, callingUid); 19635 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19636 synchronized (mPackages) { 19637 CrossProfileIntentResolver resolver = 19638 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19639 ArraySet<CrossProfileIntentFilter> set = 19640 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19641 for (CrossProfileIntentFilter filter : set) { 19642 if (filter.getOwnerPackage().equals(ownerPackage)) { 19643 resolver.removeFilter(filter); 19644 } 19645 } 19646 scheduleWritePackageRestrictionsLocked(sourceUserId); 19647 } 19648 } 19649 19650 // Enforcing that callingUid is owning pkg on userId 19651 private void enforceOwnerRights(String pkg, int callingUid) { 19652 // The system owns everything. 19653 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19654 return; 19655 } 19656 int callingUserId = UserHandle.getUserId(callingUid); 19657 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19658 if (pi == null) { 19659 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19660 + callingUserId); 19661 } 19662 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19663 throw new SecurityException("Calling uid " + callingUid 19664 + " does not own package " + pkg); 19665 } 19666 } 19667 19668 @Override 19669 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19670 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19671 } 19672 19673 private Intent getHomeIntent() { 19674 Intent intent = new Intent(Intent.ACTION_MAIN); 19675 intent.addCategory(Intent.CATEGORY_HOME); 19676 intent.addCategory(Intent.CATEGORY_DEFAULT); 19677 return intent; 19678 } 19679 19680 private IntentFilter getHomeFilter() { 19681 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19682 filter.addCategory(Intent.CATEGORY_HOME); 19683 filter.addCategory(Intent.CATEGORY_DEFAULT); 19684 return filter; 19685 } 19686 19687 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19688 int userId) { 19689 Intent intent = getHomeIntent(); 19690 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19691 PackageManager.GET_META_DATA, userId); 19692 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19693 true, false, false, userId); 19694 19695 allHomeCandidates.clear(); 19696 if (list != null) { 19697 for (ResolveInfo ri : list) { 19698 allHomeCandidates.add(ri); 19699 } 19700 } 19701 return (preferred == null || preferred.activityInfo == null) 19702 ? null 19703 : new ComponentName(preferred.activityInfo.packageName, 19704 preferred.activityInfo.name); 19705 } 19706 19707 @Override 19708 public void setHomeActivity(ComponentName comp, int userId) { 19709 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19710 getHomeActivitiesAsUser(homeActivities, userId); 19711 19712 boolean found = false; 19713 19714 final int size = homeActivities.size(); 19715 final ComponentName[] set = new ComponentName[size]; 19716 for (int i = 0; i < size; i++) { 19717 final ResolveInfo candidate = homeActivities.get(i); 19718 final ActivityInfo info = candidate.activityInfo; 19719 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19720 set[i] = activityName; 19721 if (!found && activityName.equals(comp)) { 19722 found = true; 19723 } 19724 } 19725 if (!found) { 19726 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19727 + userId); 19728 } 19729 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19730 set, comp, userId); 19731 } 19732 19733 private @Nullable String getSetupWizardPackageName() { 19734 final Intent intent = new Intent(Intent.ACTION_MAIN); 19735 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19736 19737 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19738 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19739 | MATCH_DISABLED_COMPONENTS, 19740 UserHandle.myUserId()); 19741 if (matches.size() == 1) { 19742 return matches.get(0).getComponentInfo().packageName; 19743 } else { 19744 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19745 + ": matches=" + matches); 19746 return null; 19747 } 19748 } 19749 19750 private @Nullable String getStorageManagerPackageName() { 19751 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19752 19753 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19754 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19755 | MATCH_DISABLED_COMPONENTS, 19756 UserHandle.myUserId()); 19757 if (matches.size() == 1) { 19758 return matches.get(0).getComponentInfo().packageName; 19759 } else { 19760 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19761 + matches.size() + ": matches=" + matches); 19762 return null; 19763 } 19764 } 19765 19766 @Override 19767 public void setApplicationEnabledSetting(String appPackageName, 19768 int newState, int flags, int userId, String callingPackage) { 19769 if (!sUserManager.exists(userId)) return; 19770 if (callingPackage == null) { 19771 callingPackage = Integer.toString(Binder.getCallingUid()); 19772 } 19773 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19774 } 19775 19776 @Override 19777 public void setComponentEnabledSetting(ComponentName componentName, 19778 int newState, int flags, int userId) { 19779 if (!sUserManager.exists(userId)) return; 19780 setEnabledSetting(componentName.getPackageName(), 19781 componentName.getClassName(), newState, flags, userId, null); 19782 } 19783 19784 private void setEnabledSetting(final String packageName, String className, int newState, 19785 final int flags, int userId, String callingPackage) { 19786 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19787 || newState == COMPONENT_ENABLED_STATE_ENABLED 19788 || newState == COMPONENT_ENABLED_STATE_DISABLED 19789 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19790 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19791 throw new IllegalArgumentException("Invalid new component state: " 19792 + newState); 19793 } 19794 PackageSetting pkgSetting; 19795 final int uid = Binder.getCallingUid(); 19796 final int permission; 19797 if (uid == Process.SYSTEM_UID) { 19798 permission = PackageManager.PERMISSION_GRANTED; 19799 } else { 19800 permission = mContext.checkCallingOrSelfPermission( 19801 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19802 } 19803 enforceCrossUserPermission(uid, userId, 19804 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19805 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19806 boolean sendNow = false; 19807 boolean isApp = (className == null); 19808 String componentName = isApp ? packageName : className; 19809 int packageUid = -1; 19810 ArrayList<String> components; 19811 19812 // writer 19813 synchronized (mPackages) { 19814 pkgSetting = mSettings.mPackages.get(packageName); 19815 if (pkgSetting == null) { 19816 if (className == null) { 19817 throw new IllegalArgumentException("Unknown package: " + packageName); 19818 } 19819 throw new IllegalArgumentException( 19820 "Unknown component: " + packageName + "/" + className); 19821 } 19822 } 19823 19824 // Limit who can change which apps 19825 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19826 // Don't allow apps that don't have permission to modify other apps 19827 if (!allowedByPermission) { 19828 throw new SecurityException( 19829 "Permission Denial: attempt to change component state from pid=" 19830 + Binder.getCallingPid() 19831 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19832 } 19833 // Don't allow changing protected packages. 19834 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19835 throw new SecurityException("Cannot disable a protected package: " + packageName); 19836 } 19837 } 19838 19839 synchronized (mPackages) { 19840 if (uid == Process.SHELL_UID 19841 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19842 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19843 // unless it is a test package. 19844 int oldState = pkgSetting.getEnabled(userId); 19845 if (className == null 19846 && 19847 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19848 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19849 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19850 && 19851 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19852 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19853 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19854 // ok 19855 } else { 19856 throw new SecurityException( 19857 "Shell cannot change component state for " + packageName + "/" 19858 + className + " to " + newState); 19859 } 19860 } 19861 if (className == null) { 19862 // We're dealing with an application/package level state change 19863 if (pkgSetting.getEnabled(userId) == newState) { 19864 // Nothing to do 19865 return; 19866 } 19867 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19868 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19869 // Don't care about who enables an app. 19870 callingPackage = null; 19871 } 19872 pkgSetting.setEnabled(newState, userId, callingPackage); 19873 // pkgSetting.pkg.mSetEnabled = newState; 19874 } else { 19875 // We're dealing with a component level state change 19876 // First, verify that this is a valid class name. 19877 PackageParser.Package pkg = pkgSetting.pkg; 19878 if (pkg == null || !pkg.hasComponentClassName(className)) { 19879 if (pkg != null && 19880 pkg.applicationInfo.targetSdkVersion >= 19881 Build.VERSION_CODES.JELLY_BEAN) { 19882 throw new IllegalArgumentException("Component class " + className 19883 + " does not exist in " + packageName); 19884 } else { 19885 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19886 + className + " does not exist in " + packageName); 19887 } 19888 } 19889 switch (newState) { 19890 case COMPONENT_ENABLED_STATE_ENABLED: 19891 if (!pkgSetting.enableComponentLPw(className, userId)) { 19892 return; 19893 } 19894 break; 19895 case COMPONENT_ENABLED_STATE_DISABLED: 19896 if (!pkgSetting.disableComponentLPw(className, userId)) { 19897 return; 19898 } 19899 break; 19900 case COMPONENT_ENABLED_STATE_DEFAULT: 19901 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19902 return; 19903 } 19904 break; 19905 default: 19906 Slog.e(TAG, "Invalid new component state: " + newState); 19907 return; 19908 } 19909 } 19910 scheduleWritePackageRestrictionsLocked(userId); 19911 updateSequenceNumberLP(packageName, new int[] { userId }); 19912 components = mPendingBroadcasts.get(userId, packageName); 19913 final boolean newPackage = components == null; 19914 if (newPackage) { 19915 components = new ArrayList<String>(); 19916 } 19917 if (!components.contains(componentName)) { 19918 components.add(componentName); 19919 } 19920 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19921 sendNow = true; 19922 // Purge entry from pending broadcast list if another one exists already 19923 // since we are sending one right away. 19924 mPendingBroadcasts.remove(userId, packageName); 19925 } else { 19926 if (newPackage) { 19927 mPendingBroadcasts.put(userId, packageName, components); 19928 } 19929 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19930 // Schedule a message 19931 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19932 } 19933 } 19934 } 19935 19936 long callingId = Binder.clearCallingIdentity(); 19937 try { 19938 if (sendNow) { 19939 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19940 sendPackageChangedBroadcast(packageName, 19941 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19942 } 19943 } finally { 19944 Binder.restoreCallingIdentity(callingId); 19945 } 19946 } 19947 19948 @Override 19949 public void flushPackageRestrictionsAsUser(int userId) { 19950 if (!sUserManager.exists(userId)) { 19951 return; 19952 } 19953 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19954 false /* checkShell */, "flushPackageRestrictions"); 19955 synchronized (mPackages) { 19956 mSettings.writePackageRestrictionsLPr(userId); 19957 mDirtyUsers.remove(userId); 19958 if (mDirtyUsers.isEmpty()) { 19959 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19960 } 19961 } 19962 } 19963 19964 private void sendPackageChangedBroadcast(String packageName, 19965 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19966 if (DEBUG_INSTALL) 19967 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19968 + componentNames); 19969 Bundle extras = new Bundle(4); 19970 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19971 String nameList[] = new String[componentNames.size()]; 19972 componentNames.toArray(nameList); 19973 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19974 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19975 extras.putInt(Intent.EXTRA_UID, packageUid); 19976 // If this is not reporting a change of the overall package, then only send it 19977 // to registered receivers. We don't want to launch a swath of apps for every 19978 // little component state change. 19979 final int flags = !componentNames.contains(packageName) 19980 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19981 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19982 new int[] {UserHandle.getUserId(packageUid)}); 19983 } 19984 19985 @Override 19986 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19987 if (!sUserManager.exists(userId)) return; 19988 final int uid = Binder.getCallingUid(); 19989 final int permission = mContext.checkCallingOrSelfPermission( 19990 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19991 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19992 enforceCrossUserPermission(uid, userId, 19993 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19994 // writer 19995 synchronized (mPackages) { 19996 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19997 allowedByPermission, uid, userId)) { 19998 scheduleWritePackageRestrictionsLocked(userId); 19999 } 20000 } 20001 } 20002 20003 @Override 20004 public String getInstallerPackageName(String packageName) { 20005 // reader 20006 synchronized (mPackages) { 20007 return mSettings.getInstallerPackageNameLPr(packageName); 20008 } 20009 } 20010 20011 public boolean isOrphaned(String packageName) { 20012 // reader 20013 synchronized (mPackages) { 20014 return mSettings.isOrphaned(packageName); 20015 } 20016 } 20017 20018 @Override 20019 public int getApplicationEnabledSetting(String packageName, int userId) { 20020 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20021 int uid = Binder.getCallingUid(); 20022 enforceCrossUserPermission(uid, userId, 20023 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20024 // reader 20025 synchronized (mPackages) { 20026 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20027 } 20028 } 20029 20030 @Override 20031 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20032 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20033 int uid = Binder.getCallingUid(); 20034 enforceCrossUserPermission(uid, userId, 20035 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20036 // reader 20037 synchronized (mPackages) { 20038 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20039 } 20040 } 20041 20042 @Override 20043 public void enterSafeMode() { 20044 enforceSystemOrRoot("Only the system can request entering safe mode"); 20045 20046 if (!mSystemReady) { 20047 mSafeMode = true; 20048 } 20049 } 20050 20051 @Override 20052 public void systemReady() { 20053 mSystemReady = true; 20054 20055 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20056 // disabled after already being started. 20057 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20058 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20059 20060 // Read the compatibilty setting when the system is ready. 20061 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20062 mContext.getContentResolver(), 20063 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20064 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20065 if (DEBUG_SETTINGS) { 20066 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20067 } 20068 20069 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20070 20071 synchronized (mPackages) { 20072 // Verify that all of the preferred activity components actually 20073 // exist. It is possible for applications to be updated and at 20074 // that point remove a previously declared activity component that 20075 // had been set as a preferred activity. We try to clean this up 20076 // the next time we encounter that preferred activity, but it is 20077 // possible for the user flow to never be able to return to that 20078 // situation so here we do a sanity check to make sure we haven't 20079 // left any junk around. 20080 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20081 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20082 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20083 removed.clear(); 20084 for (PreferredActivity pa : pir.filterSet()) { 20085 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20086 removed.add(pa); 20087 } 20088 } 20089 if (removed.size() > 0) { 20090 for (int r=0; r<removed.size(); r++) { 20091 PreferredActivity pa = removed.get(r); 20092 Slog.w(TAG, "Removing dangling preferred activity: " 20093 + pa.mPref.mComponent); 20094 pir.removeFilter(pa); 20095 } 20096 mSettings.writePackageRestrictionsLPr( 20097 mSettings.mPreferredActivities.keyAt(i)); 20098 } 20099 } 20100 20101 for (int userId : UserManagerService.getInstance().getUserIds()) { 20102 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20103 grantPermissionsUserIds = ArrayUtils.appendInt( 20104 grantPermissionsUserIds, userId); 20105 } 20106 } 20107 } 20108 sUserManager.systemReady(); 20109 20110 // If we upgraded grant all default permissions before kicking off. 20111 for (int userId : grantPermissionsUserIds) { 20112 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20113 } 20114 20115 // If we did not grant default permissions, we preload from this the 20116 // default permission exceptions lazily to ensure we don't hit the 20117 // disk on a new user creation. 20118 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20119 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20120 } 20121 20122 // Kick off any messages waiting for system ready 20123 if (mPostSystemReadyMessages != null) { 20124 for (Message msg : mPostSystemReadyMessages) { 20125 msg.sendToTarget(); 20126 } 20127 mPostSystemReadyMessages = null; 20128 } 20129 20130 // Watch for external volumes that come and go over time 20131 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20132 storage.registerListener(mStorageListener); 20133 20134 mInstallerService.systemReady(); 20135 mPackageDexOptimizer.systemReady(); 20136 20137 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20138 StorageManagerInternal.class); 20139 StorageManagerInternal.addExternalStoragePolicy( 20140 new StorageManagerInternal.ExternalStorageMountPolicy() { 20141 @Override 20142 public int getMountMode(int uid, String packageName) { 20143 if (Process.isIsolated(uid)) { 20144 return Zygote.MOUNT_EXTERNAL_NONE; 20145 } 20146 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20147 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20148 } 20149 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20150 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20151 } 20152 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20153 return Zygote.MOUNT_EXTERNAL_READ; 20154 } 20155 return Zygote.MOUNT_EXTERNAL_WRITE; 20156 } 20157 20158 @Override 20159 public boolean hasExternalStorage(int uid, String packageName) { 20160 return true; 20161 } 20162 }); 20163 20164 // Now that we're mostly running, clean up stale users and apps 20165 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20166 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20167 20168 if (mPrivappPermissionsViolations != null) { 20169 Slog.wtf(TAG,"Signature|privileged permissions not in " 20170 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20171 mPrivappPermissionsViolations = null; 20172 } 20173 } 20174 20175 public void waitForAppDataPrepared() { 20176 if (mPrepareAppDataFuture == null) { 20177 return; 20178 } 20179 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20180 mPrepareAppDataFuture = null; 20181 } 20182 20183 @Override 20184 public boolean isSafeMode() { 20185 return mSafeMode; 20186 } 20187 20188 @Override 20189 public boolean hasSystemUidErrors() { 20190 return mHasSystemUidErrors; 20191 } 20192 20193 static String arrayToString(int[] array) { 20194 StringBuffer buf = new StringBuffer(128); 20195 buf.append('['); 20196 if (array != null) { 20197 for (int i=0; i<array.length; i++) { 20198 if (i > 0) buf.append(", "); 20199 buf.append(array[i]); 20200 } 20201 } 20202 buf.append(']'); 20203 return buf.toString(); 20204 } 20205 20206 static class DumpState { 20207 public static final int DUMP_LIBS = 1 << 0; 20208 public static final int DUMP_FEATURES = 1 << 1; 20209 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20210 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20211 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20212 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20213 public static final int DUMP_PERMISSIONS = 1 << 6; 20214 public static final int DUMP_PACKAGES = 1 << 7; 20215 public static final int DUMP_SHARED_USERS = 1 << 8; 20216 public static final int DUMP_MESSAGES = 1 << 9; 20217 public static final int DUMP_PROVIDERS = 1 << 10; 20218 public static final int DUMP_VERIFIERS = 1 << 11; 20219 public static final int DUMP_PREFERRED = 1 << 12; 20220 public static final int DUMP_PREFERRED_XML = 1 << 13; 20221 public static final int DUMP_KEYSETS = 1 << 14; 20222 public static final int DUMP_VERSION = 1 << 15; 20223 public static final int DUMP_INSTALLS = 1 << 16; 20224 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20225 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20226 public static final int DUMP_FROZEN = 1 << 19; 20227 public static final int DUMP_DEXOPT = 1 << 20; 20228 public static final int DUMP_COMPILER_STATS = 1 << 21; 20229 20230 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20231 20232 private int mTypes; 20233 20234 private int mOptions; 20235 20236 private boolean mTitlePrinted; 20237 20238 private SharedUserSetting mSharedUser; 20239 20240 public boolean isDumping(int type) { 20241 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20242 return true; 20243 } 20244 20245 return (mTypes & type) != 0; 20246 } 20247 20248 public void setDump(int type) { 20249 mTypes |= type; 20250 } 20251 20252 public boolean isOptionEnabled(int option) { 20253 return (mOptions & option) != 0; 20254 } 20255 20256 public void setOptionEnabled(int option) { 20257 mOptions |= option; 20258 } 20259 20260 public boolean onTitlePrinted() { 20261 final boolean printed = mTitlePrinted; 20262 mTitlePrinted = true; 20263 return printed; 20264 } 20265 20266 public boolean getTitlePrinted() { 20267 return mTitlePrinted; 20268 } 20269 20270 public void setTitlePrinted(boolean enabled) { 20271 mTitlePrinted = enabled; 20272 } 20273 20274 public SharedUserSetting getSharedUser() { 20275 return mSharedUser; 20276 } 20277 20278 public void setSharedUser(SharedUserSetting user) { 20279 mSharedUser = user; 20280 } 20281 } 20282 20283 @Override 20284 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20285 FileDescriptor err, String[] args, ShellCallback callback, 20286 ResultReceiver resultReceiver) { 20287 (new PackageManagerShellCommand(this)).exec( 20288 this, in, out, err, args, callback, resultReceiver); 20289 } 20290 20291 @Override 20292 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20293 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20294 != PackageManager.PERMISSION_GRANTED) { 20295 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20296 + Binder.getCallingPid() 20297 + ", uid=" + Binder.getCallingUid() 20298 + " without permission " 20299 + android.Manifest.permission.DUMP); 20300 return; 20301 } 20302 20303 DumpState dumpState = new DumpState(); 20304 boolean fullPreferred = false; 20305 boolean checkin = false; 20306 20307 String packageName = null; 20308 ArraySet<String> permissionNames = null; 20309 20310 int opti = 0; 20311 while (opti < args.length) { 20312 String opt = args[opti]; 20313 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20314 break; 20315 } 20316 opti++; 20317 20318 if ("-a".equals(opt)) { 20319 // Right now we only know how to print all. 20320 } else if ("-h".equals(opt)) { 20321 pw.println("Package manager dump options:"); 20322 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20323 pw.println(" --checkin: dump for a checkin"); 20324 pw.println(" -f: print details of intent filters"); 20325 pw.println(" -h: print this help"); 20326 pw.println(" cmd may be one of:"); 20327 pw.println(" l[ibraries]: list known shared libraries"); 20328 pw.println(" f[eatures]: list device features"); 20329 pw.println(" k[eysets]: print known keysets"); 20330 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20331 pw.println(" perm[issions]: dump permissions"); 20332 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20333 pw.println(" pref[erred]: print preferred package settings"); 20334 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20335 pw.println(" prov[iders]: dump content providers"); 20336 pw.println(" p[ackages]: dump installed packages"); 20337 pw.println(" s[hared-users]: dump shared user IDs"); 20338 pw.println(" m[essages]: print collected runtime messages"); 20339 pw.println(" v[erifiers]: print package verifier info"); 20340 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20341 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20342 pw.println(" version: print database version info"); 20343 pw.println(" write: write current settings now"); 20344 pw.println(" installs: details about install sessions"); 20345 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20346 pw.println(" dexopt: dump dexopt state"); 20347 pw.println(" compiler-stats: dump compiler statistics"); 20348 pw.println(" <package.name>: info about given package"); 20349 return; 20350 } else if ("--checkin".equals(opt)) { 20351 checkin = true; 20352 } else if ("-f".equals(opt)) { 20353 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20354 } else { 20355 pw.println("Unknown argument: " + opt + "; use -h for help"); 20356 } 20357 } 20358 20359 // Is the caller requesting to dump a particular piece of data? 20360 if (opti < args.length) { 20361 String cmd = args[opti]; 20362 opti++; 20363 // Is this a package name? 20364 if ("android".equals(cmd) || cmd.contains(".")) { 20365 packageName = cmd; 20366 // When dumping a single package, we always dump all of its 20367 // filter information since the amount of data will be reasonable. 20368 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20369 } else if ("check-permission".equals(cmd)) { 20370 if (opti >= args.length) { 20371 pw.println("Error: check-permission missing permission argument"); 20372 return; 20373 } 20374 String perm = args[opti]; 20375 opti++; 20376 if (opti >= args.length) { 20377 pw.println("Error: check-permission missing package argument"); 20378 return; 20379 } 20380 20381 String pkg = args[opti]; 20382 opti++; 20383 int user = UserHandle.getUserId(Binder.getCallingUid()); 20384 if (opti < args.length) { 20385 try { 20386 user = Integer.parseInt(args[opti]); 20387 } catch (NumberFormatException e) { 20388 pw.println("Error: check-permission user argument is not a number: " 20389 + args[opti]); 20390 return; 20391 } 20392 } 20393 20394 // Normalize package name to handle renamed packages and static libs 20395 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20396 20397 pw.println(checkPermission(perm, pkg, user)); 20398 return; 20399 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20400 dumpState.setDump(DumpState.DUMP_LIBS); 20401 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20402 dumpState.setDump(DumpState.DUMP_FEATURES); 20403 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20404 if (opti >= args.length) { 20405 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20406 | DumpState.DUMP_SERVICE_RESOLVERS 20407 | DumpState.DUMP_RECEIVER_RESOLVERS 20408 | DumpState.DUMP_CONTENT_RESOLVERS); 20409 } else { 20410 while (opti < args.length) { 20411 String name = args[opti]; 20412 if ("a".equals(name) || "activity".equals(name)) { 20413 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20414 } else if ("s".equals(name) || "service".equals(name)) { 20415 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20416 } else if ("r".equals(name) || "receiver".equals(name)) { 20417 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20418 } else if ("c".equals(name) || "content".equals(name)) { 20419 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20420 } else { 20421 pw.println("Error: unknown resolver table type: " + name); 20422 return; 20423 } 20424 opti++; 20425 } 20426 } 20427 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20428 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20429 } else if ("permission".equals(cmd)) { 20430 if (opti >= args.length) { 20431 pw.println("Error: permission requires permission name"); 20432 return; 20433 } 20434 permissionNames = new ArraySet<>(); 20435 while (opti < args.length) { 20436 permissionNames.add(args[opti]); 20437 opti++; 20438 } 20439 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20440 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20441 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20442 dumpState.setDump(DumpState.DUMP_PREFERRED); 20443 } else if ("preferred-xml".equals(cmd)) { 20444 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20445 if (opti < args.length && "--full".equals(args[opti])) { 20446 fullPreferred = true; 20447 opti++; 20448 } 20449 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20450 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20451 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20452 dumpState.setDump(DumpState.DUMP_PACKAGES); 20453 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20454 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20455 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20456 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20457 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20458 dumpState.setDump(DumpState.DUMP_MESSAGES); 20459 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20460 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20461 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20462 || "intent-filter-verifiers".equals(cmd)) { 20463 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20464 } else if ("version".equals(cmd)) { 20465 dumpState.setDump(DumpState.DUMP_VERSION); 20466 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20467 dumpState.setDump(DumpState.DUMP_KEYSETS); 20468 } else if ("installs".equals(cmd)) { 20469 dumpState.setDump(DumpState.DUMP_INSTALLS); 20470 } else if ("frozen".equals(cmd)) { 20471 dumpState.setDump(DumpState.DUMP_FROZEN); 20472 } else if ("dexopt".equals(cmd)) { 20473 dumpState.setDump(DumpState.DUMP_DEXOPT); 20474 } else if ("compiler-stats".equals(cmd)) { 20475 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20476 } else if ("write".equals(cmd)) { 20477 synchronized (mPackages) { 20478 mSettings.writeLPr(); 20479 pw.println("Settings written."); 20480 return; 20481 } 20482 } 20483 } 20484 20485 if (checkin) { 20486 pw.println("vers,1"); 20487 } 20488 20489 // reader 20490 synchronized (mPackages) { 20491 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20492 if (!checkin) { 20493 if (dumpState.onTitlePrinted()) 20494 pw.println(); 20495 pw.println("Database versions:"); 20496 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20497 } 20498 } 20499 20500 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20501 if (!checkin) { 20502 if (dumpState.onTitlePrinted()) 20503 pw.println(); 20504 pw.println("Verifiers:"); 20505 pw.print(" Required: "); 20506 pw.print(mRequiredVerifierPackage); 20507 pw.print(" (uid="); 20508 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20509 UserHandle.USER_SYSTEM)); 20510 pw.println(")"); 20511 } else if (mRequiredVerifierPackage != null) { 20512 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20513 pw.print(","); 20514 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20515 UserHandle.USER_SYSTEM)); 20516 } 20517 } 20518 20519 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20520 packageName == null) { 20521 if (mIntentFilterVerifierComponent != null) { 20522 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20523 if (!checkin) { 20524 if (dumpState.onTitlePrinted()) 20525 pw.println(); 20526 pw.println("Intent Filter Verifier:"); 20527 pw.print(" Using: "); 20528 pw.print(verifierPackageName); 20529 pw.print(" (uid="); 20530 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20531 UserHandle.USER_SYSTEM)); 20532 pw.println(")"); 20533 } else if (verifierPackageName != null) { 20534 pw.print("ifv,"); pw.print(verifierPackageName); 20535 pw.print(","); 20536 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20537 UserHandle.USER_SYSTEM)); 20538 } 20539 } else { 20540 pw.println(); 20541 pw.println("No Intent Filter Verifier available!"); 20542 } 20543 } 20544 20545 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20546 boolean printedHeader = false; 20547 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20548 while (it.hasNext()) { 20549 String libName = it.next(); 20550 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20551 if (versionedLib == null) { 20552 continue; 20553 } 20554 final int versionCount = versionedLib.size(); 20555 for (int i = 0; i < versionCount; i++) { 20556 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20557 if (!checkin) { 20558 if (!printedHeader) { 20559 if (dumpState.onTitlePrinted()) 20560 pw.println(); 20561 pw.println("Libraries:"); 20562 printedHeader = true; 20563 } 20564 pw.print(" "); 20565 } else { 20566 pw.print("lib,"); 20567 } 20568 pw.print(libEntry.info.getName()); 20569 if (libEntry.info.isStatic()) { 20570 pw.print(" version=" + libEntry.info.getVersion()); 20571 } 20572 if (!checkin) { 20573 pw.print(" -> "); 20574 } 20575 if (libEntry.path != null) { 20576 pw.print(" (jar) "); 20577 pw.print(libEntry.path); 20578 } else { 20579 pw.print(" (apk) "); 20580 pw.print(libEntry.apk); 20581 } 20582 pw.println(); 20583 } 20584 } 20585 } 20586 20587 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20588 if (dumpState.onTitlePrinted()) 20589 pw.println(); 20590 if (!checkin) { 20591 pw.println("Features:"); 20592 } 20593 20594 synchronized (mAvailableFeatures) { 20595 for (FeatureInfo feat : mAvailableFeatures.values()) { 20596 if (checkin) { 20597 pw.print("feat,"); 20598 pw.print(feat.name); 20599 pw.print(","); 20600 pw.println(feat.version); 20601 } else { 20602 pw.print(" "); 20603 pw.print(feat.name); 20604 if (feat.version > 0) { 20605 pw.print(" version="); 20606 pw.print(feat.version); 20607 } 20608 pw.println(); 20609 } 20610 } 20611 } 20612 } 20613 20614 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20615 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20616 : "Activity Resolver Table:", " ", packageName, 20617 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20618 dumpState.setTitlePrinted(true); 20619 } 20620 } 20621 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20622 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20623 : "Receiver Resolver Table:", " ", packageName, 20624 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20625 dumpState.setTitlePrinted(true); 20626 } 20627 } 20628 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20629 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20630 : "Service Resolver Table:", " ", packageName, 20631 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20632 dumpState.setTitlePrinted(true); 20633 } 20634 } 20635 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20636 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20637 : "Provider Resolver Table:", " ", packageName, 20638 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20639 dumpState.setTitlePrinted(true); 20640 } 20641 } 20642 20643 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20644 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20645 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20646 int user = mSettings.mPreferredActivities.keyAt(i); 20647 if (pir.dump(pw, 20648 dumpState.getTitlePrinted() 20649 ? "\nPreferred Activities User " + user + ":" 20650 : "Preferred Activities User " + user + ":", " ", 20651 packageName, true, false)) { 20652 dumpState.setTitlePrinted(true); 20653 } 20654 } 20655 } 20656 20657 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20658 pw.flush(); 20659 FileOutputStream fout = new FileOutputStream(fd); 20660 BufferedOutputStream str = new BufferedOutputStream(fout); 20661 XmlSerializer serializer = new FastXmlSerializer(); 20662 try { 20663 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20664 serializer.startDocument(null, true); 20665 serializer.setFeature( 20666 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20667 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20668 serializer.endDocument(); 20669 serializer.flush(); 20670 } catch (IllegalArgumentException e) { 20671 pw.println("Failed writing: " + e); 20672 } catch (IllegalStateException e) { 20673 pw.println("Failed writing: " + e); 20674 } catch (IOException e) { 20675 pw.println("Failed writing: " + e); 20676 } 20677 } 20678 20679 if (!checkin 20680 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20681 && packageName == null) { 20682 pw.println(); 20683 int count = mSettings.mPackages.size(); 20684 if (count == 0) { 20685 pw.println("No applications!"); 20686 pw.println(); 20687 } else { 20688 final String prefix = " "; 20689 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20690 if (allPackageSettings.size() == 0) { 20691 pw.println("No domain preferred apps!"); 20692 pw.println(); 20693 } else { 20694 pw.println("App verification status:"); 20695 pw.println(); 20696 count = 0; 20697 for (PackageSetting ps : allPackageSettings) { 20698 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20699 if (ivi == null || ivi.getPackageName() == null) continue; 20700 pw.println(prefix + "Package: " + ivi.getPackageName()); 20701 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20702 pw.println(prefix + "Status: " + ivi.getStatusString()); 20703 pw.println(); 20704 count++; 20705 } 20706 if (count == 0) { 20707 pw.println(prefix + "No app verification established."); 20708 pw.println(); 20709 } 20710 for (int userId : sUserManager.getUserIds()) { 20711 pw.println("App linkages for user " + userId + ":"); 20712 pw.println(); 20713 count = 0; 20714 for (PackageSetting ps : allPackageSettings) { 20715 final long status = ps.getDomainVerificationStatusForUser(userId); 20716 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20717 && !DEBUG_DOMAIN_VERIFICATION) { 20718 continue; 20719 } 20720 pw.println(prefix + "Package: " + ps.name); 20721 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20722 String statusStr = IntentFilterVerificationInfo. 20723 getStatusStringFromValue(status); 20724 pw.println(prefix + "Status: " + statusStr); 20725 pw.println(); 20726 count++; 20727 } 20728 if (count == 0) { 20729 pw.println(prefix + "No configured app linkages."); 20730 pw.println(); 20731 } 20732 } 20733 } 20734 } 20735 } 20736 20737 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20738 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20739 if (packageName == null && permissionNames == null) { 20740 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20741 if (iperm == 0) { 20742 if (dumpState.onTitlePrinted()) 20743 pw.println(); 20744 pw.println("AppOp Permissions:"); 20745 } 20746 pw.print(" AppOp Permission "); 20747 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20748 pw.println(":"); 20749 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20750 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20751 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20752 } 20753 } 20754 } 20755 } 20756 20757 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20758 boolean printedSomething = false; 20759 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20760 if (packageName != null && !packageName.equals(p.info.packageName)) { 20761 continue; 20762 } 20763 if (!printedSomething) { 20764 if (dumpState.onTitlePrinted()) 20765 pw.println(); 20766 pw.println("Registered ContentProviders:"); 20767 printedSomething = true; 20768 } 20769 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20770 pw.print(" "); pw.println(p.toString()); 20771 } 20772 printedSomething = false; 20773 for (Map.Entry<String, PackageParser.Provider> entry : 20774 mProvidersByAuthority.entrySet()) { 20775 PackageParser.Provider p = entry.getValue(); 20776 if (packageName != null && !packageName.equals(p.info.packageName)) { 20777 continue; 20778 } 20779 if (!printedSomething) { 20780 if (dumpState.onTitlePrinted()) 20781 pw.println(); 20782 pw.println("ContentProvider Authorities:"); 20783 printedSomething = true; 20784 } 20785 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20786 pw.print(" "); pw.println(p.toString()); 20787 if (p.info != null && p.info.applicationInfo != null) { 20788 final String appInfo = p.info.applicationInfo.toString(); 20789 pw.print(" applicationInfo="); pw.println(appInfo); 20790 } 20791 } 20792 } 20793 20794 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20795 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20796 } 20797 20798 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20799 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20800 } 20801 20802 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20803 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20804 } 20805 20806 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20807 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20808 } 20809 20810 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20811 // XXX should handle packageName != null by dumping only install data that 20812 // the given package is involved with. 20813 if (dumpState.onTitlePrinted()) pw.println(); 20814 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20815 } 20816 20817 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20818 // XXX should handle packageName != null by dumping only install data that 20819 // the given package is involved with. 20820 if (dumpState.onTitlePrinted()) pw.println(); 20821 20822 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20823 ipw.println(); 20824 ipw.println("Frozen packages:"); 20825 ipw.increaseIndent(); 20826 if (mFrozenPackages.size() == 0) { 20827 ipw.println("(none)"); 20828 } else { 20829 for (int i = 0; i < mFrozenPackages.size(); i++) { 20830 ipw.println(mFrozenPackages.valueAt(i)); 20831 } 20832 } 20833 ipw.decreaseIndent(); 20834 } 20835 20836 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20837 if (dumpState.onTitlePrinted()) pw.println(); 20838 dumpDexoptStateLPr(pw, packageName); 20839 } 20840 20841 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20842 if (dumpState.onTitlePrinted()) pw.println(); 20843 dumpCompilerStatsLPr(pw, packageName); 20844 } 20845 20846 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20847 if (dumpState.onTitlePrinted()) pw.println(); 20848 mSettings.dumpReadMessagesLPr(pw, dumpState); 20849 20850 pw.println(); 20851 pw.println("Package warning messages:"); 20852 BufferedReader in = null; 20853 String line = null; 20854 try { 20855 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20856 while ((line = in.readLine()) != null) { 20857 if (line.contains("ignored: updated version")) continue; 20858 pw.println(line); 20859 } 20860 } catch (IOException ignored) { 20861 } finally { 20862 IoUtils.closeQuietly(in); 20863 } 20864 } 20865 20866 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20867 BufferedReader in = null; 20868 String line = null; 20869 try { 20870 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20871 while ((line = in.readLine()) != null) { 20872 if (line.contains("ignored: updated version")) continue; 20873 pw.print("msg,"); 20874 pw.println(line); 20875 } 20876 } catch (IOException ignored) { 20877 } finally { 20878 IoUtils.closeQuietly(in); 20879 } 20880 } 20881 } 20882 } 20883 20884 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20885 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20886 ipw.println(); 20887 ipw.println("Dexopt state:"); 20888 ipw.increaseIndent(); 20889 Collection<PackageParser.Package> packages = null; 20890 if (packageName != null) { 20891 PackageParser.Package targetPackage = mPackages.get(packageName); 20892 if (targetPackage != null) { 20893 packages = Collections.singletonList(targetPackage); 20894 } else { 20895 ipw.println("Unable to find package: " + packageName); 20896 return; 20897 } 20898 } else { 20899 packages = mPackages.values(); 20900 } 20901 20902 for (PackageParser.Package pkg : packages) { 20903 ipw.println("[" + pkg.packageName + "]"); 20904 ipw.increaseIndent(); 20905 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20906 ipw.decreaseIndent(); 20907 } 20908 } 20909 20910 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20911 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20912 ipw.println(); 20913 ipw.println("Compiler stats:"); 20914 ipw.increaseIndent(); 20915 Collection<PackageParser.Package> packages = null; 20916 if (packageName != null) { 20917 PackageParser.Package targetPackage = mPackages.get(packageName); 20918 if (targetPackage != null) { 20919 packages = Collections.singletonList(targetPackage); 20920 } else { 20921 ipw.println("Unable to find package: " + packageName); 20922 return; 20923 } 20924 } else { 20925 packages = mPackages.values(); 20926 } 20927 20928 for (PackageParser.Package pkg : packages) { 20929 ipw.println("[" + pkg.packageName + "]"); 20930 ipw.increaseIndent(); 20931 20932 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20933 if (stats == null) { 20934 ipw.println("(No recorded stats)"); 20935 } else { 20936 stats.dump(ipw); 20937 } 20938 ipw.decreaseIndent(); 20939 } 20940 } 20941 20942 private String dumpDomainString(String packageName) { 20943 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20944 .getList(); 20945 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20946 20947 ArraySet<String> result = new ArraySet<>(); 20948 if (iviList.size() > 0) { 20949 for (IntentFilterVerificationInfo ivi : iviList) { 20950 for (String host : ivi.getDomains()) { 20951 result.add(host); 20952 } 20953 } 20954 } 20955 if (filters != null && filters.size() > 0) { 20956 for (IntentFilter filter : filters) { 20957 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20958 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20959 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20960 result.addAll(filter.getHostsList()); 20961 } 20962 } 20963 } 20964 20965 StringBuilder sb = new StringBuilder(result.size() * 16); 20966 for (String domain : result) { 20967 if (sb.length() > 0) sb.append(" "); 20968 sb.append(domain); 20969 } 20970 return sb.toString(); 20971 } 20972 20973 // ------- apps on sdcard specific code ------- 20974 static final boolean DEBUG_SD_INSTALL = false; 20975 20976 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20977 20978 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20979 20980 private boolean mMediaMounted = false; 20981 20982 static String getEncryptKey() { 20983 try { 20984 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20985 SD_ENCRYPTION_KEYSTORE_NAME); 20986 if (sdEncKey == null) { 20987 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20988 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20989 if (sdEncKey == null) { 20990 Slog.e(TAG, "Failed to create encryption keys"); 20991 return null; 20992 } 20993 } 20994 return sdEncKey; 20995 } catch (NoSuchAlgorithmException nsae) { 20996 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20997 return null; 20998 } catch (IOException ioe) { 20999 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21000 return null; 21001 } 21002 } 21003 21004 /* 21005 * Update media status on PackageManager. 21006 */ 21007 @Override 21008 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21009 int callingUid = Binder.getCallingUid(); 21010 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21011 throw new SecurityException("Media status can only be updated by the system"); 21012 } 21013 // reader; this apparently protects mMediaMounted, but should probably 21014 // be a different lock in that case. 21015 synchronized (mPackages) { 21016 Log.i(TAG, "Updating external media status from " 21017 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21018 + (mediaStatus ? "mounted" : "unmounted")); 21019 if (DEBUG_SD_INSTALL) 21020 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21021 + ", mMediaMounted=" + mMediaMounted); 21022 if (mediaStatus == mMediaMounted) { 21023 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21024 : 0, -1); 21025 mHandler.sendMessage(msg); 21026 return; 21027 } 21028 mMediaMounted = mediaStatus; 21029 } 21030 // Queue up an async operation since the package installation may take a 21031 // little while. 21032 mHandler.post(new Runnable() { 21033 public void run() { 21034 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21035 } 21036 }); 21037 } 21038 21039 /** 21040 * Called by StorageManagerService when the initial ASECs to scan are available. 21041 * Should block until all the ASEC containers are finished being scanned. 21042 */ 21043 public void scanAvailableAsecs() { 21044 updateExternalMediaStatusInner(true, false, false); 21045 } 21046 21047 /* 21048 * Collect information of applications on external media, map them against 21049 * existing containers and update information based on current mount status. 21050 * Please note that we always have to report status if reportStatus has been 21051 * set to true especially when unloading packages. 21052 */ 21053 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21054 boolean externalStorage) { 21055 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21056 int[] uidArr = EmptyArray.INT; 21057 21058 final String[] list = PackageHelper.getSecureContainerList(); 21059 if (ArrayUtils.isEmpty(list)) { 21060 Log.i(TAG, "No secure containers found"); 21061 } else { 21062 // Process list of secure containers and categorize them 21063 // as active or stale based on their package internal state. 21064 21065 // reader 21066 synchronized (mPackages) { 21067 for (String cid : list) { 21068 // Leave stages untouched for now; installer service owns them 21069 if (PackageInstallerService.isStageName(cid)) continue; 21070 21071 if (DEBUG_SD_INSTALL) 21072 Log.i(TAG, "Processing container " + cid); 21073 String pkgName = getAsecPackageName(cid); 21074 if (pkgName == null) { 21075 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21076 continue; 21077 } 21078 if (DEBUG_SD_INSTALL) 21079 Log.i(TAG, "Looking for pkg : " + pkgName); 21080 21081 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21082 if (ps == null) { 21083 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21084 continue; 21085 } 21086 21087 /* 21088 * Skip packages that are not external if we're unmounting 21089 * external storage. 21090 */ 21091 if (externalStorage && !isMounted && !isExternal(ps)) { 21092 continue; 21093 } 21094 21095 final AsecInstallArgs args = new AsecInstallArgs(cid, 21096 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21097 // The package status is changed only if the code path 21098 // matches between settings and the container id. 21099 if (ps.codePathString != null 21100 && ps.codePathString.startsWith(args.getCodePath())) { 21101 if (DEBUG_SD_INSTALL) { 21102 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21103 + " at code path: " + ps.codePathString); 21104 } 21105 21106 // We do have a valid package installed on sdcard 21107 processCids.put(args, ps.codePathString); 21108 final int uid = ps.appId; 21109 if (uid != -1) { 21110 uidArr = ArrayUtils.appendInt(uidArr, uid); 21111 } 21112 } else { 21113 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21114 + ps.codePathString); 21115 } 21116 } 21117 } 21118 21119 Arrays.sort(uidArr); 21120 } 21121 21122 // Process packages with valid entries. 21123 if (isMounted) { 21124 if (DEBUG_SD_INSTALL) 21125 Log.i(TAG, "Loading packages"); 21126 loadMediaPackages(processCids, uidArr, externalStorage); 21127 startCleaningPackages(); 21128 mInstallerService.onSecureContainersAvailable(); 21129 } else { 21130 if (DEBUG_SD_INSTALL) 21131 Log.i(TAG, "Unloading packages"); 21132 unloadMediaPackages(processCids, uidArr, reportStatus); 21133 } 21134 } 21135 21136 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21137 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21138 final int size = infos.size(); 21139 final String[] packageNames = new String[size]; 21140 final int[] packageUids = new int[size]; 21141 for (int i = 0; i < size; i++) { 21142 final ApplicationInfo info = infos.get(i); 21143 packageNames[i] = info.packageName; 21144 packageUids[i] = info.uid; 21145 } 21146 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21147 finishedReceiver); 21148 } 21149 21150 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21151 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21152 sendResourcesChangedBroadcast(mediaStatus, replacing, 21153 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21154 } 21155 21156 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21157 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21158 int size = pkgList.length; 21159 if (size > 0) { 21160 // Send broadcasts here 21161 Bundle extras = new Bundle(); 21162 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21163 if (uidArr != null) { 21164 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21165 } 21166 if (replacing) { 21167 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21168 } 21169 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21170 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21171 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21172 } 21173 } 21174 21175 /* 21176 * Look at potentially valid container ids from processCids If package 21177 * information doesn't match the one on record or package scanning fails, 21178 * the cid is added to list of removeCids. We currently don't delete stale 21179 * containers. 21180 */ 21181 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21182 boolean externalStorage) { 21183 ArrayList<String> pkgList = new ArrayList<String>(); 21184 Set<AsecInstallArgs> keys = processCids.keySet(); 21185 21186 for (AsecInstallArgs args : keys) { 21187 String codePath = processCids.get(args); 21188 if (DEBUG_SD_INSTALL) 21189 Log.i(TAG, "Loading container : " + args.cid); 21190 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21191 try { 21192 // Make sure there are no container errors first. 21193 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21194 Slog.e(TAG, "Failed to mount cid : " + args.cid 21195 + " when installing from sdcard"); 21196 continue; 21197 } 21198 // Check code path here. 21199 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21200 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21201 + " does not match one in settings " + codePath); 21202 continue; 21203 } 21204 // Parse package 21205 int parseFlags = mDefParseFlags; 21206 if (args.isExternalAsec()) { 21207 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21208 } 21209 if (args.isFwdLocked()) { 21210 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21211 } 21212 21213 synchronized (mInstallLock) { 21214 PackageParser.Package pkg = null; 21215 try { 21216 // Sadly we don't know the package name yet to freeze it 21217 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21218 SCAN_IGNORE_FROZEN, 0, null); 21219 } catch (PackageManagerException e) { 21220 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21221 } 21222 // Scan the package 21223 if (pkg != null) { 21224 /* 21225 * TODO why is the lock being held? doPostInstall is 21226 * called in other places without the lock. This needs 21227 * to be straightened out. 21228 */ 21229 // writer 21230 synchronized (mPackages) { 21231 retCode = PackageManager.INSTALL_SUCCEEDED; 21232 pkgList.add(pkg.packageName); 21233 // Post process args 21234 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21235 pkg.applicationInfo.uid); 21236 } 21237 } else { 21238 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21239 } 21240 } 21241 21242 } finally { 21243 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21244 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21245 } 21246 } 21247 } 21248 // writer 21249 synchronized (mPackages) { 21250 // If the platform SDK has changed since the last time we booted, 21251 // we need to re-grant app permission to catch any new ones that 21252 // appear. This is really a hack, and means that apps can in some 21253 // cases get permissions that the user didn't initially explicitly 21254 // allow... it would be nice to have some better way to handle 21255 // this situation. 21256 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21257 : mSettings.getInternalVersion(); 21258 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21259 : StorageManager.UUID_PRIVATE_INTERNAL; 21260 21261 int updateFlags = UPDATE_PERMISSIONS_ALL; 21262 if (ver.sdkVersion != mSdkVersion) { 21263 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21264 + mSdkVersion + "; regranting permissions for external"); 21265 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21266 } 21267 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21268 21269 // Yay, everything is now upgraded 21270 ver.forceCurrent(); 21271 21272 // can downgrade to reader 21273 // Persist settings 21274 mSettings.writeLPr(); 21275 } 21276 // Send a broadcast to let everyone know we are done processing 21277 if (pkgList.size() > 0) { 21278 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21279 } 21280 } 21281 21282 /* 21283 * Utility method to unload a list of specified containers 21284 */ 21285 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21286 // Just unmount all valid containers. 21287 for (AsecInstallArgs arg : cidArgs) { 21288 synchronized (mInstallLock) { 21289 arg.doPostDeleteLI(false); 21290 } 21291 } 21292 } 21293 21294 /* 21295 * Unload packages mounted on external media. This involves deleting package 21296 * data from internal structures, sending broadcasts about disabled packages, 21297 * gc'ing to free up references, unmounting all secure containers 21298 * corresponding to packages on external media, and posting a 21299 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21300 * that we always have to post this message if status has been requested no 21301 * matter what. 21302 */ 21303 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21304 final boolean reportStatus) { 21305 if (DEBUG_SD_INSTALL) 21306 Log.i(TAG, "unloading media packages"); 21307 ArrayList<String> pkgList = new ArrayList<String>(); 21308 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21309 final Set<AsecInstallArgs> keys = processCids.keySet(); 21310 for (AsecInstallArgs args : keys) { 21311 String pkgName = args.getPackageName(); 21312 if (DEBUG_SD_INSTALL) 21313 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21314 // Delete package internally 21315 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21316 synchronized (mInstallLock) { 21317 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21318 final boolean res; 21319 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21320 "unloadMediaPackages")) { 21321 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21322 null); 21323 } 21324 if (res) { 21325 pkgList.add(pkgName); 21326 } else { 21327 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21328 failedList.add(args); 21329 } 21330 } 21331 } 21332 21333 // reader 21334 synchronized (mPackages) { 21335 // We didn't update the settings after removing each package; 21336 // write them now for all packages. 21337 mSettings.writeLPr(); 21338 } 21339 21340 // We have to absolutely send UPDATED_MEDIA_STATUS only 21341 // after confirming that all the receivers processed the ordered 21342 // broadcast when packages get disabled, force a gc to clean things up. 21343 // and unload all the containers. 21344 if (pkgList.size() > 0) { 21345 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21346 new IIntentReceiver.Stub() { 21347 public void performReceive(Intent intent, int resultCode, String data, 21348 Bundle extras, boolean ordered, boolean sticky, 21349 int sendingUser) throws RemoteException { 21350 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21351 reportStatus ? 1 : 0, 1, keys); 21352 mHandler.sendMessage(msg); 21353 } 21354 }); 21355 } else { 21356 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21357 keys); 21358 mHandler.sendMessage(msg); 21359 } 21360 } 21361 21362 private void loadPrivatePackages(final VolumeInfo vol) { 21363 mHandler.post(new Runnable() { 21364 @Override 21365 public void run() { 21366 loadPrivatePackagesInner(vol); 21367 } 21368 }); 21369 } 21370 21371 private void loadPrivatePackagesInner(VolumeInfo vol) { 21372 final String volumeUuid = vol.fsUuid; 21373 if (TextUtils.isEmpty(volumeUuid)) { 21374 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21375 return; 21376 } 21377 21378 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21379 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21380 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21381 21382 final VersionInfo ver; 21383 final List<PackageSetting> packages; 21384 synchronized (mPackages) { 21385 ver = mSettings.findOrCreateVersion(volumeUuid); 21386 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21387 } 21388 21389 for (PackageSetting ps : packages) { 21390 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21391 synchronized (mInstallLock) { 21392 final PackageParser.Package pkg; 21393 try { 21394 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21395 loaded.add(pkg.applicationInfo); 21396 21397 } catch (PackageManagerException e) { 21398 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21399 } 21400 21401 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21402 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21403 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21404 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21405 } 21406 } 21407 } 21408 21409 // Reconcile app data for all started/unlocked users 21410 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21411 final UserManager um = mContext.getSystemService(UserManager.class); 21412 UserManagerInternal umInternal = getUserManagerInternal(); 21413 for (UserInfo user : um.getUsers()) { 21414 final int flags; 21415 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21416 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21417 } else if (umInternal.isUserRunning(user.id)) { 21418 flags = StorageManager.FLAG_STORAGE_DE; 21419 } else { 21420 continue; 21421 } 21422 21423 try { 21424 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21425 synchronized (mInstallLock) { 21426 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21427 } 21428 } catch (IllegalStateException e) { 21429 // Device was probably ejected, and we'll process that event momentarily 21430 Slog.w(TAG, "Failed to prepare storage: " + e); 21431 } 21432 } 21433 21434 synchronized (mPackages) { 21435 int updateFlags = UPDATE_PERMISSIONS_ALL; 21436 if (ver.sdkVersion != mSdkVersion) { 21437 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21438 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21439 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21440 } 21441 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21442 21443 // Yay, everything is now upgraded 21444 ver.forceCurrent(); 21445 21446 mSettings.writeLPr(); 21447 } 21448 21449 for (PackageFreezer freezer : freezers) { 21450 freezer.close(); 21451 } 21452 21453 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21454 sendResourcesChangedBroadcast(true, false, loaded, null); 21455 } 21456 21457 private void unloadPrivatePackages(final VolumeInfo vol) { 21458 mHandler.post(new Runnable() { 21459 @Override 21460 public void run() { 21461 unloadPrivatePackagesInner(vol); 21462 } 21463 }); 21464 } 21465 21466 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21467 final String volumeUuid = vol.fsUuid; 21468 if (TextUtils.isEmpty(volumeUuid)) { 21469 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21470 return; 21471 } 21472 21473 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21474 synchronized (mInstallLock) { 21475 synchronized (mPackages) { 21476 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21477 for (PackageSetting ps : packages) { 21478 if (ps.pkg == null) continue; 21479 21480 final ApplicationInfo info = ps.pkg.applicationInfo; 21481 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21482 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21483 21484 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21485 "unloadPrivatePackagesInner")) { 21486 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21487 false, null)) { 21488 unloaded.add(info); 21489 } else { 21490 Slog.w(TAG, "Failed to unload " + ps.codePath); 21491 } 21492 } 21493 21494 // Try very hard to release any references to this package 21495 // so we don't risk the system server being killed due to 21496 // open FDs 21497 AttributeCache.instance().removePackage(ps.name); 21498 } 21499 21500 mSettings.writeLPr(); 21501 } 21502 } 21503 21504 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21505 sendResourcesChangedBroadcast(false, false, unloaded, null); 21506 21507 // Try very hard to release any references to this path so we don't risk 21508 // the system server being killed due to open FDs 21509 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21510 21511 for (int i = 0; i < 3; i++) { 21512 System.gc(); 21513 System.runFinalization(); 21514 } 21515 } 21516 21517 private void assertPackageKnown(String volumeUuid, String packageName) 21518 throws PackageManagerException { 21519 synchronized (mPackages) { 21520 // Normalize package name to handle renamed packages 21521 packageName = normalizePackageNameLPr(packageName); 21522 21523 final PackageSetting ps = mSettings.mPackages.get(packageName); 21524 if (ps == null) { 21525 throw new PackageManagerException("Package " + packageName + " is unknown"); 21526 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21527 throw new PackageManagerException( 21528 "Package " + packageName + " found on unknown volume " + volumeUuid 21529 + "; expected volume " + ps.volumeUuid); 21530 } 21531 } 21532 } 21533 21534 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21535 throws PackageManagerException { 21536 synchronized (mPackages) { 21537 // Normalize package name to handle renamed packages 21538 packageName = normalizePackageNameLPr(packageName); 21539 21540 final PackageSetting ps = mSettings.mPackages.get(packageName); 21541 if (ps == null) { 21542 throw new PackageManagerException("Package " + packageName + " is unknown"); 21543 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21544 throw new PackageManagerException( 21545 "Package " + packageName + " found on unknown volume " + volumeUuid 21546 + "; expected volume " + ps.volumeUuid); 21547 } else if (!ps.getInstalled(userId)) { 21548 throw new PackageManagerException( 21549 "Package " + packageName + " not installed for user " + userId); 21550 } 21551 } 21552 } 21553 21554 private List<String> collectAbsoluteCodePaths() { 21555 synchronized (mPackages) { 21556 List<String> codePaths = new ArrayList<>(); 21557 final int packageCount = mSettings.mPackages.size(); 21558 for (int i = 0; i < packageCount; i++) { 21559 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21560 codePaths.add(ps.codePath.getAbsolutePath()); 21561 } 21562 return codePaths; 21563 } 21564 } 21565 21566 /** 21567 * Examine all apps present on given mounted volume, and destroy apps that 21568 * aren't expected, either due to uninstallation or reinstallation on 21569 * another volume. 21570 */ 21571 private void reconcileApps(String volumeUuid) { 21572 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21573 List<File> filesToDelete = null; 21574 21575 final File[] files = FileUtils.listFilesOrEmpty( 21576 Environment.getDataAppDirectory(volumeUuid)); 21577 for (File file : files) { 21578 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21579 && !PackageInstallerService.isStageName(file.getName()); 21580 if (!isPackage) { 21581 // Ignore entries which are not packages 21582 continue; 21583 } 21584 21585 String absolutePath = file.getAbsolutePath(); 21586 21587 boolean pathValid = false; 21588 final int absoluteCodePathCount = absoluteCodePaths.size(); 21589 for (int i = 0; i < absoluteCodePathCount; i++) { 21590 String absoluteCodePath = absoluteCodePaths.get(i); 21591 if (absolutePath.startsWith(absoluteCodePath)) { 21592 pathValid = true; 21593 break; 21594 } 21595 } 21596 21597 if (!pathValid) { 21598 if (filesToDelete == null) { 21599 filesToDelete = new ArrayList<>(); 21600 } 21601 filesToDelete.add(file); 21602 } 21603 } 21604 21605 if (filesToDelete != null) { 21606 final int fileToDeleteCount = filesToDelete.size(); 21607 for (int i = 0; i < fileToDeleteCount; i++) { 21608 File fileToDelete = filesToDelete.get(i); 21609 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21610 synchronized (mInstallLock) { 21611 removeCodePathLI(fileToDelete); 21612 } 21613 } 21614 } 21615 } 21616 21617 /** 21618 * Reconcile all app data for the given user. 21619 * <p> 21620 * Verifies that directories exist and that ownership and labeling is 21621 * correct for all installed apps on all mounted volumes. 21622 */ 21623 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21624 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21625 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21626 final String volumeUuid = vol.getFsUuid(); 21627 synchronized (mInstallLock) { 21628 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21629 } 21630 } 21631 } 21632 21633 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21634 boolean migrateAppData) { 21635 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21636 } 21637 21638 /** 21639 * Reconcile all app data on given mounted volume. 21640 * <p> 21641 * Destroys app data that isn't expected, either due to uninstallation or 21642 * reinstallation on another volume. 21643 * <p> 21644 * Verifies that directories exist and that ownership and labeling is 21645 * correct for all installed apps. 21646 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21647 */ 21648 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21649 boolean migrateAppData, boolean onlyCoreApps) { 21650 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21651 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21652 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21653 21654 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21655 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21656 21657 // First look for stale data that doesn't belong, and check if things 21658 // have changed since we did our last restorecon 21659 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21660 if (StorageManager.isFileEncryptedNativeOrEmulated() 21661 && !StorageManager.isUserKeyUnlocked(userId)) { 21662 throw new RuntimeException( 21663 "Yikes, someone asked us to reconcile CE storage while " + userId 21664 + " was still locked; this would have caused massive data loss!"); 21665 } 21666 21667 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21668 for (File file : files) { 21669 final String packageName = file.getName(); 21670 try { 21671 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21672 } catch (PackageManagerException e) { 21673 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21674 try { 21675 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21676 StorageManager.FLAG_STORAGE_CE, 0); 21677 } catch (InstallerException e2) { 21678 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21679 } 21680 } 21681 } 21682 } 21683 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21684 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21685 for (File file : files) { 21686 final String packageName = file.getName(); 21687 try { 21688 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21689 } catch (PackageManagerException e) { 21690 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21691 try { 21692 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21693 StorageManager.FLAG_STORAGE_DE, 0); 21694 } catch (InstallerException e2) { 21695 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21696 } 21697 } 21698 } 21699 } 21700 21701 // Ensure that data directories are ready to roll for all packages 21702 // installed for this volume and user 21703 final List<PackageSetting> packages; 21704 synchronized (mPackages) { 21705 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21706 } 21707 int preparedCount = 0; 21708 for (PackageSetting ps : packages) { 21709 final String packageName = ps.name; 21710 if (ps.pkg == null) { 21711 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21712 // TODO: might be due to legacy ASEC apps; we should circle back 21713 // and reconcile again once they're scanned 21714 continue; 21715 } 21716 // Skip non-core apps if requested 21717 if (onlyCoreApps && !ps.pkg.coreApp) { 21718 result.add(packageName); 21719 continue; 21720 } 21721 21722 if (ps.getInstalled(userId)) { 21723 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21724 preparedCount++; 21725 } 21726 } 21727 21728 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21729 return result; 21730 } 21731 21732 /** 21733 * Prepare app data for the given app just after it was installed or 21734 * upgraded. This method carefully only touches users that it's installed 21735 * for, and it forces a restorecon to handle any seinfo changes. 21736 * <p> 21737 * Verifies that directories exist and that ownership and labeling is 21738 * correct for all installed apps. If there is an ownership mismatch, it 21739 * will try recovering system apps by wiping data; third-party app data is 21740 * left intact. 21741 * <p> 21742 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21743 */ 21744 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21745 final PackageSetting ps; 21746 synchronized (mPackages) { 21747 ps = mSettings.mPackages.get(pkg.packageName); 21748 mSettings.writeKernelMappingLPr(ps); 21749 } 21750 21751 final UserManager um = mContext.getSystemService(UserManager.class); 21752 UserManagerInternal umInternal = getUserManagerInternal(); 21753 for (UserInfo user : um.getUsers()) { 21754 final int flags; 21755 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21756 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21757 } else if (umInternal.isUserRunning(user.id)) { 21758 flags = StorageManager.FLAG_STORAGE_DE; 21759 } else { 21760 continue; 21761 } 21762 21763 if (ps.getInstalled(user.id)) { 21764 // TODO: when user data is locked, mark that we're still dirty 21765 prepareAppDataLIF(pkg, user.id, flags); 21766 } 21767 } 21768 } 21769 21770 /** 21771 * Prepare app data for the given app. 21772 * <p> 21773 * Verifies that directories exist and that ownership and labeling is 21774 * correct for all installed apps. If there is an ownership mismatch, this 21775 * will try recovering system apps by wiping data; third-party app data is 21776 * left intact. 21777 */ 21778 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21779 if (pkg == null) { 21780 Slog.wtf(TAG, "Package was null!", new Throwable()); 21781 return; 21782 } 21783 prepareAppDataLeafLIF(pkg, userId, flags); 21784 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21785 for (int i = 0; i < childCount; i++) { 21786 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21787 } 21788 } 21789 21790 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21791 boolean maybeMigrateAppData) { 21792 prepareAppDataLIF(pkg, userId, flags); 21793 21794 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21795 // We may have just shuffled around app data directories, so 21796 // prepare them one more time 21797 prepareAppDataLIF(pkg, userId, flags); 21798 } 21799 } 21800 21801 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21802 if (DEBUG_APP_DATA) { 21803 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21804 + Integer.toHexString(flags)); 21805 } 21806 21807 final String volumeUuid = pkg.volumeUuid; 21808 final String packageName = pkg.packageName; 21809 final ApplicationInfo app = pkg.applicationInfo; 21810 final int appId = UserHandle.getAppId(app.uid); 21811 21812 Preconditions.checkNotNull(app.seInfo); 21813 21814 long ceDataInode = -1; 21815 try { 21816 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21817 appId, app.seInfo, app.targetSdkVersion); 21818 } catch (InstallerException e) { 21819 if (app.isSystemApp()) { 21820 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21821 + ", but trying to recover: " + e); 21822 destroyAppDataLeafLIF(pkg, userId, flags); 21823 try { 21824 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21825 appId, app.seInfo, app.targetSdkVersion); 21826 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21827 } catch (InstallerException e2) { 21828 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21829 } 21830 } else { 21831 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21832 } 21833 } 21834 21835 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21836 // TODO: mark this structure as dirty so we persist it! 21837 synchronized (mPackages) { 21838 final PackageSetting ps = mSettings.mPackages.get(packageName); 21839 if (ps != null) { 21840 ps.setCeDataInode(ceDataInode, userId); 21841 } 21842 } 21843 } 21844 21845 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21846 } 21847 21848 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21849 if (pkg == null) { 21850 Slog.wtf(TAG, "Package was null!", new Throwable()); 21851 return; 21852 } 21853 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21854 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21855 for (int i = 0; i < childCount; i++) { 21856 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21857 } 21858 } 21859 21860 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21861 final String volumeUuid = pkg.volumeUuid; 21862 final String packageName = pkg.packageName; 21863 final ApplicationInfo app = pkg.applicationInfo; 21864 21865 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21866 // Create a native library symlink only if we have native libraries 21867 // and if the native libraries are 32 bit libraries. We do not provide 21868 // this symlink for 64 bit libraries. 21869 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21870 final String nativeLibPath = app.nativeLibraryDir; 21871 try { 21872 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21873 nativeLibPath, userId); 21874 } catch (InstallerException e) { 21875 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21876 } 21877 } 21878 } 21879 } 21880 21881 /** 21882 * For system apps on non-FBE devices, this method migrates any existing 21883 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21884 * requested by the app. 21885 */ 21886 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21887 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21888 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21889 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21890 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21891 try { 21892 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21893 storageTarget); 21894 } catch (InstallerException e) { 21895 logCriticalInfo(Log.WARN, 21896 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21897 } 21898 return true; 21899 } else { 21900 return false; 21901 } 21902 } 21903 21904 public PackageFreezer freezePackage(String packageName, String killReason) { 21905 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21906 } 21907 21908 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21909 return new PackageFreezer(packageName, userId, killReason); 21910 } 21911 21912 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21913 String killReason) { 21914 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21915 } 21916 21917 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21918 String killReason) { 21919 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21920 return new PackageFreezer(); 21921 } else { 21922 return freezePackage(packageName, userId, killReason); 21923 } 21924 } 21925 21926 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21927 String killReason) { 21928 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21929 } 21930 21931 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21932 String killReason) { 21933 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21934 return new PackageFreezer(); 21935 } else { 21936 return freezePackage(packageName, userId, killReason); 21937 } 21938 } 21939 21940 /** 21941 * Class that freezes and kills the given package upon creation, and 21942 * unfreezes it upon closing. This is typically used when doing surgery on 21943 * app code/data to prevent the app from running while you're working. 21944 */ 21945 private class PackageFreezer implements AutoCloseable { 21946 private final String mPackageName; 21947 private final PackageFreezer[] mChildren; 21948 21949 private final boolean mWeFroze; 21950 21951 private final AtomicBoolean mClosed = new AtomicBoolean(); 21952 private final CloseGuard mCloseGuard = CloseGuard.get(); 21953 21954 /** 21955 * Create and return a stub freezer that doesn't actually do anything, 21956 * typically used when someone requested 21957 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21958 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21959 */ 21960 public PackageFreezer() { 21961 mPackageName = null; 21962 mChildren = null; 21963 mWeFroze = false; 21964 mCloseGuard.open("close"); 21965 } 21966 21967 public PackageFreezer(String packageName, int userId, String killReason) { 21968 synchronized (mPackages) { 21969 mPackageName = packageName; 21970 mWeFroze = mFrozenPackages.add(mPackageName); 21971 21972 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21973 if (ps != null) { 21974 killApplication(ps.name, ps.appId, userId, killReason); 21975 } 21976 21977 final PackageParser.Package p = mPackages.get(packageName); 21978 if (p != null && p.childPackages != null) { 21979 final int N = p.childPackages.size(); 21980 mChildren = new PackageFreezer[N]; 21981 for (int i = 0; i < N; i++) { 21982 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21983 userId, killReason); 21984 } 21985 } else { 21986 mChildren = null; 21987 } 21988 } 21989 mCloseGuard.open("close"); 21990 } 21991 21992 @Override 21993 protected void finalize() throws Throwable { 21994 try { 21995 mCloseGuard.warnIfOpen(); 21996 close(); 21997 } finally { 21998 super.finalize(); 21999 } 22000 } 22001 22002 @Override 22003 public void close() { 22004 mCloseGuard.close(); 22005 if (mClosed.compareAndSet(false, true)) { 22006 synchronized (mPackages) { 22007 if (mWeFroze) { 22008 mFrozenPackages.remove(mPackageName); 22009 } 22010 22011 if (mChildren != null) { 22012 for (PackageFreezer freezer : mChildren) { 22013 freezer.close(); 22014 } 22015 } 22016 } 22017 } 22018 } 22019 } 22020 22021 /** 22022 * Verify that given package is currently frozen. 22023 */ 22024 private void checkPackageFrozen(String packageName) { 22025 synchronized (mPackages) { 22026 if (!mFrozenPackages.contains(packageName)) { 22027 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22028 } 22029 } 22030 } 22031 22032 @Override 22033 public int movePackage(final String packageName, final String volumeUuid) { 22034 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22035 22036 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22037 final int moveId = mNextMoveId.getAndIncrement(); 22038 mHandler.post(new Runnable() { 22039 @Override 22040 public void run() { 22041 try { 22042 movePackageInternal(packageName, volumeUuid, moveId, user); 22043 } catch (PackageManagerException e) { 22044 Slog.w(TAG, "Failed to move " + packageName, e); 22045 mMoveCallbacks.notifyStatusChanged(moveId, 22046 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22047 } 22048 } 22049 }); 22050 return moveId; 22051 } 22052 22053 private void movePackageInternal(final String packageName, final String volumeUuid, 22054 final int moveId, UserHandle user) throws PackageManagerException { 22055 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22056 final PackageManager pm = mContext.getPackageManager(); 22057 22058 final boolean currentAsec; 22059 final String currentVolumeUuid; 22060 final File codeFile; 22061 final String installerPackageName; 22062 final String packageAbiOverride; 22063 final int appId; 22064 final String seinfo; 22065 final String label; 22066 final int targetSdkVersion; 22067 final PackageFreezer freezer; 22068 final int[] installedUserIds; 22069 22070 // reader 22071 synchronized (mPackages) { 22072 final PackageParser.Package pkg = mPackages.get(packageName); 22073 final PackageSetting ps = mSettings.mPackages.get(packageName); 22074 if (pkg == null || ps == null) { 22075 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22076 } 22077 22078 if (pkg.applicationInfo.isSystemApp()) { 22079 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22080 "Cannot move system application"); 22081 } 22082 22083 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22084 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22085 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22086 if (isInternalStorage && !allow3rdPartyOnInternal) { 22087 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22088 "3rd party apps are not allowed on internal storage"); 22089 } 22090 22091 if (pkg.applicationInfo.isExternalAsec()) { 22092 currentAsec = true; 22093 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22094 } else if (pkg.applicationInfo.isForwardLocked()) { 22095 currentAsec = true; 22096 currentVolumeUuid = "forward_locked"; 22097 } else { 22098 currentAsec = false; 22099 currentVolumeUuid = ps.volumeUuid; 22100 22101 final File probe = new File(pkg.codePath); 22102 final File probeOat = new File(probe, "oat"); 22103 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22104 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22105 "Move only supported for modern cluster style installs"); 22106 } 22107 } 22108 22109 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22110 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22111 "Package already moved to " + volumeUuid); 22112 } 22113 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22114 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22115 "Device admin cannot be moved"); 22116 } 22117 22118 if (mFrozenPackages.contains(packageName)) { 22119 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22120 "Failed to move already frozen package"); 22121 } 22122 22123 codeFile = new File(pkg.codePath); 22124 installerPackageName = ps.installerPackageName; 22125 packageAbiOverride = ps.cpuAbiOverrideString; 22126 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22127 seinfo = pkg.applicationInfo.seInfo; 22128 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22129 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22130 freezer = freezePackage(packageName, "movePackageInternal"); 22131 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22132 } 22133 22134 final Bundle extras = new Bundle(); 22135 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22136 extras.putString(Intent.EXTRA_TITLE, label); 22137 mMoveCallbacks.notifyCreated(moveId, extras); 22138 22139 int installFlags; 22140 final boolean moveCompleteApp; 22141 final File measurePath; 22142 22143 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22144 installFlags = INSTALL_INTERNAL; 22145 moveCompleteApp = !currentAsec; 22146 measurePath = Environment.getDataAppDirectory(volumeUuid); 22147 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22148 installFlags = INSTALL_EXTERNAL; 22149 moveCompleteApp = false; 22150 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22151 } else { 22152 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22153 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22154 || !volume.isMountedWritable()) { 22155 freezer.close(); 22156 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22157 "Move location not mounted private volume"); 22158 } 22159 22160 Preconditions.checkState(!currentAsec); 22161 22162 installFlags = INSTALL_INTERNAL; 22163 moveCompleteApp = true; 22164 measurePath = Environment.getDataAppDirectory(volumeUuid); 22165 } 22166 22167 final PackageStats stats = new PackageStats(null, -1); 22168 synchronized (mInstaller) { 22169 for (int userId : installedUserIds) { 22170 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22171 freezer.close(); 22172 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22173 "Failed to measure package size"); 22174 } 22175 } 22176 } 22177 22178 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22179 + stats.dataSize); 22180 22181 final long startFreeBytes = measurePath.getFreeSpace(); 22182 final long sizeBytes; 22183 if (moveCompleteApp) { 22184 sizeBytes = stats.codeSize + stats.dataSize; 22185 } else { 22186 sizeBytes = stats.codeSize; 22187 } 22188 22189 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22190 freezer.close(); 22191 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22192 "Not enough free space to move"); 22193 } 22194 22195 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22196 22197 final CountDownLatch installedLatch = new CountDownLatch(1); 22198 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22199 @Override 22200 public void onUserActionRequired(Intent intent) throws RemoteException { 22201 throw new IllegalStateException(); 22202 } 22203 22204 @Override 22205 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22206 Bundle extras) throws RemoteException { 22207 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22208 + PackageManager.installStatusToString(returnCode, msg)); 22209 22210 installedLatch.countDown(); 22211 freezer.close(); 22212 22213 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22214 switch (status) { 22215 case PackageInstaller.STATUS_SUCCESS: 22216 mMoveCallbacks.notifyStatusChanged(moveId, 22217 PackageManager.MOVE_SUCCEEDED); 22218 break; 22219 case PackageInstaller.STATUS_FAILURE_STORAGE: 22220 mMoveCallbacks.notifyStatusChanged(moveId, 22221 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22222 break; 22223 default: 22224 mMoveCallbacks.notifyStatusChanged(moveId, 22225 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22226 break; 22227 } 22228 } 22229 }; 22230 22231 final MoveInfo move; 22232 if (moveCompleteApp) { 22233 // Kick off a thread to report progress estimates 22234 new Thread() { 22235 @Override 22236 public void run() { 22237 while (true) { 22238 try { 22239 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22240 break; 22241 } 22242 } catch (InterruptedException ignored) { 22243 } 22244 22245 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22246 final int progress = 10 + (int) MathUtils.constrain( 22247 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22248 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22249 } 22250 } 22251 }.start(); 22252 22253 final String dataAppName = codeFile.getName(); 22254 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22255 dataAppName, appId, seinfo, targetSdkVersion); 22256 } else { 22257 move = null; 22258 } 22259 22260 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22261 22262 final Message msg = mHandler.obtainMessage(INIT_COPY); 22263 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22264 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22265 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22266 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22267 PackageManager.INSTALL_REASON_UNKNOWN); 22268 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22269 msg.obj = params; 22270 22271 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22272 System.identityHashCode(msg.obj)); 22273 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22274 System.identityHashCode(msg.obj)); 22275 22276 mHandler.sendMessage(msg); 22277 } 22278 22279 @Override 22280 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22281 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22282 22283 final int realMoveId = mNextMoveId.getAndIncrement(); 22284 final Bundle extras = new Bundle(); 22285 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22286 mMoveCallbacks.notifyCreated(realMoveId, extras); 22287 22288 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22289 @Override 22290 public void onCreated(int moveId, Bundle extras) { 22291 // Ignored 22292 } 22293 22294 @Override 22295 public void onStatusChanged(int moveId, int status, long estMillis) { 22296 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22297 } 22298 }; 22299 22300 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22301 storage.setPrimaryStorageUuid(volumeUuid, callback); 22302 return realMoveId; 22303 } 22304 22305 @Override 22306 public int getMoveStatus(int moveId) { 22307 mContext.enforceCallingOrSelfPermission( 22308 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22309 return mMoveCallbacks.mLastStatus.get(moveId); 22310 } 22311 22312 @Override 22313 public void registerMoveCallback(IPackageMoveObserver callback) { 22314 mContext.enforceCallingOrSelfPermission( 22315 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22316 mMoveCallbacks.register(callback); 22317 } 22318 22319 @Override 22320 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22321 mContext.enforceCallingOrSelfPermission( 22322 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22323 mMoveCallbacks.unregister(callback); 22324 } 22325 22326 @Override 22327 public boolean setInstallLocation(int loc) { 22328 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22329 null); 22330 if (getInstallLocation() == loc) { 22331 return true; 22332 } 22333 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22334 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22335 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22336 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22337 return true; 22338 } 22339 return false; 22340 } 22341 22342 @Override 22343 public int getInstallLocation() { 22344 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22345 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22346 PackageHelper.APP_INSTALL_AUTO); 22347 } 22348 22349 /** Called by UserManagerService */ 22350 void cleanUpUser(UserManagerService userManager, int userHandle) { 22351 synchronized (mPackages) { 22352 mDirtyUsers.remove(userHandle); 22353 mUserNeedsBadging.delete(userHandle); 22354 mSettings.removeUserLPw(userHandle); 22355 mPendingBroadcasts.remove(userHandle); 22356 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22357 removeUnusedPackagesLPw(userManager, userHandle); 22358 } 22359 } 22360 22361 /** 22362 * We're removing userHandle and would like to remove any downloaded packages 22363 * that are no longer in use by any other user. 22364 * @param userHandle the user being removed 22365 */ 22366 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22367 final boolean DEBUG_CLEAN_APKS = false; 22368 int [] users = userManager.getUserIds(); 22369 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22370 while (psit.hasNext()) { 22371 PackageSetting ps = psit.next(); 22372 if (ps.pkg == null) { 22373 continue; 22374 } 22375 final String packageName = ps.pkg.packageName; 22376 // Skip over if system app 22377 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22378 continue; 22379 } 22380 if (DEBUG_CLEAN_APKS) { 22381 Slog.i(TAG, "Checking package " + packageName); 22382 } 22383 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22384 if (keep) { 22385 if (DEBUG_CLEAN_APKS) { 22386 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22387 } 22388 } else { 22389 for (int i = 0; i < users.length; i++) { 22390 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22391 keep = true; 22392 if (DEBUG_CLEAN_APKS) { 22393 Slog.i(TAG, " Keeping package " + packageName + " for user " 22394 + users[i]); 22395 } 22396 break; 22397 } 22398 } 22399 } 22400 if (!keep) { 22401 if (DEBUG_CLEAN_APKS) { 22402 Slog.i(TAG, " Removing package " + packageName); 22403 } 22404 mHandler.post(new Runnable() { 22405 public void run() { 22406 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22407 userHandle, 0); 22408 } //end run 22409 }); 22410 } 22411 } 22412 } 22413 22414 /** Called by UserManagerService */ 22415 void createNewUser(int userId, String[] disallowedPackages) { 22416 synchronized (mInstallLock) { 22417 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22418 } 22419 synchronized (mPackages) { 22420 scheduleWritePackageRestrictionsLocked(userId); 22421 scheduleWritePackageListLocked(userId); 22422 applyFactoryDefaultBrowserLPw(userId); 22423 primeDomainVerificationsLPw(userId); 22424 } 22425 } 22426 22427 void onNewUserCreated(final int userId) { 22428 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22429 // If permission review for legacy apps is required, we represent 22430 // dagerous permissions for such apps as always granted runtime 22431 // permissions to keep per user flag state whether review is needed. 22432 // Hence, if a new user is added we have to propagate dangerous 22433 // permission grants for these legacy apps. 22434 if (mPermissionReviewRequired) { 22435 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22436 | UPDATE_PERMISSIONS_REPLACE_ALL); 22437 } 22438 } 22439 22440 @Override 22441 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22442 mContext.enforceCallingOrSelfPermission( 22443 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22444 "Only package verification agents can read the verifier device identity"); 22445 22446 synchronized (mPackages) { 22447 return mSettings.getVerifierDeviceIdentityLPw(); 22448 } 22449 } 22450 22451 @Override 22452 public void setPermissionEnforced(String permission, boolean enforced) { 22453 // TODO: Now that we no longer change GID for storage, this should to away. 22454 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22455 "setPermissionEnforced"); 22456 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22457 synchronized (mPackages) { 22458 if (mSettings.mReadExternalStorageEnforced == null 22459 || mSettings.mReadExternalStorageEnforced != enforced) { 22460 mSettings.mReadExternalStorageEnforced = enforced; 22461 mSettings.writeLPr(); 22462 } 22463 } 22464 // kill any non-foreground processes so we restart them and 22465 // grant/revoke the GID. 22466 final IActivityManager am = ActivityManager.getService(); 22467 if (am != null) { 22468 final long token = Binder.clearCallingIdentity(); 22469 try { 22470 am.killProcessesBelowForeground("setPermissionEnforcement"); 22471 } catch (RemoteException e) { 22472 } finally { 22473 Binder.restoreCallingIdentity(token); 22474 } 22475 } 22476 } else { 22477 throw new IllegalArgumentException("No selective enforcement for " + permission); 22478 } 22479 } 22480 22481 @Override 22482 @Deprecated 22483 public boolean isPermissionEnforced(String permission) { 22484 return true; 22485 } 22486 22487 @Override 22488 public boolean isStorageLow() { 22489 final long token = Binder.clearCallingIdentity(); 22490 try { 22491 final DeviceStorageMonitorInternal 22492 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22493 if (dsm != null) { 22494 return dsm.isMemoryLow(); 22495 } else { 22496 return false; 22497 } 22498 } finally { 22499 Binder.restoreCallingIdentity(token); 22500 } 22501 } 22502 22503 @Override 22504 public IPackageInstaller getPackageInstaller() { 22505 return mInstallerService; 22506 } 22507 22508 private boolean userNeedsBadging(int userId) { 22509 int index = mUserNeedsBadging.indexOfKey(userId); 22510 if (index < 0) { 22511 final UserInfo userInfo; 22512 final long token = Binder.clearCallingIdentity(); 22513 try { 22514 userInfo = sUserManager.getUserInfo(userId); 22515 } finally { 22516 Binder.restoreCallingIdentity(token); 22517 } 22518 final boolean b; 22519 if (userInfo != null && userInfo.isManagedProfile()) { 22520 b = true; 22521 } else { 22522 b = false; 22523 } 22524 mUserNeedsBadging.put(userId, b); 22525 return b; 22526 } 22527 return mUserNeedsBadging.valueAt(index); 22528 } 22529 22530 @Override 22531 public KeySet getKeySetByAlias(String packageName, String alias) { 22532 if (packageName == null || alias == null) { 22533 return null; 22534 } 22535 synchronized(mPackages) { 22536 final PackageParser.Package pkg = mPackages.get(packageName); 22537 if (pkg == null) { 22538 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22539 throw new IllegalArgumentException("Unknown package: " + packageName); 22540 } 22541 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22542 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22543 } 22544 } 22545 22546 @Override 22547 public KeySet getSigningKeySet(String packageName) { 22548 if (packageName == null) { 22549 return null; 22550 } 22551 synchronized(mPackages) { 22552 final PackageParser.Package pkg = mPackages.get(packageName); 22553 if (pkg == null) { 22554 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22555 throw new IllegalArgumentException("Unknown package: " + packageName); 22556 } 22557 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22558 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22559 throw new SecurityException("May not access signing KeySet of other apps."); 22560 } 22561 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22562 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22563 } 22564 } 22565 22566 @Override 22567 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22568 if (packageName == null || ks == null) { 22569 return false; 22570 } 22571 synchronized(mPackages) { 22572 final PackageParser.Package pkg = mPackages.get(packageName); 22573 if (pkg == null) { 22574 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22575 throw new IllegalArgumentException("Unknown package: " + packageName); 22576 } 22577 IBinder ksh = ks.getToken(); 22578 if (ksh instanceof KeySetHandle) { 22579 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22580 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22581 } 22582 return false; 22583 } 22584 } 22585 22586 @Override 22587 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22588 if (packageName == null || ks == null) { 22589 return false; 22590 } 22591 synchronized(mPackages) { 22592 final PackageParser.Package pkg = mPackages.get(packageName); 22593 if (pkg == null) { 22594 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22595 throw new IllegalArgumentException("Unknown package: " + packageName); 22596 } 22597 IBinder ksh = ks.getToken(); 22598 if (ksh instanceof KeySetHandle) { 22599 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22600 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22601 } 22602 return false; 22603 } 22604 } 22605 22606 private void deletePackageIfUnusedLPr(final String packageName) { 22607 PackageSetting ps = mSettings.mPackages.get(packageName); 22608 if (ps == null) { 22609 return; 22610 } 22611 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22612 // TODO Implement atomic delete if package is unused 22613 // It is currently possible that the package will be deleted even if it is installed 22614 // after this method returns. 22615 mHandler.post(new Runnable() { 22616 public void run() { 22617 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22618 0, PackageManager.DELETE_ALL_USERS); 22619 } 22620 }); 22621 } 22622 } 22623 22624 /** 22625 * Check and throw if the given before/after packages would be considered a 22626 * downgrade. 22627 */ 22628 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22629 throws PackageManagerException { 22630 if (after.versionCode < before.mVersionCode) { 22631 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22632 "Update version code " + after.versionCode + " is older than current " 22633 + before.mVersionCode); 22634 } else if (after.versionCode == before.mVersionCode) { 22635 if (after.baseRevisionCode < before.baseRevisionCode) { 22636 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22637 "Update base revision code " + after.baseRevisionCode 22638 + " is older than current " + before.baseRevisionCode); 22639 } 22640 22641 if (!ArrayUtils.isEmpty(after.splitNames)) { 22642 for (int i = 0; i < after.splitNames.length; i++) { 22643 final String splitName = after.splitNames[i]; 22644 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22645 if (j != -1) { 22646 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22647 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22648 "Update split " + splitName + " revision code " 22649 + after.splitRevisionCodes[i] + " is older than current " 22650 + before.splitRevisionCodes[j]); 22651 } 22652 } 22653 } 22654 } 22655 } 22656 } 22657 22658 private static class MoveCallbacks extends Handler { 22659 private static final int MSG_CREATED = 1; 22660 private static final int MSG_STATUS_CHANGED = 2; 22661 22662 private final RemoteCallbackList<IPackageMoveObserver> 22663 mCallbacks = new RemoteCallbackList<>(); 22664 22665 private final SparseIntArray mLastStatus = new SparseIntArray(); 22666 22667 public MoveCallbacks(Looper looper) { 22668 super(looper); 22669 } 22670 22671 public void register(IPackageMoveObserver callback) { 22672 mCallbacks.register(callback); 22673 } 22674 22675 public void unregister(IPackageMoveObserver callback) { 22676 mCallbacks.unregister(callback); 22677 } 22678 22679 @Override 22680 public void handleMessage(Message msg) { 22681 final SomeArgs args = (SomeArgs) msg.obj; 22682 final int n = mCallbacks.beginBroadcast(); 22683 for (int i = 0; i < n; i++) { 22684 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22685 try { 22686 invokeCallback(callback, msg.what, args); 22687 } catch (RemoteException ignored) { 22688 } 22689 } 22690 mCallbacks.finishBroadcast(); 22691 args.recycle(); 22692 } 22693 22694 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22695 throws RemoteException { 22696 switch (what) { 22697 case MSG_CREATED: { 22698 callback.onCreated(args.argi1, (Bundle) args.arg2); 22699 break; 22700 } 22701 case MSG_STATUS_CHANGED: { 22702 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22703 break; 22704 } 22705 } 22706 } 22707 22708 private void notifyCreated(int moveId, Bundle extras) { 22709 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22710 22711 final SomeArgs args = SomeArgs.obtain(); 22712 args.argi1 = moveId; 22713 args.arg2 = extras; 22714 obtainMessage(MSG_CREATED, args).sendToTarget(); 22715 } 22716 22717 private void notifyStatusChanged(int moveId, int status) { 22718 notifyStatusChanged(moveId, status, -1); 22719 } 22720 22721 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22722 Slog.v(TAG, "Move " + moveId + " status " + status); 22723 22724 final SomeArgs args = SomeArgs.obtain(); 22725 args.argi1 = moveId; 22726 args.argi2 = status; 22727 args.arg3 = estMillis; 22728 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22729 22730 synchronized (mLastStatus) { 22731 mLastStatus.put(moveId, status); 22732 } 22733 } 22734 } 22735 22736 private final static class OnPermissionChangeListeners extends Handler { 22737 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22738 22739 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22740 new RemoteCallbackList<>(); 22741 22742 public OnPermissionChangeListeners(Looper looper) { 22743 super(looper); 22744 } 22745 22746 @Override 22747 public void handleMessage(Message msg) { 22748 switch (msg.what) { 22749 case MSG_ON_PERMISSIONS_CHANGED: { 22750 final int uid = msg.arg1; 22751 handleOnPermissionsChanged(uid); 22752 } break; 22753 } 22754 } 22755 22756 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22757 mPermissionListeners.register(listener); 22758 22759 } 22760 22761 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22762 mPermissionListeners.unregister(listener); 22763 } 22764 22765 public void onPermissionsChanged(int uid) { 22766 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22767 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22768 } 22769 } 22770 22771 private void handleOnPermissionsChanged(int uid) { 22772 final int count = mPermissionListeners.beginBroadcast(); 22773 try { 22774 for (int i = 0; i < count; i++) { 22775 IOnPermissionsChangeListener callback = mPermissionListeners 22776 .getBroadcastItem(i); 22777 try { 22778 callback.onPermissionsChanged(uid); 22779 } catch (RemoteException e) { 22780 Log.e(TAG, "Permission listener is dead", e); 22781 } 22782 } 22783 } finally { 22784 mPermissionListeners.finishBroadcast(); 22785 } 22786 } 22787 } 22788 22789 private class PackageManagerInternalImpl extends PackageManagerInternal { 22790 @Override 22791 public void setLocationPackagesProvider(PackagesProvider provider) { 22792 synchronized (mPackages) { 22793 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22794 } 22795 } 22796 22797 @Override 22798 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22799 synchronized (mPackages) { 22800 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22801 } 22802 } 22803 22804 @Override 22805 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22806 synchronized (mPackages) { 22807 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22808 } 22809 } 22810 22811 @Override 22812 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22813 synchronized (mPackages) { 22814 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22815 } 22816 } 22817 22818 @Override 22819 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22820 synchronized (mPackages) { 22821 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22822 } 22823 } 22824 22825 @Override 22826 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22827 synchronized (mPackages) { 22828 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22829 } 22830 } 22831 22832 @Override 22833 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22834 synchronized (mPackages) { 22835 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22836 packageName, userId); 22837 } 22838 } 22839 22840 @Override 22841 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22842 synchronized (mPackages) { 22843 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22844 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22845 packageName, userId); 22846 } 22847 } 22848 22849 @Override 22850 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22851 synchronized (mPackages) { 22852 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22853 packageName, userId); 22854 } 22855 } 22856 22857 @Override 22858 public void setKeepUninstalledPackages(final List<String> packageList) { 22859 Preconditions.checkNotNull(packageList); 22860 List<String> removedFromList = null; 22861 synchronized (mPackages) { 22862 if (mKeepUninstalledPackages != null) { 22863 final int packagesCount = mKeepUninstalledPackages.size(); 22864 for (int i = 0; i < packagesCount; i++) { 22865 String oldPackage = mKeepUninstalledPackages.get(i); 22866 if (packageList != null && packageList.contains(oldPackage)) { 22867 continue; 22868 } 22869 if (removedFromList == null) { 22870 removedFromList = new ArrayList<>(); 22871 } 22872 removedFromList.add(oldPackage); 22873 } 22874 } 22875 mKeepUninstalledPackages = new ArrayList<>(packageList); 22876 if (removedFromList != null) { 22877 final int removedCount = removedFromList.size(); 22878 for (int i = 0; i < removedCount; i++) { 22879 deletePackageIfUnusedLPr(removedFromList.get(i)); 22880 } 22881 } 22882 } 22883 } 22884 22885 @Override 22886 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22887 synchronized (mPackages) { 22888 // If we do not support permission review, done. 22889 if (!mPermissionReviewRequired) { 22890 return false; 22891 } 22892 22893 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22894 if (packageSetting == null) { 22895 return false; 22896 } 22897 22898 // Permission review applies only to apps not supporting the new permission model. 22899 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22900 return false; 22901 } 22902 22903 // Legacy apps have the permission and get user consent on launch. 22904 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22905 return permissionsState.isPermissionReviewRequired(userId); 22906 } 22907 } 22908 22909 @Override 22910 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22911 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22912 } 22913 22914 @Override 22915 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22916 int userId) { 22917 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22918 } 22919 22920 @Override 22921 public void setDeviceAndProfileOwnerPackages( 22922 int deviceOwnerUserId, String deviceOwnerPackage, 22923 SparseArray<String> profileOwnerPackages) { 22924 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22925 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22926 } 22927 22928 @Override 22929 public boolean isPackageDataProtected(int userId, String packageName) { 22930 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22931 } 22932 22933 @Override 22934 public boolean isPackageEphemeral(int userId, String packageName) { 22935 synchronized (mPackages) { 22936 final PackageSetting ps = mSettings.mPackages.get(packageName); 22937 return ps != null ? ps.getInstantApp(userId) : false; 22938 } 22939 } 22940 22941 @Override 22942 public boolean wasPackageEverLaunched(String packageName, int userId) { 22943 synchronized (mPackages) { 22944 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22945 } 22946 } 22947 22948 @Override 22949 public void grantRuntimePermission(String packageName, String name, int userId, 22950 boolean overridePolicy) { 22951 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22952 overridePolicy); 22953 } 22954 22955 @Override 22956 public void revokeRuntimePermission(String packageName, String name, int userId, 22957 boolean overridePolicy) { 22958 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22959 overridePolicy); 22960 } 22961 22962 @Override 22963 public String getNameForUid(int uid) { 22964 return PackageManagerService.this.getNameForUid(uid); 22965 } 22966 22967 @Override 22968 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 22969 Intent origIntent, String resolvedType, String callingPackage, int userId) { 22970 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 22971 responseObj, origIntent, resolvedType, callingPackage, userId); 22972 } 22973 22974 @Override 22975 public void grantEphemeralAccess(int userId, Intent intent, 22976 int targetAppId, int ephemeralAppId) { 22977 synchronized (mPackages) { 22978 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 22979 targetAppId, ephemeralAppId); 22980 } 22981 } 22982 22983 @Override 22984 public void pruneInstantApps() { 22985 synchronized (mPackages) { 22986 mInstantAppRegistry.pruneInstantAppsLPw(); 22987 } 22988 } 22989 22990 @Override 22991 public String getSetupWizardPackageName() { 22992 return mSetupWizardPackage; 22993 } 22994 22995 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22996 if (policy != null) { 22997 mExternalSourcesPolicy = policy; 22998 } 22999 } 23000 23001 @Override 23002 public boolean isPackagePersistent(String packageName) { 23003 synchronized (mPackages) { 23004 PackageParser.Package pkg = mPackages.get(packageName); 23005 return pkg != null 23006 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23007 | ApplicationInfo.FLAG_PERSISTENT)) == 23008 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23009 : false; 23010 } 23011 } 23012 23013 @Override 23014 public List<PackageInfo> getOverlayPackages(int userId) { 23015 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23016 synchronized (mPackages) { 23017 for (PackageParser.Package p : mPackages.values()) { 23018 if (p.mOverlayTarget != null) { 23019 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23020 if (pkg != null) { 23021 overlayPackages.add(pkg); 23022 } 23023 } 23024 } 23025 } 23026 return overlayPackages; 23027 } 23028 23029 @Override 23030 public List<String> getTargetPackageNames(int userId) { 23031 List<String> targetPackages = new ArrayList<>(); 23032 synchronized (mPackages) { 23033 for (PackageParser.Package p : mPackages.values()) { 23034 if (p.mOverlayTarget == null) { 23035 targetPackages.add(p.packageName); 23036 } 23037 } 23038 } 23039 return targetPackages; 23040 } 23041 23042 @Override 23043 public boolean setEnabledOverlayPackages(int userId, String targetPackageName, 23044 List<String> overlayPackageNames) { 23045 // TODO: implement when we integrate OMS properly 23046 return false; 23047 } 23048 23049 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23050 int flags, int userId) { 23051 return resolveIntentInternal( 23052 intent, resolvedType, flags, userId, true /*includeInstantApp*/); 23053 } 23054 } 23055 23056 @Override 23057 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23058 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23059 synchronized (mPackages) { 23060 final long identity = Binder.clearCallingIdentity(); 23061 try { 23062 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23063 packageNames, userId); 23064 } finally { 23065 Binder.restoreCallingIdentity(identity); 23066 } 23067 } 23068 } 23069 23070 @Override 23071 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23072 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23073 synchronized (mPackages) { 23074 final long identity = Binder.clearCallingIdentity(); 23075 try { 23076 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23077 packageNames, userId); 23078 } finally { 23079 Binder.restoreCallingIdentity(identity); 23080 } 23081 } 23082 } 23083 23084 private static void enforceSystemOrPhoneCaller(String tag) { 23085 int callingUid = Binder.getCallingUid(); 23086 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23087 throw new SecurityException( 23088 "Cannot call " + tag + " from UID " + callingUid); 23089 } 23090 } 23091 23092 boolean isHistoricalPackageUsageAvailable() { 23093 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23094 } 23095 23096 /** 23097 * Return a <b>copy</b> of the collection of packages known to the package manager. 23098 * @return A copy of the values of mPackages. 23099 */ 23100 Collection<PackageParser.Package> getPackages() { 23101 synchronized (mPackages) { 23102 return new ArrayList<>(mPackages.values()); 23103 } 23104 } 23105 23106 /** 23107 * Logs process start information (including base APK hash) to the security log. 23108 * @hide 23109 */ 23110 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23111 String apkFile, int pid) { 23112 if (!SecurityLog.isLoggingEnabled()) { 23113 return; 23114 } 23115 Bundle data = new Bundle(); 23116 data.putLong("startTimestamp", System.currentTimeMillis()); 23117 data.putString("processName", processName); 23118 data.putInt("uid", uid); 23119 data.putString("seinfo", seinfo); 23120 data.putString("apkFile", apkFile); 23121 data.putInt("pid", pid); 23122 Message msg = mProcessLoggingHandler.obtainMessage( 23123 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23124 msg.setData(data); 23125 mProcessLoggingHandler.sendMessage(msg); 23126 } 23127 23128 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23129 return mCompilerStats.getPackageStats(pkgName); 23130 } 23131 23132 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23133 return getOrCreateCompilerPackageStats(pkg.packageName); 23134 } 23135 23136 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23137 return mCompilerStats.getOrCreatePackageStats(pkgName); 23138 } 23139 23140 public void deleteCompilerPackageStats(String pkgName) { 23141 mCompilerStats.deletePackageStats(pkgName); 23142 } 23143 23144 @Override 23145 public int getInstallReason(String packageName, int userId) { 23146 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23147 true /* requireFullPermission */, false /* checkShell */, 23148 "get install reason"); 23149 synchronized (mPackages) { 23150 final PackageSetting ps = mSettings.mPackages.get(packageName); 23151 if (ps != null) { 23152 return ps.getInstallReason(userId); 23153 } 23154 } 23155 return PackageManager.INSTALL_REASON_UNKNOWN; 23156 } 23157 23158 @Override 23159 public boolean canRequestPackageInstalls(String packageName, int userId) { 23160 int callingUid = Binder.getCallingUid(); 23161 int uid = getPackageUid(packageName, 0, userId); 23162 if (callingUid != uid && callingUid != Process.ROOT_UID 23163 && callingUid != Process.SYSTEM_UID) { 23164 throw new SecurityException( 23165 "Caller uid " + callingUid + " does not own package " + packageName); 23166 } 23167 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23168 if (info == null) { 23169 return false; 23170 } 23171 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23172 throw new UnsupportedOperationException( 23173 "Operation only supported on apps targeting Android O or higher"); 23174 } 23175 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23176 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23177 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23178 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23179 } 23180 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23181 return false; 23182 } 23183 if (mExternalSourcesPolicy != null) { 23184 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23185 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23186 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23187 } 23188 } 23189 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23190 } 23191} 23192